# Question
Title: In SDL2, how do I determine if a key was pressed or released this frame?
Determining if a key is currently down is easy. Just return `keys[scancode]`:

```
switch (ev.type) {
    case SDL_KEYDOWN:
        keys[ev.key.keysym.scancode] = true;
        break;
    case SDL_KEYUP:
        keys[ev.key.keysym.scancode] = false;
        break;
}

```

Determining if a key was pressed or released this frame is another thing. I just don't know where to start here. It would be accessed by `keyPressed(scancode)` / `keyReleased(scancode)`, what's a good way to do this?

Of course it would also be easy to do if I just handled it inside of the event handler itself but I'm just using functions anything can call to check the keys.

# Answer
> 4 votes
Store the keys from the last frame and compare in the current frame.

```
if(!old_keys[key] && keys[key]) { /* pressed since last frame */ }
if(old_keys[key] && !keys[key]) { /* released since last frame */ }
if(old_keys[key] && keys[key]) { /* held since last frame */ }

```

# Answer
> 0 votes
If you have to handle a large set of keys have a look at:

```
SDL_GetKeyState

```

which gives you a snapshot of the state of the whole keyboard.

# Answer
> 0 votes
Instead of true/false I use a value of 2/-2 for a recent change (2 for a new press, -2 for a new release), then at the beginning of the loop, before going through the new events I go through the whole array and change every 2 or -2 to 1 or -1. I use 3 in case of a key repeat, so I can handle all those different things in the rest of my code smoothly. So if I test the key for ==2 it means only new presses, if I test for \>=2 it means new presses and repeats, \>=1 is if it's down at all and so on.

But if you don't want to directly use numbers (probably best not to if other people need to understand your code) you can use the following enum:

```
enum
{
    KEYUP_NEW = -2,
    KEYUP,
    KEY_UNINIT,
    KEYDOWN,
    KEYDOWN_NEW,
    KEYDOWN_REPEAT
};

```

and then you only have to test for `if (keys[key]==KEYDOWN_NEW)` instead of the less readable `if (!old_keys[key] && keys[key])` whose meaning isn't as instantly obvious. You can even go one better by having a function do the test for you so that `test_key(key, KEYDOWN)` or `is_key_down(key)` can return positive whether the value is KEYDOWN, KEYDOWN\_NEW or KEYDOWN\_REPEAT if you don't want to use the less obvious `if (keys[key]>=KEYDOWN)`.

But there's a big problem with your approach, it's that you'll miss keypresses that last shorter than your average loop because in those cases you'll have a down event instantly followed by a up event, and therefore your table as seen from outside of the event polling loop will miss the keypress entirely. I have a solution for this, it's to have another table and when you detect a down event while your entry in your table is 2 then don't change it to -2 but rather set the matching entry in that other table to 1. This way for that one iteration of the loop your key is set to 2, which is what you want. Then when the next loop starts, at the same time as you turn 2s into 1s you check that other table and if it's set to 1 then you turn the 2 into a -2 so that you signal the release.

---
Tags: c++, input, sdl2
---


# Question
Title: GameObject With Background Covers GameObject Without Background
so I have two sprites, a box and an X animation (I'm making Tic-Tac-Toe). So, in the code, when I click on the box, it instantiates the X animation at the right place. The X animation does not have a background, but the box does. However, when it instantiates, it puts it *behind* the box.

This doesn't make sense to me, but even when I move it around in the editor, moving it across the box puts it behind it. Which is interesting, since neither have layers. And even when I do put layers on (a higher layer on the X animation), it still goes behind. Take a look:

Any ideas on why this is happening, and how I can fix it?

**EDIT:** Here's my hierarchy and inspector:

# Answer
Though I'm not sure why, I tried messing around, and putting the Z-radius of the X Animation *behind* the box, it actually showed up in front of it (with the Z-radius of the X animation being -2 and the box being 0).
> 1 votes

# Answer
From your edit, it looks like you’ve selected the X animation GameObject. I see that it’s on the Default sorting layer. See SpriteRenderer component’s layer. If you have multiple layers, put the X animation on the a foreground layer. You can create new layers if you don’t have any.

If you are not able to create/use a different layer due to some reason, you can change the Order in Layer property of the SpriteRenderer component. It is currently set to 0. You can try changing it to 1 or more.

Putting the X animation slightly closer towards the camera, meaning a slight negative offset than the box, will also work. But remember, if you move the X animation in z axis, and you’re using a perspective camera, the result might not be what you are looking for. I would prefer doing it in either of the 2 above mentioned ways
> 0 votes

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


title: Space nebula cloud generation?

text:
# Question
Title: Space nebula cloud generation?
I found a cool kickstarter project called "Skywanders". It's an minecraft like space game with a lego like building system and pretty cool graphics.

One thing I noticed are the "nebula clouds". They are procedurally generated 3D Objects and they look amazing.

How do I generate such nebulas? I bet there's a way to do that. And is it possible to convert a 2D nebula into a 3D one? I didn't found any algorithm yet or other sources.

# Answer
I've done something similar in the past through glsl's Fragment Shaders:

https://www.shadertoy.com/view/lsyfWy

And a Processing version:

https://github.com/felipunky/Stars

It is basically a Fractional Brownian Motion or several layers of noise at different frequencies and amplitudes stacked together:

```
#define HASHSCALE .1031
// We create the pseudo-random number generator.
// https://www.shadertoy.com/view/4djSRW
float hash(float p)
{

    vec3 p3  = fract(vec3(p) * HASHSCALE);
    p3 += dot(p3, p3.yzx + 19.19);
    return fract((p3.x + p3.y) * p3.z);

}

// This function is by @Inigo Quilez.
// We create the 3D noise by generating pseudo-random numbers in the x, y and z directions and then interpolating between them.
float noise( in vec3 x )
{

    vec3 p = floor( x );
    vec3 k = fract( x );

    k *= k * k * ( 3.0 - 2.0 * k );

    float n = p.x + p.y * 57.0 + p.z * 113.0;

    float a = hash( n );
    float b = hash( n + 1.0 );
    float c = hash( n + 57.0 );
    float d = hash( n + 58.0 );

    float e = hash( n + 113.0 );
    float f = hash( n + 114.0 );
    float g = hash( n + 170.0 );
    float h = hash( n + 171.0 );

    float res = mix( mix( mix ( a, b, k.x ), mix( c, d, k.x ), k.y ),
                 mix( mix ( e, f, k.x ), mix( g, h, k.x ), k.y ),
                 k.z
                 );

    return res;

}

// Here we do the stacking of noise at different octaves.
float fbm( in vec3 p )
{

    float f = 0.0;
    f += 0.5000 * noise( p ); p *= 2.02; p -= iTime * 0.5;
    f += 0.2500 * noise( p ); p *= 2.03; p += iTime * 0.4;
    f += 0.1250 * noise( p ); p *= 2.01; p -= iTime * 0.5;
    f += 0.0625 * noise( p );
    f += 0.0125 * noise( p );
    return f / 0.9375;

}

```

I find this fbm function more readable and easier to tweak:

```
float fbm( in vec3 p )
{

    float res = 0.0, fre = 1.0, amp = 1.0, div = 0.0;

    for( int i = 0; i < 5; ++i )
    {

        res += amp * noise( p * fre );
        div += amp;
        amp *= 0.7;
        fre *= 1.7;

    }

    res /= div;

    return res;

}

```

Rendered through a Sphere Tracing Algorithm that accumulates for a volumetric look:

```
// This is our ray marching algorithm.
float ray( vec3 ro, vec3 rd, out float den )
{

    float t = 0.0, maxD = 0.0, d = 1.0; den = 0.0;

    // The more STEPS the more accurate the marching.
    for( int i = 0; i < STEPS; ++i )
    {

        // Here we compute our Position p by the formula RayOrigin + RayDirection * our RayMarchStep.
        vec3 p = ro + rd * t;

        // This is our density, it is simply calling the Fractional Brownian Motion fbm function.
        den = fbm( p );

        // This allows us to put a limit in our accumulation of density.
        maxD = maxD < den ? den : maxD;

        // Here we bail on our marching according to MaximumDensity or our FAR threshold.
        if( maxD > 1.0 || t > FAR ) break;

       // We increment our RayMarchingSteps.
        t += 0.05;

    }

    den = maxD;

    return t;

}

```
> 4 votes

# Answer
You could use noise generation (Perlin, Value or Gradient are amongst the most popular). Either that or use techniques such as this: Procedurally Generated Nebulae in Unity3D

Otherwise using billboard rendered objects or something similar is probably your best bet. Especially when you want them to be 3D. You could potentially look into Z depth techniques (volumetric rendering), but this is an expensive process. So as far as entire nebula's go... Anyway, this should get you started.
> 2 votes

# Answer
So in general, you have two basic components to a nebula (from the visual side).

**A: The silhouette:**

To generate a random silhouette, I'd look into cellular automata. This process is often used to generate "natural" random structures (think caves).

Here's a decent series on how that can be done. It's in unity, but the principles are the same everywhere else. https://www.youtube.com/watch?v=v7yyZZjF1z4

**B: The texture:**

You can probably "get away" with using several layers of perlin noise with various blend modes to get the right amount of color variation.

---

**Putting it all together:**

Once you have your shape and noise maps, it's fairly straightforward to assign colors to regions and intensities using color ramp textures.

---

**Bringing it to 3d** Good news is that each of the processing can be extended into 3D. The rules get a little more complex, but it's pretty straightforward.

Resource for 3D noise generation: https://en.wikipedia.org/wiki/Simplex\_noise http://catlikecoding.com/unity/tutorials/simplex-noise/ (unity, but universally applicable) https://developer.nvidia.com/gpugems/GPUGems3/gpugems3\_ch01.html (speifically section 1.3.3)

3D cellular automata is very straightforward, the rules don't change, you just add more neighbors to consider.
> 1 votes

---
Tags: algorithm, graphics, procedural-generation
---


# Question
Title: Why do I get an unexpexted token error while compiling this shader?
I get the following error

> syntax error unexpected token vertex

I am still learning shaders so I can't really understand the reason for this error. How can I make this shader work?

```
enter Shader "Custom/VertAnimShader"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
        _PosTex("Position texture", 2D) = "black" {}
        _NmlTex("Normal texture", 2D) = "white" {}
        _Length("Animator lengh", float) = 1
        _DT("Delta time", float) = 0
    }

    SubShader{
        Pass{
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma debug
            #include "UnityCG.cginc"

            #define ts _PosTex_TexelSize

            struct appdata
            {
                float2 uv : TEXTCOORD0;
            };

            struct v2f {
                float2 uv : TEXTCOORD0;
                float3 normal: TEXTCOORD1;
                float4  vertex : SV_POSITION;
            };

            sampler2D _MainTex, _PosTex, _NmlTex;
            float4 _PosTex_TexelSize;
            float _Length, _DT;

            v2f vert(appdata v, uint vid: SV_VertexID)
            {
                float t = (_Time.y - _DT) / _Length;
                t = fmod(t, 1.0);
                float x = (vid + 0.5) * ts.x;
                float y = t;
                float4 pos = tex2Dlod(_PosTex, float4(x, y, 0, 0));
                float4 normal = tex2Dlod(_NmlTex, float4(x, y, 0, 0));
                v2f o;
                o.vertex = UnityObjectToClipPos(pos);
                o.normal = UnityObjectToWorldNormal(normal);
                o.uv = v.uv;
                return o;
            }

            half4 frag(v2f i) : SV_TARGET
            {
                half diff = dot(i.normal, float3(0,1,0))*0.5 + 0.5;
                half4 col = tex2D(_MainTex, i.uv);
                return diff * col;
            }
            ENDCG
        }
    }
}

```

# Answer
```
struct v2f {
    float2 uv : TEXTCOORD0;
    float3 normal: TEXTCOORD1;
    float4 position vertex : SV_POSITION;
};

```

There is a mistake in the last line, it needs to be

```
struct v2f {
    float2 uv : TEXCOORD0;
    float3 normal: TEXCOORD1;
    float4 vertex : SV_POSITION;
};

```

Also note that `TEXTCOORD` needs to be spelled `TEXCOORD`. The tutorial you are using seems to be quite terrible.

This is correctly written later in the tutorial.

In addition, you are missing a semicolon in the function `vert`: The line

```
o.uv = v.uv

```

needs to be

```
o.uv = v.uv;

```

As of why `ts` is not defined, it's because you are missing a space character in your `#define`:

```
#define TS_PosTex_TexelSize

```

needs to be `#define TS _PosTex_TexelSize`.
> 2 votes

---
Tags: unity, shaders
---


# Question
Title: Can Unity censor my content or invalidate my license for offensive content?
If I make an offensive game can they pull my license and prevent me from selling my game? Like we're talking think of the most offensive thing you can think of: you're in charge of the most efficient genocide against some specific racial/religious/political group, your choice... now imagine the game is mocking victims and generally being extremely rude, violent, and insensitive.

Now ***I have no intention of making such a horrible game*** but I am using an extreme example to ask my question. It's not unheard of for less extreme things to get blocked by brands who didn't want to associate with them, for example I saw that Apple removed the Confederate flags from Civil War games in the App Store.

Would Unity be able to prevent me from using their game engine or selling my game after I had already purchased appropriate Unity licenses and completed the game?

Do they have that kind of power with their licensing model? Or would even the most extreme cases still be legally allowed to sell the content?

I want to make something that may have some mildly provocative/divisive content (not as offensive as say, South Park, which I know was made in Unity, but more serious than South Park) and I'm just making sure I don't get a bunch of work done and then get disappointed later, wishing I had gone with some kind of more free/open engine.

# Answer
> 2 votes
The current Unity license terms only want you to "comply with all applicable laws and regulations". So as long as your game is still within the legal limits of what you are allowed to publish, you are not violating the license agreement.

As the answer by Pako88 points out, Unity *might* one day decide to change their license agreement in a way which excludes your use-case. But the question is "why would they do that"? Avoiding bad PR? So far, whenever there was a moral outrage about a scandalous game, that outrage was usually targeted at developers, publishers and distributors. I can not think of any case where *technology providers* were targeted by protests and boycott calls because they licensed their engine to a game they didn't agree with. So Unity Technologies will likely be happy to take your business. Just make sure you pay for a professional license and take down the Unity splash screen, so they don't get associated with your game in a way that someone might think they had creative influence.

If you are looking for precedent cases: I couldn't think of any games which were actually promoting hate speech and are based on Unity. But I didn't really look, and if they would exist, it wouldn't really surprise me (looking at some statements by some gamers in various communities, there seems to be a market for this). However, I did see Unity being used for 3d *pornographic* games by at least two game studios in Japan which are quite large and established in the hentai game niche. If Unity would disapprove of their engine being used for games like that, then these companies would likely not stay under the radar. This gives the impression that Unity Technologies does not mind what you use their engine for. At least not at the moment.

# Answer
> 3 votes
Unity Terms of Service doesn't **directly** state that they will revoke your license if you make an offensive game. However, in section 3 of the ToS "Your Responsibilities" they specify:

> (c) you will comply with all applicable laws and regulations in connection with your use of the Services (including but not limited to applicable Federal Trade Commission rules and COPPA)

Also, in section 7 of the ToS "Termination and Account Cancellation" they specify:

> Unity will have the right in its sole discretion, and without prior notice to you, to suspend or disable your Unity Account or terminate the Agreement and/or your right or ability to access or use any of the Services if: (a) you breach this Agreement; (b) your use of the Services poses a security risk to, or otherwise adversely impacts, the Services or any third party; (c) your use of the Services subjects Unity, our affiliates or any third party to liability; (d) your use of the Services may be fraudulent; etc, etc...

Last but not least, in section 1.4 of the ToS "Modification" they specify:

> ... Unity may also modify the Agreement at any time and without prior notice...

In other words, **indirectly** there's always a chance they may actually do revoke your license, either because you did not comply with the laws and regulations of a third party, or because they just decided to modify the current agreement and include and offensive content clause. Bear in mind that each 3rd party can interpret "offensive content" as they like, and they typically have modification clauses too.

It's like you are walking on thin ice, and if you're really committed to making a game with offensive content you should really seek legal advice from a professional.

IMHO Unity should be the least of your concerns, because it might be hard for you to find a marketplace to upload your game, because as far as I now they typically do contain offensive content clauses. I'm sure Google does, and I think (not sure though) Steam does too.

Anyway, as far as Unity is concerned, which was the subject of your post, here's a link to all Unity Legal Information

---
Tags: unity, licensing
---


# Question
Title: Say I've got a list of a hundred unique weapons, how can I programmatically and easily identify them all?
I've got a class, `WeaponFrame`, that has an int member, `weapon_frame_id`, that I intend to use as a way to identify the weapon, and I use that compare against other `WeaponFrame` instances.

The problem is that I want to pull the weapon from the global list of WeaponFrames and equip it on an `Actor`. As the designer, I might know that `weapon_frame_id #2` is the bow weapon I want, but what is the best way to programmatically identify them?

If I assign an ID to the `WeaponFrame` on instantiation, I am unable to rely on the value being identical the next time the game is run, unless I assign the value to an enum or int then. That might work though.

I'm using C++11, would I just create a namespace somewhere, and enumerate all the weapon types,

```
enum class WeaponFrameIDs {
  Sword = 1,
  Bow = 2, //repeated a hundred-plus times
};

```

or would I make a ton of const integers in a header somewhere, even if effectively an enum that way too:

```
namespace WeaponFrameIDs {
  const int Sword = 1;
  const int Bow = 2;
}

```

I could also use strings mapped to an integer, but I'm losing compile-time verification (and I can't use constexprs with VS2013), and run the risk of duplicating entries. However it supports dynamic assignment to the list:

```
std::unordered_map<std::string, int> WeaponFrameIDs {
  {"Sword", 1},
  {"Bow", 2},
};

```

Is there an alternative that I'm missing? What is the best way to write a system for identifying weapons in a game?

If it's relevant, here's an example situation I'm trying to solve via code. I am not using a visual editor where I can drag a weapon onto an actor.

```
void set_up_actor()
{
  Actor actor;
  WeaponFrame* weapon_frame = AllWeaponFrames.at(WeaponFrameIDs::Bow);
  actor.weapon_frame = weapon_frame;
};

```

---

Points I'm looking to avoid:

* Filling an entire header with enums
* Needing to recompile the entire project because I changed that header
* Losing the ability to verify the id at compile time
* Eventually add user-generated ids. This conflicts *a lot* with the compile-time verification.

I'm trying to solve the best way to pull the Weapon from a list, whether it's by ID, index, specially mapped key or something else.

* If I use a literal ID, `actor->weapon_id = 1`, I don't know what weapon is tied to the ID of 1.
* If I use an enum, or a const int, to represent the `1`, I need to recompile the game for each of the new weapons I add.
* If I change the id type to a string, I lose the ability to programmatically validate the string against the existing list of weapons.

# Answer
> 3 votes
Persist your weapon data seperately. You probably want to use a database, but you could also use a file and load it into memory. Using constants creates (at least) two problems, the first is adding or changing data requires you to recompile the binary, and the second is it inflates the size of the binary.

Let's consider a simple example where we use database.

Suppose we have a table for weapons which has the following a columns, id (pkey), name (varchar), max damage (int). Our weapons do a random amount of damage between 0 and max damage.

We also need a table to store player data, it will have the following columns, id (pkey), name (varchar), and weapon\_id (fkey).

Our program defines the following structures (for simplicity).

```
struct Weapon {
    int id;
    char *name;
    int max_damage;
}

struct Player {
    int id;
    char *name;
    Weapon *weapon;
};

```

Suppose a player with an id of 1 loads into our game.

```
SELECT * FROM player INNER JOIN weapon ON weapon.id = player.weapon_id WHERE player.id = 1

```

We can use the data returned from the database to fill in our structs and the rest of the program can use them.

Do not get bogged down in the specifics of this example as it is mearly that.

# Answer
> 2 votes
The simplest and easiest way to handle this is to:

1. Store weapons in a file to be loaded at runtime.
2. Use fixed-length strings as identifiers for the items. Your code references them by using string literals.

Fixed-length strings make for great identifiers. They are:

1. Hard to overlap. You need the identifiers to be assigned by hand in the weapon files themselves, not at load time (this allows the identifiers to be persistent). But it's really easy to accidentally reuse an integer value, especially if you're counting from 1. It's a lot harder to repeat a fixed-length string by accident. Even a 16-character string has plenty of space, and a 32-character one is long enough for you to have a naming convention with groups of names partitioned by prefixes and such.
2. Fast to compare. When doing comparisons with fixed-length identifier strings, you don't care about any specific ordering. You don't specifically need ASCII, lexicographical, or Unicode ordering. What you need is a single, specific, unchanging ordering. This can be achieved by comparing the strings as though they were arrays of *integers* rather than bytes. A 16-character fixed-length string can be compared with 2 64-bit integer compares rather than 16 character compares.

This also makes lookups in associative containers faster.
3. Not particularly large. 16 character strings are probably big enough for a unique identifier, but if you want to get really descriptive, you can use 32. Oh sure, that's bigger than the 4 or 8 bytes a single integer would take up, but it's not a huge amount.

* And if their size does become a legitimate problem (which it almost certainly won't), you can always have non-debugging builds have the fixed-length string class store a hash rather than a string. You'll lose #5 on this list, but you'll get back the storage space from your strings.
4. Legible in code. When you read your code, you see string names, so you have an idea what it's referencing.
5. Legible in the *debugger*. This is a *very* big deal. At some point in your game's development, you're going to be looking at some data structure and trying to figure out which weapon this data structure is referencing. An integer value is pretty opaque; a fixed-length string can be read in the debugger and tells you everything you need to know about what is being referenced.

Yes, there's no compile-time protection in your source code references, but you lost that the moment the weapons stopped being part of your C++ code. After all, if the weapons are not part of your code, there's nothing that ensures that the integer 1 or an enumerator maps to the actual weapon that it appears to (or any weapon at all). That's determined by what is in your weapon file, not what's in your C++ code.

---
Tags: c++, software-engineering
---


title: How to Destroy Text after certain Time

text:
# Question
Title: How to Destroy Text after certain Time
So, I have this 2D game built. In it, a text pop ups in the beginning but I want that text to stop appearing after certain seconds. (Using Unity)*This text is also attached to a panel*

# Answer
The simple way would be to use a script which uses the `Destroy` method with a time-parameter on the the text panel when it is created. This is an example of a simple self-destruct script you can attach to any game object which is supposed to have a limited lifetime:

```
public class SelfDestruct :  MonoBehaviour {
    public float lifetime = 3.0;
    public void Start() {
        Destroy(this.gameObject, lifetime);
    }
}

```

An even nicer method might be to not have it disappear suddenly but rather fade it out by lowering its alpha value and then destroy it when the alpha reaches zero. Here is a simplified version of a "fade out and destroy" script from one of my projects (supposed to get attached to a panel which can have as many sub-components as you want):

```
public class FadeOutAndDestroy : MonoBehaviour {

    public float stayTime = 3.0f;
    public float fadeoutTime = 1.0f;

    private float time;

    public void Start() {
        time = stayTime + fadeoutTime;
    }

    void Update () {
        time -= Time.deltaTime;

        if (time < fadeoutTime && time > 0) {
            float alpha  = time / fadeoutTime;
            foreach (CanvasRenderer r in GetComponentsInChildren<CanvasRenderer>()) {
                r.SetAlpha(alpha);
            }
        }

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

```
> 2 votes

---
Tags: unity, text
---


title: How to avoid lots of booleans

text:
# Question
Title: How to avoid lots of booleans
This was probably asked somewhere but I can't google anything for some reason. So I'm making a puzzle game as a result I have lots of booleans which affect the game only once and become redundant. As an example, to enter some door player needs to pickup a key so there is check for that. After that when hero enters a doors for the first there is a special animation triggered. So after player had entered the door this checks are no longer neccery.

I am not worried about perfomance but rather code design. Maybe there is some clever trick to manage game state without bunch of ifs and bools?

# Answer
Oldschool RPGs with lots of these switch/lock-and-key style steps but a strictly linear progression would often implement this as a "Quest Stage" integer or enumeration.

Let's imagine a linear dungeon with a key to open the entrance door, two rooms of puzzles to solve, and a boss to defeat:

* the dungeon's quest stage begins at `0 == QUEST_START`
* finding the entrance key sets the stage to `1 == KEY_FOUND`
* the door opens if you interact with it and the quest stage is 1.
    + This sets the stage to `2 == DOOR_OPEN`. If you come back to this map with quest stage \>= 2, the door spawns already-open.
* solving the first puzzle sets the quest stage to `3 == FIRST_PUZZLE`
    + with the quest stage at 3 or greater, the door to the next room opens
* solving the second puzzle sets the quest stage to `4 == BOSS`
    + now the boss door will open
* defeating the boss sets the quest stage to `5 == DUNGEON_COMPLETE`
    + all the villagers can check if the quest stage is \>= 5 to say "Thank you for defeating the boss monster!'

Here we had 5 boolean tests (has key, has opened door, has solved puzzle 1, 2, has defeated boss) packed into a single number we can store in 3 bits rather than 5 bools. In 16 bits we could store 16 independent booleans as a bitfields, or distinguish 65535 stages of a linear sequence (which might have been significant back in the day of tiny on-cartidge save game storage)

Even though the storage efficiency isn't so relevant today, it can still help tame the explosion of variables you need to keep track of to describe the game state. (Hopefully these aren't hard coded in your program, but even the conceptual overhead for your level designer can be improved by this kind of reduction)

The obvious limitation is that it's linear. This style of tracking doesn't work at all for optional objectives/events the player could skip, or choice points where the player can do multiple things in any order. For those you need to fall back on individual flags.

This also means all your indices may have to shift around whenever you insert/remove/rearrange these beats in your level & mission design. (But hopefully you're implementing this in a data-driven way, where you just specify the dependency relationships in your level/quest markup and they're numbered for you) This can invalidate save files from before the change.

You can get some benefit from using a separate quest stage variable for each linear branch of a quest chain/tree. This lets you have branching and limits the amount of spillover effects when one branch gets redesigned, while still getting a modest reduction in the amount of state you're tracking.
> 6 votes

# Answer
Consider using a bit field. You can divide up the values into 8, 16, 32, or 64 bit segments.
> -3 votes

---
Tags: architecture, game-state
---


# Question
Title: How do I merge colliders in a tile-based game?
I'm doing a tiled based platformer in unity, and I was having some issues with collisions and I figured the problem was the way my colliders were arranged.

So right now, my collision look like this:

You see each tile has its own collider, outlined in black. Polygon colliders in unity are formed by lists of points in space, and I can manipulate them freely. What I would ultimately want, is to have all this colliders in the example image to merge into just two colliders ( or maybe one, depending on how the edges of those squares touching would be handled ):

How could I achieve that? Is there any known algorithm?

# Answer
Ok, so I solved this problem using the Clipper library: http://www.angusj.com/delphi/clipper.php

The library has an all in one .cs file, so the easiest way to use it in unity, is to just paste this file in your Assets folder.

Here is what the collision looks like in my scene view, before and after:

It's not 100% perfect, but I think I'll do in most cases.

Here is the commented code:

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

using ClipperLib;
using Path = System.Collections.Generic.List<ClipperLib.IntPoint>;
using Paths = System.Collections.Generic.List<System.Collections.Generic.List<ClipperLib.IntPoint>>;

//this function takes a list of polygons as a parameter, this list of polygons represent all the polygons that constitute collision in your level.
public List<List<Vector2>> UniteCollisionPolygons(List<List<Vector2>> polygons)
{
    //this is going to be the result of the method
    List<List<Vector2>> unitedPolygons = new List<List<Vector2>>();
    Clipper clipper = new Clipper();

    //clipper only works with ints, so if we're working with floats, we need to multiply all our floats by
    //a scaling factor, and when we're done, divide by the same scaling factor again
    int scalingFactor = 10000;

    //this loop will convert our List<List<Vector2>> to what Clipper works with, which is "Path" and "IntPoint"
    //and then add all the Paths to the clipper object so we can process them
    for (int i = 0; i < polygons.Count; i++)
    {
        Path allPolygonsPath = new Path(polygons[i].Count);

        for (int j = 0; j < polygons[i].Count; j++)
        {
            allPolygonsPath.Add(new IntPoint(Mathf.Floor(polygons[i][j].x * scalingFactor), Mathf.Floor(polygons[i][j].y * scalingFactor)));
        }
        clipper.AddPath(allPolygonsPath, PolyType.ptSubject, true);

    }

    //this will be the result
    Paths solution = new Paths();

    //having added all the Paths added to the clipper object, we tell clipper to execute an union
    clipper.Execute(ClipType.ctUnion, solution);

    //the union may not end perfectly, so we're gonna do an offset in our polygons, that is, expand them outside a little bit
    ClipperOffset offset = new ClipperOffset();
    offset.AddPaths(solution, JoinType.jtMiter, EndType.etClosedPolygon);
    //5 is the ammount of offset
    offset.Execute(ref solution, 5f);

    //now we just need to conver it into a List<List<Vector2>> while removing the scaling
    foreach (Path path in solution)
    {
        List<Vector2> unitedPolygon = new List<Vector2>();
        foreach (IntPoint point in path)
        {
            unitedPolygon.Add(new Vector2(point.X / (float)scalingFactor, point.Y / (float)scalingFactor));
        }
        unitedPolygons.Add(unitedPolygon);
    }

    //this removes some redundant vertices in the polygons when they are too close from each other
    //may be useful to clean things up a little if your initial collisions don't match perfectly from tile to tile
    unitedPolygons = RemoveClosePointsInPolygons(unitedPolygons);

    //everything done
    return unitedPolygons;
}

//create the collider in unity from the list of polygons
public void CreateLevelCollider(List<List<Vector2>> polygons)
{
    GameObject colliderObj = new GameObject("LevelCollision");
    colliderObj.layer = GR.inst.GetLayerID(Layer.PLATFORM);
    colliderObj.transform.SetParent(level.levelObj.transform);

    PolygonCollider2D collider = colliderObj.AddComponent<PolygonCollider2D>();

    collider.pathCount = polygons.Count;

    for (int i = 0; i < polygons.Count; i++)
    {
        Vector2[] points = polygons[i].ToArray();

        collider.SetPath(i, points);
    }
}

public List<List<Vector2>> RemoveClosePointsInPolygons(List<List<Vector2>> polygons)
{
    float proximityLimit = 0.1f;

    List<List<Vector2>> resultPolygons = new List<List<Vector2>>();

    foreach(List<Vector2> polygon in polygons)
    {
        List<Vector2> pointsToTest = polygon;
        List<Vector2> pointsToRemove = new List<Vector2>();

        foreach (Vector2 pointToTest in pointsToTest)
        {
            foreach (Vector2 point in polygon)
            {
                if (point == pointToTest || pointsToRemove.Contains(point)) continue;

                bool closeInX = Math.Abs(point.x - pointToTest.x) < proximityLimit;
                bool closeInY = Math.Abs(point.y - pointToTest.y) < proximityLimit;

                if (closeInX && closeInY)
                {
                    pointsToRemove.Add(pointToTest);
                    break;
                }
            }
        }
        polygon.RemoveAll(x => pointsToRemove.Contains(x));

        if(polygon.Count > 0)
        {
            resultPolygons.Add(polygon);
        }
    }

    return resultPolygons;
}

```
> 3 votes

# Answer
use Composite Collider component
> -4 votes

---
Tags: unity, tiles
---


# Question
Title: How to keep my Unity build from minimizing when I switch focus to an app on another monitor?
I have a multi-monitor setup. We are doing a lot of demos right now. I have my meeting controls on one screen and my Unity build on another one that is shared. When I click anything on any other monitor, the Unity build minimizes. My build was initially set to "Fullscreen Window" but in an attempt to resolve this issue I have set it to "Maximized Window" but this did not fix the issue.

How can I interact with apps on another monitor without minimizing my game?

# Answer
> 1 votes
The "Visible In Background" option did exactly what I needed. Not sure why I didn't notice this first.

---
Tags: unity, fullscreen
---


# Question
Title: Trying to trigger dialogue when the space bar is clicked, and two objects are colliding
I'm getting a NullReferenceException on OnTriggerStay. I've been going crazy trying to figure out why. I have tried to cut this down to only the relevent information. I got this code through a tutorial: https://www.youtube.com/watch?time\_continue=48&v=\_nRzoTzeyxU (just for credits).

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

[RequireComponent(typeof(Rigidbody))]
public class MainCharacter : MonoBehaviour {
    public int limbs;

    public float speed;
    public Vector3 jump;
    public float jumpForce;
    Rigidbody2D rb;
    public float fire_start_time = Time.time;
    Animator animator;
    public DialogueManager dialogueManager;

    // Checking if we are grounded
    public bool isGrounded;
    public LayerMask groundLayers;

    private SpriteRenderer myRenderer;

    public Sprite[] LimbSprites;

    void Start()
    {
        dialogueManager = gameObject.GetComponent<DialogueManager>();
    }

    public void OnTriggerStay2D(Collider2D collision)
    {
        if (Input.GetKey(KeyCode.Space))
        {
            Dialogue dialogue = collision.GetComponent<Dialogue>();
            dialogueManager.StartDialogue(dialogue);

        }
    }

}

```

Here is my dialogue manager:

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

public class DialogueManager : MonoBehaviour {

    public Text nameText;
    public Text dialogueText;

    public Animator animator;

    private Queue<string> sentences;

    // Use this for initialization
    void Start () {
        sentences = new Queue<string>();
    }

    public void StartDialogue (Dialogue dialogue) {

        animator.SetBool("IsOpen", true);

        nameText.text = dialogue.name;
        sentences.Clear();

        foreach (string sentence in dialogue.sentences) {
            sentences.Enqueue(sentence);
        }

        DisplayNextSentence();
    }

    public void DisplayNextSentence() {
        if (sentences.Count == 0) {
            EndDialogue();
            return;
        }

        string sentence = sentences.Dequeue();
        dialogueText.text = sentence;
    }

    void EndDialogue() {
        animator.SetBool("IsOpen", false);
    }
}

```

Here is DialogueTrigger

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

public class DialogueTrigger : MonoBehaviour {

    public Dialogue dialogue;

    public void TriggerDialogue () {
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);

    }
}

```

Here is Dialogue

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

[System.Serializable]
public class Dialogue : MonoBehaviour {

    public string name;

    [TextArea(3, 10)]
    public string[] sentences;

}

```

# Answer
> 1 votes
Here is your OnTriggerStay method

```
public void OnTriggerStay2D(Collider2D collision)
{
        if (Input.GetKey(KeyCode.Space))
        {
            Dialogue dialogue = collision.GetComponent<Dialogue>();
            dialogueManager.StartDialogue(dialogue);

        }
}

```

The problem is that you don't control with which object you are currently colliding, it can be any GameObject with a collider set on trigger and not just those who have a Dialog component.

I suggest adding a tag to those GameObjects or do a defensive check.

```
public void OnTriggerStay2D(Collider2D collision)
        {
            if (collision.gameObject.tag == "CanTalkWith")
            {
                if (Input.GetKey(KeyCode.Space))
                {
                    Dialogue dialogue = collision.gameObject.GetComponent<Dialogue>();
                    if (dialogue != null)
                    {
                        dialogueManager.StartDialogue(dialogue);
                    }

                }
            }
        }

```

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


# Question
Title: How to make a Blend-Effect like yomawari did?
I would like to know, how to make that effect, I have seen in the game named Yomawari. The little girl has a lamp and its cone revals the dark spirits around her. But only if they are in the light. I think it's like the additive blending, but I dont get it to work. I use monogame and c#.

Here is a sample: https://youtu.be/kPLRXP7ovB0?t=1241

All ideas are wellcome (sourcecode preferred ;))

Greetings Kai

My current test code: (DL: https://github.com/EnemyArea/yomawari-lights)

```
    protected override void Draw(GameTime gameTime)
    {
        var blend = new BlendState
        {
            ColorBlendFunction = BlendFunction.Add,
            ColorSourceBlend = Blend.DestinationColor,
            ColorDestinationBlend = Blend.Zero
        };

        var lightBlendState = new BlendState
        {
            ColorSourceBlend = Blend.Zero,
            ColorDestinationBlend = Blend.SourceColor
        };

        var mousePosition = Mouse.GetState().Position;

        // Draw lights
        this.GraphicsDevice.SetRenderTarget(this.blackpixel);
        this.GraphicsDevice.Clear(Color.DarkGray);
        this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
        this.spriteBatch.Draw(this.lichtRund, new Vector2(mousePosition.X, mousePosition.Y), null, Color.White, 0f, new Vector2(this.lichtRund.Width * 0.5f, this.lichtRund.Height * 0.5f), 1f, SpriteEffects.None, 0);
        this.spriteBatch.End();
        this.GraphicsDevice.SetRenderTarget(null);

        // Draw hidden
        this.GraphicsDevice.SetRenderTarget(this.renderTarget);
        this.GraphicsDevice.Clear(Color.White);
        this.spriteBatch.Begin(SpriteSortMode.Deferred, blend);
        this.spriteBatch.Draw(this.testeye, new Vector2(this.GraphicsDevice.Viewport.Width / 2f, this.GraphicsDevice.Viewport.Height / 2f), null, Color.White, 0f, new Vector2(this.testeye.Width * 0.5f, this.testeye.Height * 0.5f), 1f, SpriteEffects.None, 0);
        this.spriteBatch.Draw(this.blackpixel, Vector2.Zero, Color.White);
        this.spriteBatch.End();
        this.GraphicsDevice.SetRenderTarget(null);

        // Combine all
        this.GraphicsDevice.Clear(Color.Black);

        this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
        this.spriteBatch.Draw(this.background, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
        this.spriteBatch.Draw(this.renderTarget, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        this.spriteBatch.Begin(SpriteSortMode.Deferred, lightBlendState);
        this.spriteBatch.Draw(this.blackpixel, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        base.Draw(gameTime);
    }

```

it results into that:  but is should look like

another sample

# Answer
Here is a solution using a shader. Basically the shader uses the lightmap to mask pixels. The lightmap is black and white texture and the R (red) component is used to determine if the mask should be applied or not. This leaves the G and B components usable for a different effect.

First the shader:

```
    #if OPENGL
    #define SV_POSITION POSITION
    #define VS_SHADERMODEL vs_3_0
    #define PS_SHADERMODEL ps_3_0
#else
    #define VS_SHADERMODEL vs_4_0_level_9_1
    #define PS_SHADERMODEL ps_4_0_level_9_1
#endif

Texture2D SpriteTexture;

sampler2D SpriteTextureSampler = sampler_state
{
    Texture = <SpriteTexture>;
};

Texture2D MaskTexture;

sampler2D MaskTextureSampler = sampler_state
{
    Texture = <MaskTexture>;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
    float2 TextureCoordinates : TEXCOORD0;
};

float4 MainPS(VertexShaderOutput input) : COLOR
{
    float4 col = tex2D(SpriteTextureSampler,input.TextureCoordinates) *input.Color; //sample the source image
    float mask = tex2D(MaskTextureSampler, input.TextureCoordinates).r; //sample the R component of the mask image.

    if(mask>0) // if the mask is >0 apply it.
        return float4(col.r,col.g,col.b,col.a*mask); // keep all colors, and use the alpha of the source.

    return float4(0, 0, 0, 0); //otherwise return a transparent (masked) pixel- without color information.
}

technique SpriteDrawing
{
    pass P0
    {
        PixelShader = compile PS_SHADERMODEL MainPS();
    }
};

```

This is the Draw function:

```
    /// <summary>
    ///     This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {

        // Draw lights
        this.GraphicsDevice.SetRenderTarget(this.LightmapLayer);
        this.GraphicsDevice.Clear(Color.Black);
        this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
        this.spriteBatch.Draw(this.Lightmap, new Vector2(this.GraphicsDevice.Viewport.Width / 2f, this.GraphicsDevice.Viewport.Height / 2f), null, Color.White, 0f, new Vector2(this.Lightmap.Width * 0.5f, this.Lightmap.Height * 0.5f), 1f, SpriteEffects.None, 0);
        this.spriteBatch.End();
        this.GraphicsDevice.SetRenderTarget(null);

        //I created a simple rendertarget 'GhostLayer':
        this.GraphicsDevice.SetRenderTarget(this.GhostLayer);
        this.GraphicsDevice.Clear(Color.Transparent);
        this.spriteBatch.Begin();
        this.spriteBatch.Draw(this.Ghost, new Vector2(this.GraphicsDevice.Viewport.Width / 2f, this.GraphicsDevice.Viewport.Height / 2f), null, Color.White, 0f, new Vector2(this.Ghost.Width * 0.5f, this.Ghost.Height * 0.5f), 1f, SpriteEffects.None, 0);
        this.spriteBatch.End();

        //show the result on the screen:
        this.GraphicsDevice.SetRenderTarget(null);
        this.GraphicsDevice.Clear(Color.Purple);

        //Draw the game scene:
        this.spriteBatch.Begin();
        this.spriteBatch.Draw(this.Background, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        //Draw the ghosts using a mask effect:
        this.MaskEffect.Parameters["MaskTexture"].SetValue(LightmapLayer);

        this.spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, MaskEffect);
        this.spriteBatch.Draw(this.GhostLayer, Vector2.Zero, Color.White);
        this.spriteBatch.End();

        //Draw the lights:
        this.spriteBatch.Begin();
        this.spriteBatch.Draw(this.LightmapLayer, Vector2.Zero, Color.White*0.25f);
        this.spriteBatch.End();

        base.Draw(gameTime);
    }

```

Based on the code in your github, it produces this result:

The final light is now simply drawn in, this could be made more subtle with another shader effect.
> 2 votes

# Answer
**Answer with the use of a shader elsewhere. I leave this answer because the technique may be of interest to someone.**

You can create your own blendstate like this:

```
        MultiplicativeBlend = new BlendState();
        //deal with transparency
        MultiplicativeBlend.AlphaBlendFunction = BlendFunction.ReverseSubtract;
        MultiplicativeBlend.AlphaSourceBlend = Blend.SourceAlpha;
        MultiplicativeBlend.AlphaDestinationBlend = Blend.Zero;
        //deal with color
        MultiplicativeBlend.ColorBlendFunction = BlendFunction.Add;
        MultiplicativeBlend.ColorSourceBlend = Blend.DestinationColor;
        MultiplicativeBlend.ColorDestinationBlend = Blend.Zero;

```

This creates a multiplicative blend, while keeping the transparency of the source.

With these textures:

*The lightmap:*

*The ghost (this texture represent all the 'ghosts' in the scene only visible in the lightbeam:*

*The game scene, as drawn normally without the ghosts:*

The image can be drawn with the mask (using the multiply blendstate). In the code below I set up the components and two custom blendstates. One is the "multiply" blendstate to mask the ghost. The other is the "Light" blendstate to render the lightbeam later:

```
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Ghost = Content.Load<Texture2D>("ghost");
        Lightmap = Content.Load<Texture2D>("lightmask");
        Background = Content.Load<Texture2D>("background");

        // TODO: use this.Content to load your game content here
        MultiplicativeBlend = new BlendState();
        //deal with transparency
        MultiplicativeBlend.AlphaBlendFunction = BlendFunction.ReverseSubtract;
        MultiplicativeBlend.AlphaSourceBlend = Blend.SourceAlpha;
        MultiplicativeBlend.AlphaDestinationBlend = Blend.Zero;
        //deal with color
        MultiplicativeBlend.ColorBlendFunction = BlendFunction.Add;
        MultiplicativeBlend.ColorSourceBlend = Blend.DestinationColor;
        MultiplicativeBlend.ColorDestinationBlend = Blend.Zero;

        //Another blendstate to deal with the lightmap later:
        LightBlend = new BlendState();
        LightBlend.ColorBlendFunction = BlendFunction.Subtract;
        LightBlend.ColorSourceBlend = Blend.DestinationColor;
        LightBlend.ColorDestinationBlend = Blend.Zero;

        GhostLayer = new RenderTarget2D(GraphicsDevice, 250, 250);
    }

```

Now putting it in use like this:

```
    protected override void Draw(GameTime gameTime)
    {

        //I created a simple 250x250 pixel rendertarget 'GhostLayer':
        GraphicsDevice.SetRenderTarget(GhostLayer);
        GraphicsDevice.Clear(Color.Transparent);

        //first draw the ghost in the normal way
        spriteBatch.Begin();
        spriteBatch.Draw(Ghost, Vector2.Zero, Color.White);
        spriteBatch.End();

        //now draw the lightmap to mask so only the 'ghost',
        //this uses the blendstate created above.
        spriteBatch.Begin(SpriteSortMode.Immediate, MultiplicativeBlend);
        spriteBatch.Draw(Lightmap, Vector2.Zero, Color.White);
        spriteBatch.End();

        //show the result on the screen:
        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin();
        //Draw the game scene:
        spriteBatch.Draw(Background, Vector2.Zero, Color.White);
        //Draw the (masked) ghosts:
        spriteBatch.Draw(GhostLayer, Vector2.Zero, Color.White);

        // uncomment the next 'Draw' line and comment out the 'lightblend'
        // section to see the alternate result.
        //spriteBatch.Draw(Lightmap, Vector2.Zero, Color.White*0.5f);

        spriteBatch.End();

        //Lightblend section:
        //Draw the lightbeam using the lightBlend (though a shader might be better for this part).
        spriteBatch.Begin(SpriteSortMode.Immediate,LightBlend);
        spriteBatch.Draw(Lightmap, Vector2.Zero, Color.White);
        spriteBatch.End();
        //End lightblend section.

        base.Draw(gameTime);
    }

```

Now the final result is the ghost is clipped according to the lightmap, with the lightmap showing.

I think, this produces the effect you're looking for.

This is the effect where the lightmap is drawn without the "lightblend" effect, to demonstrate the red circle is indeed clipped:

Though I recommend taking a look at the sample code https://github.com/Felsir/LightingEngine as it shows a C#, Monogame example how the light effect is achieved by using a shader. This produces a more subtle effect with better control over ambient light and light flow.

It produces this effect:
> 2 votes

---
Tags: c#, xna, monogame, graphic-effects
---


# Question
Title: How to stop a host from the client script?
I am developing a two player multiplayer game. Since its only two players, I don't want to keep my connection open if a player disconnects.

Now this works well from the host side, through usage of `StopHost()`. If the player who hosts disconnects, it disconnects both the players from the game.

But using `StopHost()` in the client(Player B) side does not remove the host player(Player A). In other words, the client is out of the game, but the host is still in the game.

**So, what I want is if one player(host or the client whoever it is) disconnects, I want both of them to be disconnected.**

So, how can I do it? Please help me with this. I have almost lost hope with UNET. Thanks

**EDIT:**

**My setup is like this, my LobbyManager comprises of UI elements like "TitlePanel", "MainPanel", etc.** **The Disconnect button is part of the title panel and gets enabled on press of Esc key.** **The button is linked to a script attached to the "TitlePanel".** **This script uses a `MonoBehaviour` which I changed to `NetworkBehaviour` in order to use `[Command]`.** **But it doesn't work as my "Title Panel" does not have a `NetworkIdentity`. Adding one creates even more problems**

**So, I thought if there was a way to send mesages from client to server without NetworkBehaviour, then maybe I could send a flag there to the server.**

**So is it possible?**

# Answer
> 1 votes
On your custom NetworkManager you can override the OnServerDisconnect for that purpose. Your code should looks like this:

```
public override void OnServerDisconnect(NetworkConnection conn)
{
    NetworkServer.DestroyPlayersForConnection(conn);
    StopHost();
}

```

OnServerDisconnect means: on the server side a client has disconnected. I know, the method name does not suggest that :/

I also know that this is a question from 2016 but as it may still hunt people at night, I'll left this answer here. Cheers ;)

---
Tags: unity, multiplayer, unet
---


title: Game assets are images or 3D models

text:
# Question
Title: Game assets are images or 3D models
I am new to game development and I have created simple games with javascript and SFML. Those games are 2D and there I used images as my gaming assets. I was trying to be familiar with OpenGL like 3D modeling APIs. In 3D gaming is all the assets are 3D models or there can be some images like in 2D?

# Answer
> 2 votes
Many 3d games use 2d sprites. A common term for a 2d sprite which always faces the camera in a 3d environment is a "Billboard". It can be a neat trick to bring detailed objects into a scene while keeping the polygon count low. A complex object which would otherwise take hundreds or even thousands of polygons can be reduced to just two when you replace it with a pre-rendered billboard. A prominent example are the trees in the intro of Super Mario 64. Notice how they don't change when the camera moves up or sideways.

But more modern games also occasionally use this technique. It is especially popular if you need to render a large number of detailed objects which are far away from the camera. In that case you just render the object once to a texture and then use that texture as a billboard instead of the actual object. This looks bad if you do it with objects which are very close to the camera. But when the objects are very far away, it can be almost impossible to see. Such a sprite is called an "Imposter".

And then there are games which combine 2d and 3d elements as an aesthetic choice. One well-known example is the Disgaea series which uses 2d character sprites in a 3d environment. The sprites got more detailed over the course of 14 years with 6 games, but they never gave in to the temptation to go fully 3d:

# Answer
> 1 votes
Short Answer: Yes, there can be 2D sprites/ assets in a 3D game.

I am just gonna explain you the general idea and what most game-engines usually use. What is *3D*, it's 3-dimensional which means it automatically encloses *2D*.

In fact, most game-engines these days allow you to work freely between 2D and 3D (Unity for example). The 2D mode in Unity is simply 3D with 2D perspective.

This is the list of a few games that mix 2D and 3D:

1. Project Octopath Traveller
2. Xenogears
3. The Last Night

---
Tags: opengl, 2d, 3d, game-design
---


title: Animation Length to Integer

text:
# Question
Title: Animation Length to Integer

Currently, I have a script; more specifically for weapons. It handles animations, and the animations are being played and then stopped (once they're finished) by co-routines. I have variables for how long certain animations are (in frames), which are designated at the beginning of the script. I then take that and divide it by the frame rate they were animated in, for the co-routine's waitForSeconds. The problem is that for each weapon, I have to manually input how long each of their usually 13 animations is in the inspector.

It'd be a lot easier if I could take the animation component that is being played, and have the script figure out how long it is, convert it to an integer, and use that for the waitForSeconds. I've looked around for this before (and just did again), but nothing has worked. If anyone needs me to clarify something, please let me know.

# Answer
> 0 votes
As DMGregory said, you can just use AnimationClip.length. It's a float, but WaitForSectonds handles floats just fine. The reason it hadn't worked for me before was that I was using a different animation handling system and because I wasn't using the "AnimationClip.length" function properly.

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


# Question
Title: GameObject.FindWithTag throwing weird errors
I've got 2 first person controller scripts, one that handles functionality for basic movement, the other handling looking around. I also have a "CursorLockManager" script, that handles the cursor locking, as well as locking movement and looking (for when opening menus and such). At the beginning of the cursor lock script, in the start function, I have two GameObject.FindWithTag lines. One looks for the playerLook script, and the other looks for the playerMove script. I have them both set up the same way, but one of them isn't working.

First few lines of the CursorLockManager script:

```
public KeyCode menuKey;
public PlayerLook playerLook;
public PlayerMove playerMove;
public bool menuIsOpened;
public GameObject tempMenu;

private void Start()
{

    playerLook = GameObject.FindWithTag("Camera").GetComponent<PlayerLook>();
    playerMove = GameObject.FindWithTag("FP_Controller").GetComponent<PlayerMove>();

}

```

and the error Unity is throwing:

> UnityException: Tag: Camera is not defined

Line 17 of the CursorLockManager:

```
        playerLook = GameObject.FindWithTag("Camera").GetComponent<PlayerLook>();

```

Any help would be greatly appreciated. If you need any further clarification as to anything else, I'd be glad to provide it to you.

# Answer
> 0 votes
It looks like you don't want to search by tags at all. If you ultimately want to find instances of a specific component, then search for that component instead, like this:

```
playerLook = FindObjectOfType<PlayerLook>();
playerMove = FindObjectOfType<PlayerMove>();

```

This searches directly for the component you want to use, so it's less sensitive to scene setup errors (like forgetting to create a tag called "Camera" or misspelling Unity's default "MainCamera" tag)

Or you can skip searching for them at all, and instead use a Singleton or Service Locator pattern to retrieve references to these key script instances more efficiently.

---

In Unity 2021.3.18 and newer, **there's a faster alternative** to `FindObjectOfType` when you know there's only one instance of this type anyway:

```
playerLook = FindAnyObjectByType<PlayerLook>();
playerMove = FindAnyObjectByType<PlayerMove>();

```

This skips invoking a sort to ensure the "first" instance is returned, since there's only going to be one of them anyway, making it more efficient.

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


# Question
Title: How do I make a quest requiring a certain number of a specific item?
I'm trying to create a quest (in RPG Maker MV) where the player has to collect 35 berries. But when I go to create the conditional branch, this is what I see:

It does not let me add a number limit, so basically all the player has to do is collect 1 berry to complete the quest.

How can I change this so the player has to collect 35 berries in order to complete the quest? Is this a limitation of RPG Maker MV?

# Answer
> 3 votes
A Conditional Branch cannot refer directly to the quantity of an item, but the quantity can be copied to a variable, and the Conditional Branch **can** refer directly to that.

Before your Conditional Branch, insert a Control Variables (tab 1). In the Variable pane, select Single, click the button next to Single, select a variable that you're not using for anything else, and name it "Berry Count". In the Operation pane, select Set. In the Operand pane, select Game Data. Click the button next to Game Data to open the Game Data dialog. In the Game Data dialog, select Item. Click the button next to Item and select your item "Berry". The Game Data dialog should look like this:

and the Control Variables dialog should look like this:

In your Conditional Branch, don't select Item (tab 4). Select Variable (tab 1), set the variable to "Berry Count", set the comparison to ≥, and set the value to constant 35. The Conditional Branch dialog should look like this:

and your event code should look like this:

---
Tags: rpg, events, quests, rpg-maker-mv
---


# Question
Title: Why is there a difference in frame rate between my fps calculation and Unity's calculation
So I wrote my own script for calculating framerate but it consistently comes out with a different value than Unitys idea of current framerate.

This is my implementation

```
  void UpdateFPSStats()
{
double frameTime = new double();
frameTime = Time.deltaTime;
m_times[frameIndex] = frameTime;

frameIndex++;

if (frameIndex == m_numberFrames)
{
  frameIndex = 0;
}

int numberSamples = 0;
double averageFrameTime = 0.0f;
foreach(double t in m_times)
{
  numberSamples++;

  averageFrameTime += t;
}

if (numberSamples > 0)
{
  averageFrameTime = averageFrameTime / numberSamples;
  m_frameRate = 1 / averageFrameTime;
}
}

```

where m\_frames is a list of the last 60 frames frame times and UpdateFPSStats is called in Unitys `Update(dt)` function.

On average in my scene my fps calculation gives a steady 50fps, while Unity calculates a steady 80fps.

Which is right and why?

# Answer
> 1 votes
Unity's built-in editor framerate estimates the performance without the editor overhead. If you go into profiler, editor overhead likely accounts for around 40% of your games processing, if the difference is 80fps to 50fps.

Your method is an accurate recording of what your actual FPS is, while Unity is trying to give you an estimation of what the FPS would be in a build.

Also, you should also look into Time.unscaledDeltaTime or Time.smoothDeltaTime to get around some of the reasons that your method might return an incorrect value.

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


# Question
Title: Drag object with mouse in diagonal direction
I have a gameobject which i want to move using mouse. Currently i can do that in x-axis and y-axis:

```
public bool moveDiagonal;
 public bool moveX, moveY;
 public float distanceXmin, distanceXmax, distanceYmin, distanceYmax;
 if (moveX)
 {
     if (curPosition.x >= distanceXmin && curPosition.x <= distanceXmax)
          goToMove.transform.position = new Vector3(curPosition.x, goToMove.transform.position.y, 0);
 }
 else if (moveY)
 {
    if (curPosition.y >= distanceYmin && curPosition.y <= distanceYmax)
          goToMove.transform.position = new Vector3(goToMove.transform.position.x, curPosition.y, 0);
 }

```

I wanted to move my object diagonally as well how to do that according to its direction using mouse? The object should move along the line or the x and y axis limits.

# Answer
I'd make this more generic.

Set up a structure you can populate in the Inspector to specify a direction you're allowed to drag the object, and a minimum and maximum signed distance along this direction that it's allowed to travel from its starting point.

Expose an array of these limits, and tweak them in `Start` to ensure their direction vectors are all unit length. (You could also use gizmos to visualize the limits in the scene view, or handles to edit them directly)

```
[System.Serializable]
public struct SlidingLimit {
     public Vector2 direction;
     public float min;
     public float max;
}

[SerializeField]
SlidingLimit[] limits;

Vector2 startPosition;

void Start() {
    startPosition = transform.position;
    for(int i = 0; i < limits.Length; i++) {
        var limit = limits[i];
        limit.direction = limit.direction.normalized;
        limit[i] = limit;
    }
}

```

Later, inside your drag function, you can call `Snap` to snap to the closest sliding limit:

```
Vector2 Snap(targetPosition) {
    if(limits.Length == 0)
         return targetPosition;

    Vector2 offset = targetPosition - startPosition;

    float closestRange = float.PositiveInfinity;
    int closestLimit = -1;

    SlidingLimit limit;

    // Find which line we're closest to,
    // by measuring our perpendicular distance.
    for(int i = 0; i < limits.Length; i++) {
         limit = limits[i];
         float range = offset.x * limit.direction.y - offset.y * limit.direction.x;
         if(range < closestRange) {
               closestRange = range;
               closestLimit = i;
         }
    }

    // Snap the returned point to this line,
    // between its min and max.
    limit = limits[closestLimit];

    float travel = Vector2.Dot(limit.direction, offset);
    travel = Mathf.Clamp(travel, limit.min, limit.max);

    return startPosition + travel * direction;
}

```

This will let you handle free draggables (no limits in the array), or draggables constrained to one, two, three, or any number of lines, at any angle, with custom travel limits on each, just by configuring your `limits` array accordingly.
> 1 votes

---
Tags: unity, movement, mouse
---


# Question
Title: Oculus Rift Touch controller input not working for some users in Unity 3D
I am working on a music based game that supports both Oculus Rift (touch controllers), HTC Vive and also no VR. Everything is working fine, but the past few days I have been stuck with 1 bug and I don't know what the cause is.

In my game I have a pause setting. This works properly for all 3 play modes. My colleague/friend that I work together with also has Oculus Rift with the touch controllers and somehow for him the buttons A, B, X and Y aren't working. The game doesn't get an input signal. In the Oculus app the input is working so it is only bugged in the game and not the hardware itself. From my side the game does get an input signal from the said buttons. Same code, same scenario. The only difference between our setups is that he has windows 7 and I have windows 10. He did a full reinstall with hotfixes, but the bug still persists.

I am using the touch mapping specified in the unity documents: https://docs.unity3d.com/Manual/OculusControllers.html Once again I have no issues and everything works correctly on my end. On his end however only the buttons X, Y, A and B aren't working. I tested this with simple objects being highlighted when the buttons are pressed as the simplest most basic visual testing method. He gets no error or whatsoever. Log file is clean as well. I have absolutely no idea about what I am doing wrong.

If both our controllers input didn't get recognized by the game then I'd understand that the buttons might not have been mapped properly. But for one person it works and for the other it doesn't. Now the other strange thing is that the other buttons are working on his end such as the triggers and thumb-sticks. And yes I have validated that both our game clients are the exact same version.

I have tried to do some research on my own, but I couldn't find working fixes, since on my end everything is working properly (including the fixes), but not on his end when it comes to those specific 4 buttons.

Update: He upgraded to windows 10 and it didn't seem to solve the problem.

# Answer
Apparantly Oculus Rift on Windows 7 doesn't work properly. The hotfixes make it seem to function correctly, but a lot drivers aren't configured correctly.

After he installed Windows 10 we did a full clean instal of Oculus Rift on Windows 10 and the issue no longer existed.

For future people having similar issues, Oculus Rift only works properly on Windows 10 and not on the older versions of Windows.
> 0 votes

---
Tags: unity, oculus
---


title: smoothly recenter view over time

text:
# Question
Title: smoothly recenter view over time
I'm currently using the Google Cardboard SDK for Unity to build a fighter pilot simulator. What I'm currently trying to do is recenter the view(CardboardHead) smoothly over time when the user looks away from the screen. This is because I want to put HUD elements out of the main central view that can be quickly seen with a "head jerk". I don't want to let the camera be free from constraints because I feel piloting is much better when the view is fixed and doesn't wobble about with every slight movement of the player's head. The Head already has a horizontal constraint that does not allow any later movement, but now I want to put a semi-constraint on the vertical axis so that the player can quickly look up or down to see something like i.e. a fuel economy indicator and then have the view quickly "follow his gaze" and recenter itself.

I noticed that the Cardboard plugin already does this type of constraint on the Head roll input when playing "in editor" and works as follows: When you press and hold Ctrl and move the mouse left/right the view rolls left/right. Upon release of Ctrl the view smoothly rolls back to 0. This is the code in the Cardboard script:

```
bool rolled = false;
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) {
      rolled = true;
      mouseZ += Input.GetAxis("Mouse X") * 5;
      mouseZ = Mathf.Clamp(mouseZ, -80, 80);
    }
    if (!rolled && autoUntiltHead) {
      // People don't usually leave their heads tilted to one side for long.
      mouseZ = Mathf.Lerp(mouseZ, 0, Time.deltaTime / (Time.deltaTime + 0.1f));
    }
    var rot = Quaternion.Euler(mouseY, mouseX, mouseZ);
    var neck = (rot * neckOffset - neckOffset.y * Vector3.up) * NeckModelScale;
    headView = Matrix4x4.TRS(neck, rot, Vector3.one);
  }

```

How could I implement this for vertical rotation of the Head?

In the Update method of the script that controls the Head it simply does `transform.localRotation = Cardboard.SDK.HeadRotation;`

This is what I've tried but it doesn't really do anything except some jerky movements:

```
transform.Rotate(new Vector3(Mathf.Lerp(rot.eulerAngles.x, 0, Time.deltaTime / (Time.deltaTime + 0.1f)),0,0));

```

(I put this in the same Update function for the Head after the above line)

Any ideas??

# Answer
Look at using Unity's Quaternion.RotateTowards and smooth the rotation per frame with something like the following:

```
    void Update()
    {
        float speed = 1f; // can adjust this to move faster or slower
        float step = speed * Time.smoothDeltaTime;
        Quaternion targetRotation = Quaternion.identity;
        transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, step);
    }

```
> 1 votes

---
Tags: unity, c#, camera, rotation, virtual-reality
---


title: Minecraft modding 1.12 draw image

text:
# Question
Title: Minecraft modding 1.12 draw image
I want to draw an image that I created but the image is too big. Now I want the Gui to scale the image to a reasonable size, but when I change the width and height it doesn't make the image scale down/up but only the texture.

Code where I draw the image on screen:

```
@Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks)
    {
        this.drawDefaultBackground();
        super.drawScreen(mouseX, mouseY, partialTicks);
        this.renderHoveredToolTip(mouseX, mouseY);
        Slot slot = getSlotAtPosition(mouseX, mouseY);

        if(slot != null) {
            if(slot.getStack().getItem() instanceof MonsterCard) {
                this.mc.getTextureManager().bindTexture(new ResourceLocation(Reference.MODID + ":textures/items/" + ((MonsterCard) slot.getStack().getItem()).getName() + ".png"));
                int i = (this.width - this.xSize) / 4;
                int j = (this.height - this.ySize) / 2;
                this.drawTexturedModalRect(0, 0, 0, 0, 154, 226);
            }
        }
    }

```

Image I want to draw which is 154px x 226px:

Output:

# Answer
```
int i = (this.width - this.xSize) / 4;
int j = (this.height - this.ySize) / 2;
this.drawTexturedModalRect(0, 0, 0, 0, 154, 226);

```

> Warning: unused variables `i` and `j`

Additionally, `drawTexturedModalRect()` assumes that the texture is 256x256 pixels exactly, so the last two parameters are divided by 256 to compute the size-agnostic UV coordinates, but your image is not 256x256, which is why it is cut off and stretched (your drawing 60% of the width and 88% of the height). There is a similar, but differently named, method that allows you to specify the texture size as well, but I can never remember the name of it.
> 2 votes

---
Tags: java, minecraft-modding
---


# Question
Title: Floating Boat 3D Physics Rotation from Rudder (no water resistance)
I have been able to simulate a floating boat very simply by attaching a script called `Boat.cs` to a ship model with a `Rigidbody`; the Drag and Angular Drag are set to `2`, and the mass to `15`, and the Rigidbody uses gravity.

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

  [RequireComponent(typeof(Rigidbody))]
  public class Boat : MonoBehaviour {
     public static float waterLevel = 16.6f;
     public float floatThreshhold = 2.0f;
     public float waterDensity = 0.125f;
     public float downForce = 0.5f;

     float forceFactor;
     Vector3 floatForce;
     public Transform pointOfBuyancy;

      void FixedUpdate () {

        forceFactor = 1.0f - ((transform.position.y - waterLevel) / floatThreshhold);
        if(forceFactor > 0.0f)
        {
           floatForce = -Physics.gravity * GetComponent<Rigidbody>().mass * (forceFactor - GetComponent<Rigidbody>().velocity.y * waterDensity);
           floatForce += new Vector3(0.0f, -downForce * GetComponent<Rigidbody>().mass, 0.0f);
           GetComponent<Rigidbody>().AddForceAtPosition(floatForce, pointOfBuyancy.position);
        }
     }
  }

```

the `Transform` named `pointOfBuyancy` is an empty placed above the ship model. This is where the floating force is applied, acting as a pendulum to stabilize the ship. This script works very well, and doesn't require changes.

The control script is called `SimpleBoatController.cs`, and is as follows:

```
  // Denis Labrecque, copy of #02 Boat Movement - How to make a Boat Controller - Unity 3D on YouTube

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

  [RequireComponent(typeof(Rigidbody))]
  [RequireComponent(typeof(Boat))]
  public class SimpleBoatController : MonoBehaviour {

     public float movementThreshold = 0.2f;
     public float turnThreshold = 0.2f;
     public float maxSpeed = 30.0f;

     public Transform pointOfEngine;

     Rigidbody rigidbody;
     Transform centerOfMassTransform;
     float waterDynamicFactor;
     float verticalInput;
     float movementFactor;
     float horizontalInput;
     float steerFactor;

     public float CurrentSpeed { get; private set; }

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

      // Update is called once per frame
      void Update () {
        // Assign properties
        CurrentSpeed = rigidbody.velocity.x;

        Move();
      }

     void Move()
     {
        // Receive player input
        verticalInput = Input.GetAxis("Vertical");
        horizontalInput = Input.GetAxis("Horizontal");

        // Calculate factors
        movementFactor = Mathf.Lerp(movementFactor, verticalInput, Time.deltaTime * movementThreshold);
        steerFactor = Mathf.Lerp(steerFactor, horizontalInput, Time.deltaTime * turnThreshold);

        // Move forwards
        rigidbody.AddForceAtPosition(new Vector3(movementFactor * rigidbody.mass * maxSpeed, 0, 0), pointOfEngine.position);

        // Turn
        // https://forum.unity.com/threads/rigidbody-lookat-torque.146625/
        // rigidbody.AddTorque(Vector3.Cross(transform.forward, rigidbody.velocity), ForceMode.FORCE);
        rigidbody.AddTorque(0, transform.position.y * CurrentSpeed * 25f * horizontalInput, 0); // Rotate
        rigidbody.AddTorque(Vector3.Cross(rigidbody.velocity, transform.forward), ForceMode.Force); // Align relative to direction
        Debug.Log("Turning of " + horizontalInput);
     }
  }

```

This script requires an additional empty at the location of the center of mass of the ship, called `pointOfEngine` in the code, where the ship is pushed forwards. This works very well.

My difficulty is in the **move** method, when it comes to applying rotation.

Because the flotation script does not apply any angular drag, the boat rotates without turning in the direction of rotation. It makes a flat spin and wobbles like over jellow -- which looks good, but just doesn't allow controlling the boat.

How can I make the boat travel in an arc, and not just back and forth while making a flat spin?

I have searched various physics answers about rotation and wind resistance, but these don't apply to my problem.

# Answer
> 0 votes
I use the following for the boat control:

```
public Vector3 COM;
[Space (15)]
public float speed = 1.0f;
public float steerSpeed = 1.0f;
public float movementThresold = 10.0f;

Transform m_COM;
float verticalInput;
float movementFactor;
float horizontalInput;
float steerFactor;

public GameObject Rudder;

// Update is called once per frame
void Update () {
    Balance ();
    Movement ();
    Steer ();
}

void Balance () {
    if (!m_COM) {
        m_COM = new GameObject ("COM").transform;
        m_COM.SetParent (transform);
    }

    m_COM.position = COM;
    GetComponent<Rigidbody> ().centerOfMass = m_COM.position;
}

void Movement () {
    verticalInput = Input.GetAxis ("Vertical");
    movementFactor = Mathf.Lerp (movementFactor, verticalInput, Time.deltaTime / movementThresold);
    transform.Translate (0.0f, 0.0f, movementFactor * speed);
}

void Steer () {
    horizontalInput = Input.GetAxis ("Horizontal");
    steerFactor = Mathf.Lerp (steerFactor, horizontalInput * verticalInput, Time.deltaTime / movementThresold);
    transform.Rotate (0.0f, steerFactor * steerSpeed, 0.0f);

    // To move the physical rudder wheel on the deck
    Rudder.transform.Rotate(Vector3.down, steerFactor * steerSpeed * 5f);
}

```

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


title: MacOS Mojave makes SDL2 unaccessible

text:
# Question
Title: MacOS Mojave makes SDL2 unaccessible
I have some code that worked with no issues on MacOS Sierra, but when I update to Mojave, my compiler always says that it can't find SDL2.

Here's the error:

```
20:24:40 **** Incremental Build of configuration Debug for project Causality ****
make all
Building file: ../src/engine/SE.cpp
Invoking: Cross G++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/engine/SE.d" -MT"src/engine/SE.o" -o "src/engine/SE.o" "../src/engine/SE.cpp"
In file included from ../src/engine/SE.cpp:1:
../src/engine/SE.h:6:10: fatal error: 'SDL2/SDL_events.h' file not found
#include <SDL2/SDL_events.h>
         ^~~~~~~~~~~~~~~~~~~
1 error generated.
make: *** [src/engine/SE.o] Error 1
"make all" terminated with exit code 2. Build might be incomplete.

20:24:42 Build Failed. 2 errors, 0 warnings. (took 1s.304ms)

```

I'm using SDL 2.0.9

My project structure is this:

```
src
|main.cpp
|engine
 |SE.h
 |SE.cpp
 |SE_Audio.h
 |SE_Audio.cpp
 |SE_Graphics.h
 |SE_Graphics.cpp
 |SE_Input.h
 |SE_Input.cpp
 |SE_Structs.h

```

I'm including the libraries with `-framework SDL2 -framework Cocoa -framework SDL2_image`

I'm using the exact same settings that I used before and that worked in MacOS Sierra. Please tell me what more details you need before down-voting

# Answer
> 0 votes
I ended up just changing my IDE to Xcode and that somehow fixed it. Guess I'm using that now.

# Answer
> 0 votes
I've been on Mojave for a bit and haven't run into any compile issues with SDL2. I also do not use Xcode, but rather compile from the command line interface. In my call to `g++` I include framework location with:

```
-F/Library/Frameworks -framework SDL2 -framework SDL2_image -framework SDL2_ttf -framework SDL2_mixer

```

Hope it helps.

---
Tags: c++, sdl2, macos
---


title: Cant make SFML work

text:
# Question
Title: Cant make SFML work
I am having an error when I try to create the first window in SFML.

the error says: The code execution cannot proceed because sfml-system-d-2.dll was not found. Reinstalling the program may fix the problem.

All my includes work and i have no syntax error

# Answer
> 0 votes
In your project folder, the same one with your stdafx.h file, you need to place the sfml .dll files. When you are setting up your sfml project under project properties -\> Debug -\> Linker -\> Input (Additional Dependencies) you should have sfml-graphics-d.lib...etc. Then you have to make sure that you copy these .dll files into your main project folder.

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


# Question
Title: How to make a single action run for two objects in GAME MAKER?
Think of a traffic light that only turns green or red.

If it is green, the next car passing through the detection point (pink square) will be directed to the green path and will cause the traffic light to turn red.

This way the next car that passes, will be directed to the red path, also making the green light, and so on.

Let's assume that two cars are in the same place and at the same speed and thus collide with the pink square at the same time. How can we make both directions to the same path be green or red and so that the light of the traffic light changes only once?

Considering "obj\_BolaAzul" as "obj\_blueCar", "obj\_BolaRoxa" as "obj\_purpleCar" and "obj\_Cannon" as "obj\_trafficLight".

The codes are basically:

```
obj_traficLight collision with obj_blueCar

if greenLight==true{
  obj_blueCar.move_towards_point(x+1,y,manSpeed); //go to right
  testGreen=true;
}

if redLight==true{
  obj_blueCar.move_towards_point(x-1,y,manSpeed); //go to left
  testRed=true;
}

if testGreen==true{
  greenLight=false;
  redLight=true
}

if testRed==false{
  redLight=false;
  greenLight=true
}
```

There are more things besides in code, but it has no relation to the problem.

I'm sorry again for the translation errors, I'm still not speaking English.

# Answer
> 0 votes
The solution is to add a value to a variable **x** after the collision of any of the cars, so that it will only modify the traffic light after all cars have passed the traffic light.

Then you makes equal the value of the variable that modifies the semaphore **y** to that of the variable **x** in the step event.

In code:

```
collision event:

if y==10{
  car to red way;
  x=20;
}

if y==20{
  car to green way;
  x=10;
}

----------------------------------------------------------------------------------------------
step event:

if x==10{
  y=10;
}

if x==20{
  y=20;
}
```

---
Tags: game-maker
---


# Question
Title: Is Patreon a viable way to implement a subscription-based monetization strategy?
I am looking for an alternative to premium currency and microtransactions as a monetization strategy for a persistent browser game. Subscriptions seem the straightforward solution, though I don't want to set up my own payment system.

**Can I use Patreon (or similar membership platforms) as a way to limit access to a premium server, or access to the game itself, for patrons only?**

I couldn't find it in their guidelines if this sort of implementation is allowed.

# Answer
After further digging into Patreon material, I found a blog post from them that answers my question. It puts subscription as one of the one of the business models one can use the platform for.

> ## 6. Service/Product Model
>
> Defined as: a specific service or product offered in exchange for monthly pledges.
>
> This category is closer to many ‘normal’ businesses: think software in exchange for monthly subscriptions, recurring consulting appointments, or commissions. It’s an exchange of time or physical goods for money.
> 4 votes

---
Tags: browser-based-games, monetization
---


title: how to use 2D noise with a voxel sphere

text:
# Question
Title: how to use 2D noise with a voxel sphere
I have a bunch of voxels, lets just say 64x64x64, that I use to create a sphere/planet. This works very well, but once I try to apply noise to create a more interesting terrain things go wrong.

3D noise works fine, but I don't always want to create terrain with caves, overhangs etc, so I figured in those cases 2D noise would be a good solution, but I can't figure out how to use it correctly.

I tried this, where pos (world position) is a float3 and x and y are the input values for the noise function:

```
float x = math.acos(pos.z / math.length(pos));
float y = math.atan(pos.y / pos.x);

```

That results in a very noticeable seam along one axis and pinching at the poles though.

Is there any way I can convert my 3D world position into 2D coordinates, so that the noise function (Perlin or Simplex) will produce a seamless result without pinching? I don't mind in the least if this causes symmetry or repeating features.

# Answer
There is no perfect way to map the surface of a sphere to a flat plane - you always get seams or stretching/pinching somewhere. This is why map projections are such a rich subject - every one offers different trade-offs that are good for some uses and less good for others.

A better route for your purposes is probably to continue using your 3D noise, but sample just a 2D manifold out of it:

```
GetSphereSurfaceNoise(float3 worldPosition, float3 center) {
    float3 surfacePosition = normalize(worldPosition - center) * noiseRadius;
    return GetNoise(surfacePosition);
}

```

This ensures all samples along a ray radiating out from the center of your sphere get the same noise value, so you can raise/lower whole columns of terrain without creating caves/overhangs, and the result will be continuous & seamless all around your sphere.

Tuning the `noiseRadius` parameter lets you control the density of the noise (scaling up or down the 2D shell you're sampling from in noise space)
> 2 votes

---
Tags: voxels, perlin-noise, sphere
---


# Question
Title: how to check if an array element is defined? (Game-maker studio)
The code is this:

```
if is_undefined(A_SA[V_X,V_Y])=false and A_SA[V_X,V_Y]=0
{
//actions from the "if" statement
}

```

The error message is this:

```
Push :: Execution Error - Variable Index [0,10] out of range [10,10] - -1.A_SA(100006,10)
 at gml_Object_objt_Canvas_StepNormalEvent_2 (line 25) -         if is_undefined(A_SA[V_X,V_Y])=false and A_SA[V_X,V_Y]=0

```

Why is this happening and how can I stop game-maker from trying to check the value of a variable outside of an array?

# Answer
`is_undefined` can be used for `ds_map` and doesn't work with arrays.

Initialize array by values, which won't cross with values you will use later. For example, if you will use values `0` and greater, then you can initialize by negative value `-1`.

If you will use any values in full available range then you need create other array with same size where each cell will show, is initialized same cell of other array, or not.

Or you can use `ds_map` with `is_undefined`, where index will be used as key.

About `Variable Index [0,10] out of range [10,10]`. If array size is 10, then maximum index is 9.
> 0 votes

# Answer
You can also check if each element is a null pointer, for an array is a list of locations that point to space in data, by default all of them are set to a null value that can be accessed with pointer\_null. in my game I use it to remember a list of 4 specific instances and access their states, like this:

```
if ( playerlist[0] != pointer_null && instance_exists( playerlist[0] ) )
{
    if playerlist[0] .state == state_dead { global.player1 = false; }
}
else
{ global.player1 = false; }

```
> 0 votes

---
Tags: data-structure, game-maker
---


# Question
Title: How To Destroy/Deactivate one enemy without affecting other enemies of the same type?
In my game, you jump on zombies'heads to squash them.

Currently I'm only able to have one zombie in my game. When I add another (duplicate or drag from prefab), then run the game, I can squash one enemy but when I try to jump on the second zombie's head it says "Coroutine couldn't be started because the game object "Zombie (1)" is inactive".

Here's the player's stompbox script code & below that the ZombieController script code:

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

public class StompEnemy : MonoBehaviour {

    private Rigidbody2D playerRigidbody;
    public ZombieController zombieController;

    public float bounceForce;
    // a bounce force of 12 is wonderful (set in unity's inspector)

    // Use this for initialization
    void Start () {
        playerRigidbody = transform.parent.GetComponent<Rigidbody2D>();
        zombieController = FindObjectOfType<ZombieController>();
    }

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

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Zombie")
        {
            zombieController.Stomped();
            playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, bounceForce);
        }
    }

}

```

Now here's the ZombieController script code:

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

public class ZombieController : MonoBehaviour {

    Animator zombieAnimator;
    Rigidbody2D myRigidBody;
    [SerializeField] float moveSpeed = 1f;

    public bool isAlive = true;

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

    // Update is called once per frame
    void Update () {
        if (!isAlive) { return; }
        if (isFacingRight())
        {
            myRigidBody.velocity = new Vector2(moveSpeed, 0f);
        }
        else
        {
            myRigidBody.velocity = new Vector2(-moveSpeed, 0f);
        }
    }

    bool isFacingRight()
    {
        return transform.localScale.x > 0;
        // if it's positive he's facing right, and if negative, facing left.
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        transform.localScale = new Vector2(-(Mathf.Sign(myRigidBody.velocity.x)), 1f);
    }

    public void Stomped()
    {
        isAlive = false;
        transform.localScale = new Vector2(-(Mathf.Sign(myRigidBody.velocity.x)), 1f);
        zombieAnimator.SetBool("Squash", true);
        if (isFacingRight())
        {
            myRigidBody.velocity = new Vector2(Mathf.Epsilon, 0f);
        }
        else if (!isFacingRight())
        {
            myRigidBody.velocity = new Vector2(-Mathf.Epsilon, 0f);
        }
        gameObject.layer = 11;
        StartCoroutine(WaitXSecond());
    }

    public IEnumerator WaitXSecond()
    {
        yield return new WaitForSeconds(2f);
        gameObject.SetActive(false);
        zombieAnimator.SetBool("Squash", false);
    }

}

```

How do I implement multiple zombies using the same script attached to each one?

When I've tried having three zombies I'd jump on the first one's head and another zombie would die (show the squashed animation, then disappear after two seconds) and the remaining zombies would no longer be jump-on-head-able, displaying the coroutine error above.

# Answer
Your problem is these two lines:

```
zombieController = FindObjectOfType<ZombieController>();

```

This says "give me *the first* `ZombieController` you find in the scene"

```
zombieController.Stomped();

```

This says "squash *that specific zombie* you found for me earlier" - ie. it doesn't care whether that's the zombie you actually landed on, or whether this zombie is still alive. You've set up your script so that one and only one zombie is predestined to receive every stomp.

To avoid this, I'd recommend centralizing the work of handling *being squashed* on the object that can be squashed. That way, any squashing always applies to "me," making it trivial to ensure it's hitting the right target.

Presumably you'll want other things you can squash beyond zombies (eg. other monster types, powerups, maybe even the player themselves (from falling blocks/etc), so let's separate the concept of `Squashable` from the concept of `Zombie` while we're at it.

First, we'll use a very simple script to mark our collider that does the squashing. You can also do this with tags, but doing it with a script lets you attach parameters to it (eg. a damage value dealt by this squasher, or flags for selective squash immunity, so you can ensure players don't squash other players)

```
public class Squasher : MonoBehaviour { }

```

Next we'll define our script for being squashed. I've set this up generically so it can work on anything that has a squash animation, so you minimize code duplication if you add other squashable types later.

```
public class Squashable : MonoBehaviour {

    bool squashed = false;

    void OnTriggerEnter2D(Collider2D other) {
        // Don't double-squash if you get two trigger enter messages at once.
        if(squashed)
           return;

        // Only squash if we got hit by a squasher collider.
        // (Can check that it came from above too)
        var squasher = other.GetComponent<Squasher>();
        if(squasher == null)
            return;

        StartCoroutine(SquashMe());
    }

    IEnumerator SquashMe() {
        squashed = true;

        var animator = GetComponent<Animator>();
        if(animator != null)
            animator.SetBool("Squash", true);

        var body = GetComponent<RigidBody2D>();
        if(body != null)
            body = new Vector2(Mathf.Epsilon * Mathf.Sign(transform.localScale.x), 0f);

        // Make your Zombie controller or other monster AI implement this interface,
        // so we can switch off their behaviour / award score or pickups as needed,
        // without the Squash logic knowing anything about "zombies."
        var killable = GetComponent<IKillable>();
        if(killable != null)
            killable.Kill();

        int oldLayer = gameObject.layer;
        gameObject.layer = 11;

        yield return new WaitForSeconds(2f);

        // Hide this object and put all its components back the way we found them.
        gameObject.SetActive(false);
        gameObject.layer = oldLayer;
        if(animator != null)
            animator.SetBool("Squash", false);
        if(killable != null)
            killable.Resurrect();
        squashed = false;
    }
}

```
> 1 votes

# Answer
```
public IEnumerator WaitXSecond()
{
    yield return new WaitForSeconds(2f);
    gameObject.SetActive(false);
    zombieAnimator.SetBool("Squash", false);
}

```

You are calling gameObject.SetActive(false) from within the ZombieController. You are actually disabling the ZombieController gameobject rather than the StompEnemy.

Try passing in a reference to your StompEnemy gameobject and call SetActive(false) on that instead.

```
public IEnumerator WaitXSecond(GameObject enemyObject)
{
    yield return new WaitForSeconds(2f);
    enemyObject.SetActive(false);
    zombieAnimator.SetBool("Squash", false);
}

```
> 0 votes

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


# Question
Title: Object activate it self without script order?
I have strange thing here in my script. In this script clock\_time turn active lamp object one by one. Where Lamp object turn off after 3 seconds be anther script. If clock time reach 120 or higher again lamp turn active !! Also, light\_timer keep counting if lamp is active ??

```
 public GameObject[] lights; // 3 lamps
public int number;
public int[] light_timer; // 3 values "2,4,6"
public int clock_timer;

void Start()
{
    // all gameObject "lamps" is off
    number = lights.Length -1;

}
void Update()
{
    if (gameObject.activeInHierarchy == true)
    {
        clock_timer = (int)Time.time;
    }
    else
    {
        clock_timer = 0;
    }
    for (int i = 0; i < lights.Length; i++)
    {

        if (clock_timer >= light_timer[i] && lights[i].activeInHierarchy == false)
        {
            lights[i].SetActive(true);
        }

        if (lights[i].activeInHierarchy == true)
        {
            light_timer[i] = light_timer[i] + 1;
            print("me : " + i);
        }

    }

}

```

# Answer
> 0 votes
I solved. It's my mistake. All what i have to do is...

```
  for (int i = 0; i < lights.Length; i++)
    {

        if (clock_timer == light_timer[i] && lights[i].activeInHierarchy == false)
        {
            lights[i].SetActive(true);
        }

    }

```

Anyway,Thank you..^-^'..

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