# Question
Title: Simple stupid funnel algorithm without visible points
In the simple stupid funnel algorithm we are searching for consecutive portals points, that are tightening the funnel (the angle between the current left and right point decreases).

But what when there is no single visible point, that would tighten the funnel, like presented on image below. How to determinate next apex and current left and right point?

# Answer
You first determine the left and right points of the funnel as the left and right points of the closest portal, then correct these points every time you find a point inside the funnel.

To determine the apex you also need to find a point that produces a turn. It either a left point of a portal that happens to be on the right side of the funnel or vice versa a right point of a portal that is on the left side of the funnel.

The steps below show how to determine the first apex from your example.

1. Considering that we enumerated points this way, we first set A as the tightest point from the right side and B as the tightest point from the left side.

2. We check the next portal. The **left** point of it (C) is on the **left** side of the funnel. So we ignore C.

3. We check the third portal. The **right** point (D) is on the **right** side of the funnel. Skip D as well.

4. We check the fourth portal. Its **left** point (E) is on the **right** side of the funnel. That means we have a turn to the **right**.

At this point, we restart the algorithm from the tightest right point of the funnel (A) and also add A to our smoothed path.

This answer provides a step-by-step demonstration that covers the general solution in more detail.
> 2 votes

---
Tags: algorithm, path-finding
---


# Question
Title: How to store and update presentation strings describing effects with parameters?
**Consider this spell:**

As you can see in my design a `Spell` is a composition of one or more `Effect`s. An Effect has properties on it like `value`, `range`, etc. So, I can say that the `Spell Description` is an aggregate description of the composition of effects.

**Presentation Layer**

In my presentation, I want to decorate part of the description string in HTML tags and display as rich text. I also want to ensure that my string's numeric values come from data.

**Solution 1**

Simply hard code the string. In this case the spell description would look like: `Choose a target within <#f4b350>4</color> squares. Deal <#f33613>4</color> damage to that target and restore your HP by <#3cf73c>50%</color> of the damage done.`

This approach has some obvious issues, namely:

* Changing the color value of a particular tag would be a nightmare when there are hundreds of abilities
* Changing the damage value of a spell means updating it in two places, the string and the data

**Solution 2**

Create a tag series separated by `_` that indicates various properties. I could for example, do something like `Deal {subtractive_value} damage to that target` with the idea that when I go to parse the string, `subtractive` could be a tag indicating a red color, and `value` can be a tag indicating that its the effect's value that should go there.

This is all fine except that a spell can have multiple effects. I need a way to associate the part of the description with the specific effect that drives it.

**Modification to Solution 2**

So then I suppose I could just add IDs to the spell effects such that the string defined in data becomes:

`Choose a target within {neutral_damageEffect_range} squares. Deal {subtractive_damageEffect_value} damage to that target and restore your HP by {additive_healEffect_value}.`

But now you see that its getting a bit cumbersome and I'm dubious of how scalable that solution is.

**Non-Goal**

Lastly I figured I'd mention a non-goal. If you take my approach thus far to its ultimate conclusion, you would probably end up with trying to find a way to generate your description text from the effect themselves. While this is an interesting idea, I think it's a bit too ambitious, so I'm specifically not trying to do that. That said, if you feel like that's easier than I think it is, feel free to make that suggestion!

**Question**

So, given what I've tried and the problem I'm trying to solve, there's no way this is a unique problem to me. **Is there a battle-tested solution to this problem? What's a good way to go about it or some patterns to use I might not know about?**

**EDIT**

Some have asked for some code, it is lengthy though so I can just link to a gist here: https://gist.github.com/jsandersr/ef6d560ad95f1d63b1f8e3b2099038a5

# Answer
To keep the markup in your strings concise, I'm going to assume that we can infer the style to use for a value from the effect we're reading it from. For example, if I'm reading `DamageEffect._value`, I want it to be rendered in "damage red", but if I'm reading `HealingEffect._value`, I want it to be rendered in "healing green".

This relationship doesn't need to be one-to-one. I could have multiple different damage effects that all use the same "damage red" style, or a `VampiricEffect` type that does damage and renders its value in "healing green", etc.

With this approach, we can write your example fairly concisely and intuitively as:

> Choose a target within {DamageRange} squares. Deal {DamageValue} damage to that target and restore your HP by {HealingValue}.

If you want to specify the styling, source, and member explicitly in the string, you can of course support that - but I think the simplicity here is worth the restrictions it imposes, since those restrictions also make it easy to stay consistent. You won't have to track down bugs where one stray text string out of the thousands is using the wrong format for damage values, if it's not the string's job to specify the formatting.

First, let's set aside an enumeration to standardize our vocabulary of text styles. That way we're not passing stringly-typed tokens around everywhere. I chose to put this inside a ScriptableObject we can use to edit our mapping of style preset IDs to their corresponding styling information.

```
public class TextStyle : ScriptableObject
{
    public enum Preset {
        Default,
        Damage,
        Healing,
        Duration,
        Target,
        Range,
        Special
    }

    [System.Serializable]
    struct Style {
        public Preset preset;
        public Color32 colour;
        public string numericFormat;
    }

    [SerializeField]
    List<Style> _styles;

    int GetStyleIndex(Preset preset) {
        return _styles.FindIndex(s => s.preset == preset);
    }

    // ...More to come...
}

```

We can obviously get more sophisticated than this, but already this gives us a functional way to specify colours and numeric formatting rules for each style preset.

Next, we'll add some helper methods that standardize applying these styles to a text or numeric parameter value, and packing the result into a structure useful for further localization.

```
public struct StyledText {
    readonly public string text;
    readonly public Preset style;

    // It's useful to tag replaced text with this info, so you can refer to it
    // and correctly substitute "You have 1 item" vs "You have 2 items".
    readonly public int pluralClass;

    public StyledText(string text, Preset style, int pluralClass = 0) {
        this.text = text;
        this.pluralClass = pluralClass;
        this.style = style;
    }
}

public StyledText Stylize(string text, Preset preset) {
    int index = GetStyleIndex(preset);
    if (index < 0)
        return Stylize(text);

    return Stylize(text, index);
}

public StyledText Stylize(float value, Preset preset) {
    int index = GetStyleIndex(preset);
    if (index < 0)
        return Stylize(value.ToString());

    string text = value.ToString(_styles[index].numericFormat);
    return Stylize(text, index, GetPluralClass(value));
}

// Punt when we don't have a matching style, and just pass the text through as-is.
StyledText Stylize(string text) {
    return new StyledText(text, Preset.Default);
}

// Apply colour formatting and package up the result for consumption.
StyledText Stylize(string text, int presetIndex, int pluralClass = 0) {

    var colour = ColorUtility.ToHtmlStringRGB(_styles[presetIndex].colour);
    text = string.Format("<#{0}>{1}</color>", colour, text);

    return new StyledText(text, _styles[presetIndex].preset, pluralClass);
}

// This currently implements "Plural Rule #1" which works for Germanic languages like English.
// TODO: Extend to select an appropriate plural rule based on your localization settings.
// https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals
int GetPluralClass(float value) {
    if (Mathf.Approximately(value, 1f))
        return 0;

    return 1;
}

```

Why the plural stuff? I wanted to show an example of how you can pipe other useful metadata through your text substitution pipeline. In some games I've worked on, we've used this to implement sophisticated substitutions like this:

> "You have {MessageCount} new {MessageCount?message,messages}"

* if `MessageCount == 0`, prints "You have 0 new messages"
* if `MessageCount == 1`, prints "You have 1 new message"
* if `MessageCount == 2`, prints "You have 2 new messages"

What's great about this is if you build it with knowledge of different plural rules, you can easily handle translating your text data to languages that have more than one plural form, like Russian, which needs a different variation for numbers ending in 1 other than 11 (first), numbers ending in 2-4 except 12-14 (second), or everything else (third):

> У вас {MessageCount} {MessageCount?новое сообщение,новых сообщений,новых сообщения}

(This is just a Google translation - definitely don't use this in your project without paying a real translator!)

I haven't implemented that here, just shown a stub that you could extend to add support for this in future, if you have need of it.

Okay, back to the task at hand. Now we need to map from our replacement tokens to the right value to fetch and the right style to apply to it. As we did with styling presets, let's standardize the vocabulary for the parameters we might want to replace, using an enum.

```
public enum ParameterID {
    DamageValue,
    DamageRange,
    DamageDuration,
    HealingValue,
    HealingRange,
    HealingDuration
    // Add more as needed...
}

```

You could put the mapping from this vocabulary to the effects to data source and style in a lot of different places, but for simplicity I decided to put it into the `Effect` class itself.

```
// Sets a contract for data structures we can ask to provide parameter values
// and associated styling appropriate to their use.
public interface IParameterSource {
    bool TryGetStyledParameter(
                  ParameterID param,
                  TextStyle style,
                  ref TextStyle.StyledText styled);
}

public abstract class Effect : IParameterSource
{
    // ... rest of your implementation...

    // Implement the interface.
    public virtual bool TryGetStyledParameter(
                           ParameterID param,
                           TextStyle style,
                           ref TextStyle.StyledText styled) {
        return false;
    }
}

```

Now each subtype can claim the parameters it can supply, and map them to the right style to use for its context.

```
public class DamageEffect : Effect
{
    public override bool TryGetStyledParameter(
                                 ParameterID param,
                                 TextStyle style,
                                 ref TextStyle.StyledText styled) {
        switch(param) {
            case Parameter.DamageValue:
                styled = style.Stylize(_value, TextStyle.Preset.Damage);
                return true;
            case Parameter.DamageRange:
                styled = style.Stylize(_value, TextStyle.Preset.Range);
                return true;
            case Parameter.DamageDuration:
                styled = style.Stylize(_value, TextStyle.Preset.Duration);
                return true;
            default:
                return false;
        }
    }
}

```

The advantage of doing it this way is that multiple subtypes can share the same parameter, so we don't need to explode our parameter vocabulary if we have a dozen different versions of the `DamageEffect`. When we need to substitute the `{DamageValue}` keyword, we'll just grab the first effect in the list that knows how to provide a matching value.

You can also include logic here where needed to vary the style based on the value - like rendering a currency value in red if it's negative but green if it's positive - or other parameters on the effect - like an `ElementalDamageEffect` that renders its `DamageValue` in different colours depending on the value of its `DamageElement` property.

Finally it all comes together. We'll have a function that...

1. Finds all the `{ParameterName}` tokens in our text template, and parses them to their corresponding enum value.
2. Walks through the list of Effects to find one that has a value for this parameter.
3. Replaces the token with the styled text from the matching effect.

Here's a simple version of that. I put it in my `TextStyle` class, but you could implement it elsewhere instead:

```
static readonly Regex PARAMETER_TOKEN_FINDER = new Regex(@"{(\w+)}");

public string StylizeParameters(string template, List<IParameterSource> sources) {
    string replaced = template;

    var matches = PARAMETER_TOKEN_FINDER.Matches(template);

    foreach(Match match in matches) {

        string token = match.Groups[1].Value;

        if(!System.Enum.TryParse(token, out ParameterID param)) {
            Debug.LogWarningFormat("Unknown tag in text string: {0}", token);
            continue;
        }

        StyledText replacement = default;
        bool matched = false;
        foreach(var source in sources) {
            if (source.TryGetStyledParameter(param, this, ref replacement)) {
                matched = true;
                break;
            }
        }

        if(!matched) {
            Debug.LogWarningFormat("No parameter source matches token: {0}", token);
            continue;
        }

        replaced = replaced.Replace(match.Value, replacement.text);
    }

    return replaced;
}

```

Because this will work with anything that implements the `IParameterSource` interface, you could slap an implementation of that interface on all sorts of data structures in your game that you might want to dig values out of for text replacement, like the player character, their inventory, or any number of UI systems.
> 1 votes

# Answer
Based on your question, I think you have a good grasp of what your problem is, and what potential solutions you have, but you are having trouble with deciding which solution to use. Therefore, my answer will be focused on that.

I suppose you are making this project because you actually want to ship a game, so you want to minimize the amount of effort that will take to build an abstraction, write the data for such abstraction, and minimize the effort that will take to modify that data. Based on this assumption, the main consideration when making design choices, should be:

> If I spend X hours to make this abstraction, so it will later save me Y hours, is X \< Y?

Let's dissect X and Y a bit more. For X, the amount of time that it takes to write an abstraction layer is not the only thing that counts; the amount of time you spend thinking about the problem, and even the amount of time it took you to write this question here at StackExchange, is definitely part of X. There are two pieces of advice I can give you when calculating X:

* It is very easy to underestimate X. Just like any other system, the amount of time it takes to build and maintain a system, grows exponentially to the complexity of such system. Corollary: simple systems are *much* easier to build and maintain than complex ones.
* It takes a lot of determination to drop a system to which you have already invested time on. In other words, if you start building a system, and you then learn you didn't need it, it is very easy to fall in the trap of thinking that you might as well finish it, since you already started it. *Especially* for complex systems.

As for Y, a good way of estimating it is by defining it as Y = k * (S - R), where k is the amount of data that the system uses, S is the amount of time it would take to build and maintain that piece of data *without* the abstraction, and R is the amount of time it will take to build and maintain that piece of data *with* the abstraction. There are some observations to be made here:

* The smaller k is, the less worth it is to make an abstraction. For your specific system, consider how many spells your game will have. If it has something in the order of 10~50, it may not be worth writing a whole abstraction for so few spells. If you're having hundreds to thousands of different spells, then abstracting it may sound better and better.
* As engineers, we like overestimating S. You said that you are worried about the possibility of changing a color, which will require you to go through every string changing it. But how about writing the data in a text file and using find-and-replace? or how about writing a simple regex that changes the colors each time you want to change them? In other words: is the actual problem as big as you think it is?
* Also, as engineers, we like underestimating R. Going back to the color issue, it is possible that the majority of the time spent adjusting the color will not be spent actually changing the color definition, but compiling the game, launching it, going to the actual screen where you can view the color, and deciding whether it needs changing or not. This time is consumed regardless of whether you have an abstraction or not.

Furthermore, as you build an abstraction, and especially, the earliest you start building it, you might fall into either one of the following paths:

* Your abstraction is too specific, and any additional flexibility you need will further increase X exponentially.
* Your abstraction is too general, and becomes nothing more than a convoluted Enterprise Rules Engine. The result is that configuring your system can even take longer than if there was no system to begin with!

It may seem as if I'm suggesting you don't make an abstraction, and I probably am a bit. If you're making a game, I think there will be dozens to hundreds of other problems that you will face, and you can end up spending much more time building abstractions than actually building the game. That's a great way to get demotivated and give up on making a game.

As controversial as it seems, hard coding is not a bad thing. My suggestion is to start building without any abstractions, and only build abstractions for specific problems that you're facing, when the time you've already spent without the abstraction is the same as the time it would take to build such an abstraction (view the ski rental problem).

What I said above is my interpretation of Donald Knuth's quote:

"Premature optimization is the root of all evil"
> 1 votes

---
Tags: unity, data-structure, text, localization
---


# Question
Title: How do I smooth out the edges at the end of the threshold on noise?
I'm making a terrain generator for a game and I need it to smooth down to a float, I've tried a bunch of different things with lerping but I can't figure it out.

I need to stop this from happening by smoothing the height down to 1 once it gets to the edges.

```
public LevelManager level;

public float noise;
public float oceanNoise;
public float mountainNoise;

public Transform water;
public Transform land;

public void Start()
{
    level = FindObjectOfType<LevelManager>();

}
public void Update()
{
    float landNoise = noise + oceanNoise;
    noise = SimplexNoise.Noise(transform.position.x * level.deatalscale, transform.position.z * level.deatalscale);
    oceanNoise = SimplexNoise.Noise(transform.position.x * level.oceanDetailScale, transform.position.z * level.oceanDetailScale);
    mountainNoise= SimplexNoise.Noise(transform.position.x * level.mountainDetailScale, transform.position.z * level.mountainDetailScale);

    if (noise > level.thresh)
    {
        land.gameObject.SetActive(true);
        water.gameObject.SetActive(false);

    }
    else
    {
        land.gameObject.SetActive(false);
        water.gameObject.SetActive(true);

    }

    if (oceanNoise < level.oceanHhresh)
    {
        land.gameObject.SetActive(false);
        water.gameObject.SetActive(true);

    }

    if (oceanNoise < level.oceanHhresh)
    {
        land.gameObject.SetActive(false);
        water.gameObject.SetActive(true);

    }
    land.transform.localScale = new Vector3(level.planeScale, Mathf.Lerp(noise*level.height,1,noise) * level.height + level.addHeight, level.planeScale);

    if (level.landpos.Contains(transform.position))
    {
        Destroy(gameObject);
    }
}

```

This script goes on the terrain chunk and it uses its position to find value in noise, the level manager just holds a few settings.

Any help is appreciated, thanks in advance.

# Answer
> 2 votes
I don't recommend using code like this for terrain generation, for several reasons:

1. You don't want to be re-processing your terrain in every Update. If your terrain parameters can change on the fly, call a `Regenerate()` function to do this work only when such a change occurs.
2. You don't want a separate object for every cell of your world. I know it *looks like* Minecraft and similar games are made of millions of separate cube objects, but they are not. They build chunk meshes that represent the visible outer surface of whole regions of the map at a time, so they don't have millions of mesh instances to render, or millions of scripts running every frame.
3. You don't want two noise functions battling over the same outcome. Right now your `noise` parameter determines the height of the land, but the `oceanNoise` parameter determines whether the land even exists. So in many cases the land will just stop abruptly, not because `noise` dropped down below the water level, but because the otherwise-invisible `oceanNoise` overruled it.

For a single cell, it looks like you want something like this:

```
void Regenerate() {
    float noise = SimplexNoise.Noise(transform.position.x * level.detailScale,
                                     transform.position.z * level.detailScale);

    bool isLand = noise > level.thresh;

    land.gameObject.SetActive(isLand);
    water.gameObject.SetActive(!isLand);

    if(isLand) {
        var scale = Vector3.one * level.planeScale;

        float surplus = (noise - level.thresh) / (MAX_NOISE_VALUE - level.thresh);
        scale.y = level.scaleToMatchOceanLevel + surplus * level.landScale;
        land.transform.localScale = scale;
    }
}

```

This way you'll get ocean where the land sinks low enough to hit the water level, and land elsewhere. Because the ocean occurs only where the land is low, you'll naturally get a falloff from land to water, instead of sudden cliffs.

---
Tags: unity, c#, noise, simplex-noise
---


# Question
Title: SDL_CreateTextureFromSurface not working
Code:

```
SDL_Surface* tmpSurface = IMG_Load("Assets/Player.png");
playerTex = SDL_CreateTextureFromSurface(renderer, tmpSurface);
SDL_FreeSurface(tmpSurface);

```

Rendering the Texture:

```
SDL_RenderCopy(renderer, playerTex, NULL, NULL);

```

I did check to see if any of them returned null and playerTex is still null even though it is being set to a texture, im not sure why can anyone help

# Answer
> 0 votes
I fixed this: I was creating a new renderer when I was initializing the texture instead of reusing the public one.

Using `SDL_GetError` helped me figure this out.

---
Tags: textures, sdl2
---


# Question
Title: Using enemy, player and gun position can player shoot enemy?
I was asked this question in an interview last week and I've been thinking about it but I'm unsure how to solve it.

You are on a spaceship and want to shoot the enemy space ship. You have the enemy position, your position, your gun position, the radius of the enemy and the radius of your gun. Assume the normal is facing forward.

So basically the function is like canHit(Vector3 enemyPosition, Vector3 playerPosition, Vector3 gunPosition, float enemyRadius, float bulletRadius)

I figured I would have to subtract the vectors and get the dot product to check if the enemy was in front of the player. Then I thought maybe I should cross the enemy and the gun to see if they intersect and if they don't check if the radius of the bullet plus the gun position is would reach the enemy. I know this is incorrect, so I'm curious how to go about solving this problem.

# Answer
> -1 votes
Using Raycast is one solution.

Raycast from the gun and check if the ray cast hits the enemy radius.

---
Tags: mathematics
---


# Question
Title: C++ Mouse picking for ray to plane intersection
I'm making a C++/OpenGL application (decidedly without GLM), and I'd like to understand how to create a ray from the camera eye to the mouse pointer, as well as detect an intersection point from the resulting ray onto a flat plane.

I have: \- Camera position, camera pitch/yaw, camera's Fwd vector \- mouse coordinates in pixel measurements (which I can convert to -1:+1 screen space) \- A world system where XY are the horizontal and Z is up \- A flat plane where Z=0 \- My own matrix class which is basically just a float\[16\] and accessed (Get()) as a float\* \- Basic matrix multiply function, cross, dot product functions.

I'm still trying to learn 3D math (this project is somewhat of a reason for that), so I'm still somewhat hazy on how to accomplish this. Most tutorials I can find are Unity tutorials, or involve using an Unproject function from glu or GLM.

I'd hopefully like to understand how to accomplish this manually as I'd like to understand what's happening. Thank you for any wisdom or guidance.

# Answer
> 2 votes
Ok: Math hat on:

In computer graphics/games, you typically work in a couple of frames of reference:

1. local/object space
2. world space
3. view space
4. screen space

Local space is represented by relative to the origin of whatever 3d mesh you want to draw.

World space is relative to the game world, i.e. the mesh translated to a position in the world, and rotated to an orientation within the world.

View space is relative to the camera, i.e is it behind, in front of, above, below etc the camera, and by how much. Think of it this way: I Tell you to meet me at the entrance of the Empire State building in New York. That is the world position. From my perspective (view space), it is simply two metres in front of me.

Screen space is when everything is transposed onto the 2d screen and scaled down for display.

So, to get from local space to screen space we have to apply what are known as **affine transformations**, using 4x4 matrices.

The basic construction of a transform matrix is as follows:

```
[ R    U     F    T]

[ XR   XU    XF   X]
[ YR   YU    YF   Y]
[ ZR   ZU    ZF   Z]
[ SX   SY    SZ   0]

```

Ok, so some explanation of the columns is necessary: R stands for "Right", and represents one principle axis of the frame of reference. U stands for "Up", F for "Forward", and T for "Translate". Never mind about S, because it will just muddy the waters at this stage.

Right, up and forward are perpendicular axes, but also represent a change in orientation which will occur when applied to a point, or vector (important later!). Translation just means how much to move the point or vector.

So, now that we have this information, we can now start moving stuff around.

local space is usually defined thusly:

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

```

And is known as the "identity matrix"

Basically, if we multiply a vector by this matrix, it will be unchanged.

So, we construct a world matrix, based on the desired position and orientation in the world. If you want to know how to do this, I would recommend reading up on GLM, or whatever math library you want to use for specifics.

Then we construct a "view matrix", which represents the position, direction, and orientation of the camera, or eye. Again, math library specifics can vary, so choose a library and go with the API.

Finally, you need a projection matrix. This is usually comprised of resolution based information etc. Again, API's vary.

Now, to get a point from local space into screen space, we multiply the vector by each of the matrices in turn:

```
transformed_point = world_transform * point;
transformed_point = view_transform * transformed_point;
transformed_point = projection * transformed_point;

```

Or: `transformed_point = projection * view_transform * world_transform * point;`

No, to your question:

in order to transform a 2d point, into a 3d point, you must perform the transform in reverse, using the inverse of the matrices:

```
world_point = inverse(view) * inverse(projection) * mouse_point;

```

Then, you can draw a line between the camera position, and the normalised(length of one) mouse\_point vector * ray length.

Some resources:

http://antongerdelan.net/opengl/raycasting.html

http://schabby.de/picking-opengl-ray-tracing/

http://www.opengl-tutorial.org/

I recommend the third link, and in particular, read the maths stuff. You'll need it.

# Answer
> 1 votes
I'll just write real code. It works for me. Modern OpenGL.

> create a ray from the camera eye to the mouse pointer

```
void screenToClient(const vec2f& screen_coord, const vec4f& client_rect, vec2f& out )
{
    out.x = screen_coord.x - client_rect.x;
    out.y = screen_coord.y - client_rect.y;
}
void getRay( Ray& ray, const vec2f& coord, const vec4f& viewport_rect,  const Matrix4& ViewProjection_invert )
{
    vec2f point;
    screenToClient(coord,viewport_rect,point);

    vec2f rect_size;
    rect_size.x = viewport_rect.z - viewport_rect.x;
    rect_size.y = viewport_rect.w - viewport_rect.y;

    float pt_x = (point.x / rect_size.x) * 2.f - 1.f;
    float pt_y = - (point.y / rect_size.y) * 2.f + 1.f;

    //                                           0.f - for d3d
    ray.m_origin = math::mul(Vector4(pt_x,pt_y,-1.f,1.f), ViewProjection_invert);
    ray.m_end   = math::mul(Vector4(pt_x,pt_y,1.f,1.f), ViewProjection_invert);

    ray.m_origin.w = 1.0f / ray.m_origin.w;
    ray.m_origin.x *= ray.m_origin.w;
    ray.m_origin.y *= ray.m_origin.w;
    ray.m_origin.z *= ray.m_origin.w;

    ray.m_end.w = 1.0f / ray.m_end.w;
    ray.m_end.x *= ray.m_end.w;
    ray.m_end.y *= ray.m_end.w;
    ray.m_end.z *= ray.m_end.w;
}

```

Matrix inversion is taken from: https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/matrix-inverse

```
//Vector-matrix product ... not matrix-vector
inline Vector4 mul( const Vector4& vec, const Matrix4& mat )
{
    return Vector4
    (
        mat[ 0u ].x * vec.x + mat[ 1u ].x * vec.y + mat[ 2u ].x * vec.z + mat[ 3u ].x * vec.w,
        mat[ 0u ].y * vec.x + mat[ 1u ].y * vec.y + mat[ 2u ].y * vec.z + mat[ 3u ].y * vec.w,
        mat[ 0u ].z * vec.x + mat[ 1u ].z * vec.y + mat[ 2u ].z * vec.z + mat[ 3u ].z * vec.w,
        mat[ 0u ].w * vec.x + mat[ 1u ].w * vec.y + mat[ 2u ].w * vec.z + mat[ 3u ].w * vec.w
        );
}

```

Calculating ray direction and other things...

```
void Ray::update()
{
    m_direction.x = m_end.x - m_origin.x;
    m_direction.y = m_end.y - m_origin.y;
    m_direction.z = m_end.z - m_origin.z;
    m_direction.normalize();

    m_invDir.x = 1.f / m_direction.x;
    m_invDir.y = 1.f / m_direction.y;
    m_invDir.z = 1.f / m_direction.z;
    m_invDir.w = 1.f / m_direction.w;
...

```

Ray-triangle intersection. You can modify this just for ray-plane intersection if you need.

```
struct Triangle
{
    Vector4 v1; // vertex 1
    Vector4 v2;
    Vector4 v3;
    Vector4 e1; // edge
    Vector4 e2;

    void update()
    {
        e1 = Vector4( v2.x - v1.x,
            v2.y - v1.y,
            v2.z - v1.z,
            0.f);
        e2 = Vector4( v3.x - v1.x,
            v3.y - v1.y,
            v3.z - v1.z,
            0.f);
    }

    // Möller–Trumbore ray-triangle intersection algorithm
    bool rayTest_MT( const Ray& ray, bool withBackFace, float& len, float& U, float& V, float& W )
    {
        Vector4  pvec = ray.m_direction.cross(e2);
        float det  = e1.dot(pvec);

        if( withBackFace )
        {
// Epsilon is #define Epsilon std::numeric_limits<float>::epsilon()
// or 1.192092896e-07F
            if( std::fabs(det) < Epsilon )
                return false;
        }
        else
        {
            if( det < Epsilon && det > -Epsilon )
                return false;
        }

        Vector4 tvec(
            ray.m_origin.x - v1.x,
            ray.m_origin.y - v1.y,
            ray.m_origin.z - v1.z,
            0.f);

        float inv_det = 1.f / det;
        U = tvec.dot(pvec) * inv_det;

        if( U < 0.f || U > 1.f )
            return false;

        Vector4  qvec = tvec.cross(e1);
        V    = ray.m_direction.dot(qvec) * inv_det;

        if( V < 0.f || U + V > 1.f )
            return false;

        len = e2.dot(qvec) * inv_det;

        if( len < Epsilon ) return false;

        W = 1.f - U - V;
        return true;
    }

```

---
Tags: opengl, c++, raycasting, mouse
---


# Question
Title: How can I assign a layer to tiles on an individual level?
I've just started out with my first game in Unity. It's a simple 2D Platformer with a tile-based level.

When coding in the movement, I used the Physics2D.OverlapCircle() and an empty to check whether my player was touching the ground. However, I need to use a layer to make sure only the ground is detected.

*my code below*

```
//fixed update used for physics calculations
void FixedUpdate()
{
    //right or left arrows being pressed
    float moveX = Input.GetAxis("Horizontal");

    Vector2 moveDir = new Vector2(moveX * playerSpeed, rb.velocity.y);
    rb.velocity = moveDir;
}

//update used for spacebar input and force
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = Vector2.up * jumpForce*Time.deltaTime;
    }

    //is my circle overlapping any other colliders
    Collider2D collider =  Physics2D.OverlapCircle(feet.position, checkRadius, groundLayer);
    Debug.Log(collider);
}

```

When I tried assigning layers to my tiles, I couldn't find a way to do it.

I would be really grateful if anyone could show me how to, or if anyone can tell me a more efficient way to deal with jumping in a 2D platformer.

# Answer
I'm Assuming you are using tiles as prefab. So just change the layer of walkable tiles in the main prefab.

Also, you can manually add the layer via script.Referance

Make a tile script and add it to the tile prefab.
> 0 votes

---
Tags: unity, tiles, platformer
---


# Question
Title: Unity Rigidbody gets pushed through collider by another rigidbody?
I'm setting up the interior of a house in a 2D platformer. Inside the house is an NPC with a box collider and rigidbody attached, and the house is boxed in by four edge colliders. My character also has a collider and rigidbody.

My NPC walks back and forth randomly, but when he pushes my character into the wall, the force of the push takes priority over the house's edge collider and my character gets pushed outside.

Is there any way to give priority to the house's collider somehow, without removing the NPC's rigidbody?

# Answer
> 2 votes
Unity's collision detection is discrete so if an object passes through another object within 1 simulation frame, the collision will not be detected. If the collision is already detected, however, forces **should** push the objects apart and prevent a pass-through.

You can adjust the physics settings to make Unity's physics respond more accurately to collisions, and thus make pass-throughs less common. There are several settings you might consider changing:

Fixed Timestep: This field in the Time Manager controls the rate at which the simulation is run. A smaller value means there is less time between every simulation frame, thus less chance a collision will not be detected.

Collider size: The bigger the collider, the more an object will have to move to pass through and dodge the collision detection.

Adaptive Force: Found in the physics manager, setting this value to true will make force transfer more realistic so instead of just hitting a brick wall and overlapping, the force will be transferred to the brick wall.

Solver Iteration Count: This is basically how many times the collision resolution algorithm is run per simulation frame. The more times, the more accurate - the less passthroughs.

Min Penetration For Penalty: If 2 objects overlap more than this magnitude, collision forces will be applied. The lower this value, the less chance there will be a pass-through.

Continuous collision detection: I don't recommend this for, well, anything because it takes a huge toll on performance but this will guarantee all collisions will be detected. Usually if something needs continuous collision detection (like a bullet), it can be handled with other means like raycasting.

Note that all of these settings have the potential to decrease performance so you should thoroughly tailor them to your game. You can find more information on these settings in Unity's documentation: http://docs.unity3d.com/Manual/comp-ManagerGroup.html.

# Answer
> 1 votes
In Unity 2020 go to Edit -\> Project Settings -\> Physics to make essential tweaks to Physics settings.

For me, what worked was to change the `Default Max Depenetration Velocity`. This is like the force that the collider pushes back against the item colliding into it. My issue was that I used a Rigid Body vs a Static Collider (Capsule). Because the `Default Max Depenetration Velocity` was set to just 10, my high-speed object was passing through the collider. I changed to 1000 and the collider became much more aggressive towards the invader :). All good now.

See also @JPtheK9's answer.

---
Tags: unity, physics
---


# Question
Title: Time-passed check with Pause functionality
I am working on a game that has a lot of time-passed checks of the following format. These work great, but there is a problem when the game is paused:

> If paused for any meaningful amount of time, the if statement will become `true`.

```
const t = new Date().getTime(); // Get the current time (in ms)
const fireCooldown = 500; // The time to wait before firing again (in ms)

if(t > lastFireTime + fireCooldown) {
   lastFireTime = t;
   fire();
}

```

How can I integrate pause functionality into this - in a way where pausing does not make the if statement `true`?

# Answer
> 1 votes
The usual way to handle this it to separate the notion of "game time" from "real time".

While the game is running, you increase your game time variable's value each frame / simulation step.

Scripts that need a timestamp to work with will read the current value of that game time variable.

When your game is paused, you disable the code that increases the game time variable. Now for anything that's checking timestamps in game time, it's as though time has frozen — exactly what you want.

The challenge often comes in due to the fact that you don't want *everything* to pause. Animations in the UI like the pause menu should still play. So you need to set up your scripts to read either realtime or game time based on their context.

As a bonus, tracking game time this way also lets you enable slow motion and (some) fast forward effects, by just scaling how much you add to the game time variable you can alter the perceived flow of time for all scripts that use it.

---
Tags: javascript, timer, time
---


# Question
Title: Please spot something wrong in my code (Instantiation)
So, when this code runs, it will just spawn like 1000 copies of pipe(two rectangles) even with the Invoke.Here is my code.

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

public class generator : MonoBehaviour
{
    public GameObject pipe;
    GameObject piper;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Invoke("MakePipe", 1.0f);
    }

    void MakePipe()
    {
        piper = Instantiate(pipe, new Vector3(transform.position.x, Random.Range(-9f, 9f), transform.position.z), transform.rotation);
        piper.AddComponent<Pipe>();
    }
}
```
</code></pre>

# Answer
> 1 votes
If you fire a new Invoke every frame, you'll get a new pipe every frame after the delay finishes.

It looks like you want something much simpler:

```
IEnumerator Start() {
    while (true) {
        yield return new WaitForSeconds(1f);
        MakePipe();
    }
}

```

This starts when the script is loaded/enabled, waits one second, makes a pipe, then waits another second, in a loop forever, with no messy looking up of method name strings.

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


# Question
Title: Unity 4 - Some Rigidbodies Won't Fall Asleep
I'm having this problem in the free edition of Unity 4.1 where rigidbodies aren't falling asleep (and yes, I've tried playing with the `sleepVelocity` and `sleepAngularVelocity` values!). I've read the docs at http://docs.unity3d.com/Documentation/Components/RigidbodySleeping.html but cannot figure out the problem.

Here is a screenshot demonstrating my problem: Rigidbody Sleep Diagram http://uberlethal.com/random/rigidbody\_sleeping.png

I wrote a script that is attached to the rigidbodies in question, which sets the material color to red if the rigidbody is currently asleep or green if it is awake. The screenshot was taken when all objects were at rest. As you can see, not all of the gameobjects are sleeping. Each piece of debris you see on screen is its own gameobject with a rigidbody and collider.

The Unity docs I linked to above state the following:

> Rigidbodies automatically wake up when:
>
> * another rigidbody collides with the sleeping rigidbody
> * when adding forces.

Perhaps some clarification on the above might help solve this issue: If two rigidbodies are touching when they fall to "rest", will they never stay asleep? Put another way, would they just keep interrupting each other's sleep? As for the "adding forces" part, do sleeping rigidbodies awake only when forces are added directly to them, or when any force is added to any object (this is important because I am using a rigidbody character controller which moves via `AddForce()` calls)

I have tried manually sleeping objects myself with undesired results. What usually happens when I do this is that some objects will remain suspended in the air.

Let me know if you need other details - I have tried a great deal of things.

# Answer
> 1 votes
Rigidbodies awake when any force is applied to them. If you had a pool game and all the balls are sleeping and you would hit them with another ball, they would all wake up.

I guess there is some minimal jittering going on that keeps your rigidbodies alive. There are a lot of parameters that can have an impact on this, but personally I would first and foremost look into these:

* Use a Physics Material for your colliders and start with high friction values and no bounciness.
* Increase the `Drag` and `AngularDrag` values of your Rigidbodies so that the objects would come to rest by themselves even if they don't collide.
* Use a `sleepVelocity` value that is appropriate for the scale of your level. Remember that 1 unit in Unity is 1 meter in the physics-engine. Ideally your objects would be in a realistic scale.
* Maybe also try increasing the `Min Penetration for Penalty` value in the physics settings. This also depends on your world scale.

# Answer
> 1 votes
I run into the same problem today and just in case someone runs into the same trouble, another temporary workaround could be using a coroutine like this:

using a wait time.

```
    private IEnumerator ResumeRigidbody(GameObject someObj, float waitTime) {
        var startingTime = Time.time;
        var startingPos = someObj.transform.position;

        //dummy way of preventing gravity, rigidbody functions do not seem to work
        while(Time.time - startingTime < waitTime) {
            someObj.transform.position = startingPos;
            yield return new WaitForFixedUpdate();
        }
    }

    StartCoroutine(ResumeRigidbody(gameObject, 2f));

```

or a boolean.

```
    private IEnumerator ResumeRigidbody(GameObject someObj) {
        var startingPos = someObj.transform.position;
        WaitingIsOver = false;
        //dummy way of preventing gravity, rigidbody functions do not seem to work
        while(!WaitingIsOver) {
            someObj.transform.position = startingPos;
            yield return new WaitForFixedUpdate();
        }
    }

    StartCoroutine(ResumeRigidbody(gameObject));

    //and after some event
    WaitingIsOver = true;

```

# Answer
> 1 votes
For the record, I had this same problem suddenly pop up where it hadn't before.

After lots of troubleshooting, I discovered it was a physics2D collider error. I had mistakenly set a dynamic collider object in conflict with a kinematic (floor) object in a way that couldn't resolve itself when the game started. This kept any objects that contacted that same floor from being able to go to sleep, for some reason.

Hope it saves somebody a bit of time! (Unity 2017.3, Mac)

# Answer
> 0 votes
In the end I solved it by manually figuring out when to destroy the rigidbodies and colliders. I created a box collider trigger that goes from the floor to the player's knees. When an object breaks (and the GameObject is replaced with the broken version), there is a script that checks every 5 seconds to see if any of its rigidbody children are fully enclosed by the trigger. The script then destroys any rigidbodies and colliders that meet this criteria and stops polling.

It feels a bit hackish, and only works for my specific use case, but it gets the job done. Even after breaking several hundred objects in rapid succession, the physics isn't getting overloaded like it was before.

If anyone thinks of a more elegant solution, please let me know!

# Answer
> 0 votes
You can try looking at `this.GetComponent<Rigidbody>().sleepThreshold = 0.0f;`

`sleepThreshold`  is what makes one of the variables of falling asleep

Rigidbody.sleepThreshold not giving a lot of information more then that...

---
Tags: unity, physics, gameobject, rigid-body-dynamics
---


# Question
Title: How do I calculate a line segment that is a certain number of degrees from another line segment?
I have a line segment that is at an arbitrary angle in 3D space. I want to (in code) draw another line that shares an end point with the first line and has an angle of arbitrary degrees between them. The second line will partially overlap the first in the XZ plane.

# Answer
It sounds like you want something like this...

```
struct LineSegment {
    public Vector3 start;
    public Vector3 end;

    public LineSegment(Vector3 start, Vector3 end) {
        this.start = start; this.end = end;
    }
}

public LineSegment LiftByAngle(LineSegment original, float angleDegrees) {
    // Compute an arrow pointing along the line segment, from start to end.
    var offset = original.end - original.start;

    // Pick a vector in the XZ plane perpendicular to our original line.
    var axis = Vector3.Cross(offset, Vector3.up);

    // Form a rotation about this axis, lifting our line upward off the XZ plane.
    var rotation = Quaternion.AngleAxis(angleDegrees, axis);

    // Create a new line segment with the same starting point, and rotated span.
    return new LineSegment(original.start, original.start + (rotation * offset));
}

```
> 1 votes

---
Tags: unity, c#, 3d
---


# Question
Title: Changing colour of multiple prefab instances when dragging over them
So I am having some issue trying to get it so that when I touch/mousedown that an instantiated prefab changes color and then with mouse down still any other prefab that mouseenters, that prefab should change color as well. the bit of code that i have is shown below. Nothing happens though, other than the one prefab that received the OnMouseDown changes color, but not the others OnMouseEnter. If i remove the if statement though, they do change color OnMouseEnter. Any suggestions on how to do this or what i may be doing wrong?

Thanks

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

public class Letter : MonoBehaviour
{
    Color clkColor = Color.red;

    private bool _clicked;

    void Start()
    {
        _clicked = false;
    }

    void OnMouseDown()
    {
        _clicked = true;
        this.GetComponent<SpriteRenderer>().color = clkColor;
    }

    private void OnMouseEnter()
    {
        if (_clicked == true)
        {
            this.GetComponent<SpriteRenderer>().color = clkColor;
        }

    }
}

```

# Answer
I solved it thanks to Brathnann on unity forums, just made the private bool a public static bool and it works.
> 0 votes

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


# Question
Title: How to make one material on object with many parts inside?
I have a weapon witch have many parts, it also have many materials. Do I really need to make it like that? It's like about 8 mats! :(

# Answer
> 0 votes
No, you don't need to use an unique material for each 3d model asset. It is possible for multiple meshes to share materials. The most blunt way to do that is to simply replace the materials of the assets in Unity after you imported them. You do that by drag&dropping a material from your Unity project view onto the assets.

But it might be better to import your models in a way that they already share materials. How to do that exactly depends on what software you are using to create your models. But usually Unity will automatically recognize if two models use the exact same material based on the names, settings and textures of the materials.

---
Tags: unity, models, materials
---


title: glfw resizing causing image scaling

text:
# Question
Title: glfw resizing causing image scaling
I have a quad rendered that extends from the top left of the window to with width of the window that is also 64 pixels high. When I resize the window, from its initial size, the quad and text scales proportionately bigger or smaller in the same say Photoshop can scale a image. What I'm seeking on a basic level is that regardless of how I resize the window, everything drawn remains the same. From the below image, the right side is the initial size and the left side is what happens when I drag the window to be a smaller size. The red bar and text scales with it. This is how Im handling my resizing:

```
glfwSetWindowSizeCallback(pWindow, WindowSizeCallback); // initialized after context

void WindowSizeCallback(GLFWwindow* window, int width, int height)
{
    glfwSetWindowSize(window, width, height);
}

```

# Answer
You need to call `glViewport(0, 0, width, height);` when your framebuffer size changes. Do note that `glfwSetWindowSizeCallback` gives you screen coordinates, so perhaps instead of sticking the `glViewport` call inside `glfwSetWindowSizeCallback`, you want to set it from `glfwSetFramebufferSizeCallback`.
> 1 votes

---
Tags: opengl, graphics, glfw, window-management
---


# Question
Title: How can I detect enclosed areas in an arbitrary set of overlapping lines
I have game where there can be arbitrary lines, these lines can overlap. I want to find out first if there are any enclosed shapes created by overlapping lines, and then I want to fill the enclosed shape.

The best guess I have at doing this comes from this other post: determine if a set of tiles on a grid forms and enclosed shape. From what I can gather this would be, given a graph you can detect loops. However I can't quite figure out how to construct the graph from my data.

Is this a good way to go about solving this problem? And if so, any pointers on how I might get there given a list of collisions?

# Answer
> 2 votes
Hello and welcome to the site!

Here are some hindsights about how to construct a graph from your data:

* The collisions are the nodes of your graph.
* Each collision is bound to at least two lines (the two crossing, making the collision).

Then, each node is connected to all the others node having a line in common.

For example, the top collision in your image (let's call it **Node A**) is bound to the two green lines. On the left green line, there's another collision (**Node B**) with a pink line ; same thing on the right green line and another pink line (**Node C**). So we can start to build the graph with **Node A** being linked to **Node B** and **Node C**, since both of these two share a line with **Node A** (respectively the left and green ones). However, there is not link between **Node B** and **Node C** since they don't share a line.
Now do the same with your other collisions, then apply the graph magic from the other post, and you're done!

---
Tags: collision-detection, algorithm
---


title: Game physics of tearing apart

text:
# Question
Title: Game physics of tearing apart
For a game I'm programming I'm looking for a kind of realistic mechanic for simulating the tearing apart of objects. Let me explain:

I have a given point p in a 2-dimensional space (possible later also more dimensions so a solution should be scalable, which i assume is not the problem) and I have a number of forces f1, f2, ..., fn acting on this point p. So normally this point moves over time according to the combination of this forces. But now I'm looking for a kind of realistic mechanic that if forces vary strongly the point/objects gets split up in two points/objects that move in different directions.

Here a simple visual example:

three "similar" forces resulting in one single force (the point will move according to this single vector)

three forces that "tear" the point apart and result in two vectors (point will be split up in two new points that move according two the respective vector)

I amuse we need two give the point some kind of inner force, that defines how easy it is to tear the point apart?

By kind of realistic I mean something that doesn't need to be extremely realistic according to the real world physics but something that would fell kind of real in a video game. So an additional benefit would be that it can be easily computed.

# Answer
Hello and welcome to the site! That's an interesting question, and here are my first thoughts about it.

First of all, you need to find the two most "opposite" resulting forces, like in your second image. If a tear should happen, it will happen there.

Naively (there's probably a better way), that means testing all combinations of adding two groups of vectors. If you have **n** forces, you'll have to test **2^(n-1) - 1** combinations (the -1 is because we don't care about "all forces against none"). For example, in your second image, you could have :

* UP competing against RIGHT and DOWN
* RIGHT competing against UP and DOWN
* DOWN competing against UP and RIGHT

Add a fourth force, and that will be four more possibilities. Again, maybe there's a way to discard some obvious "bad competitions", but if you don't have to manage too much forces, even exponential complexity can do the trick.

Then, you'll have to decide wich pair of forces is the most "tearing" one. And the math seems pretty simple: you just have to look for the weakest vector (in magnitude) and apply a coefficient depending on the angle between the vectors, in that case the opposite value of the cosinus function.

**Tearing = - min(Vector\_magnitude) * cos(Vectors\_angle)**

Here are some examples:

* Two perfectly opposite (angle = PI) forces of magnitude 5 and 8 : Tearing = - 5 * -1 = 5
* Two rouglhly opposite (PI \> angle \> PI/2) forces of magnitude 5 and 8 : Tearing = - 5 * -0.x = anything between 0 and 5
* Two perpendicular (angle = PI/2) forces of magnitude 5 and 8 : Tearing = - 5 * 0 = 0
* Two rouglhly colinear (PI/2 \> angle \> 0) forces of magnitude 5 and 8 : Tearing = - 5 * 0.x = some negative value, because of course there's no tearing since the forces both work in the same general direction

Find the grouping of forces with the highest tearing value, and compare that value with the "tearing resistance" of your object. If it's higher, your object split between the two resulting forces.

---

Here is an example with 3 forces A, B and C, and some eyeballed values. We can see that the biggest tear value happen when A and B pull against C (which indeed seems to be the biggest "fight"), with a tear factor of 5.7
> 1 votes

---
Tags: physics, movement
---


title: Enemy AI on a platform

text:
# Question
Title: Enemy AI on a platform
I was working on a 2.5D enemy AI movement on a platform. The idea is to get the enemy(green cubes) to move along the platform, when it gets to the edge of the platform, it turns around and goes the opposite direction, if it meets another enemy, it should turn around and go the opposite direction.

My code works and the enemy moves as I expected on the editor, but when I build it out to mobile, the enemy develops a weird movement(like it is trying to go in both directions at the same time).

Here's a playtest on the editor: https://youtu.be/fmZSHd3GXDE

Here's a playtest on mobile: https://youtu.be/xBDDdgVrGQE

I can't find out what could be the cause. What do you think?

Here is my code:

```
private Rigidbody mRigidbody = null;

private bool isIdle = true;
private bool turnedLeft = false;
private bool turnedRight = false;

private Transform currentObstacle = null;
private Transform currentPlatformEdge = null;
private Transform leftMostPlatformEdge = null; //transform that represents left end of a platform
private Transform rightMostPlatformEdge = null; //transform that represents the right end of a platform

private int randomNumber = 0;

private float lookDirection = 1f;

[SerializeField] private float walkSpeed = 92f;
[SerializeField] private float gravityMultiplier = 2f;
[SerializeField] private float rayDistanceToObstacle = 1.25f;

private Vector2 right = Vector2.zero;

private void Awake()
{
    mRigidbody = GetComponent<Rigidbody>();
}

void Start()
{
    randomNumber = Random.Range(0, 2);
    currentPlatformEdge = leftMostPlatformEdge;
}

private void FixedUpdate()
{
    ApplyGravity();

    right = transform.TransformDirection(Vector2.right);

    CastRay();

    Navigation();
}

private void ApplyGravity()
{
    Vector2 extraGravityForce = (Physics.gravity * gravityMultiplier) - Physics.gravity;
    mRigidbody.AddForce(extraGravityForce);
}

private void CastRay()
{
    Ray ray = new Ray(transform.position, Vector2.right * lookDirection);

    Vector2 startPos = transform.position;
    startPos.y += 1f;

    #region Obstacle Ray
    bool HittingObstacle = Physics.Raycast(ray, out RaycastHit obstacleHit, rayDistanceToObstacle);
    if (HittingObstacle)
    {
        if (obstacleHit.collider.CompareTag("Obstacle") || obstacleHit.collider.CompareTag("Enemy")
            || obstacleHit.collider.CompareTag("Platform"))
            currentObstacle = obstacleHit.transform;
    }
    else if (!HittingObstacle && currentPlatformEdge != null)
        currentObstacle = null;
    #endregion
}

private void Navigation()
{
    Vector2 CurrentTargetDistanceFromTransform = Vector2.zero, CurrentPlatformEdgeDistanceFromTransform = Vector2.zero;
    if (currentObstacle != null)
        CurrentTargetDistanceFromTransform = currentObstacle.position - transform.position;
    if (currentPlatformEdge != null)
        CurrentPlatformEdgeDistanceFromTransform = currentPlatformEdge.position - transform.position;

    if (currentObstacle != null || currentPlatformEdge != null)
    {
        if (currentObstacle != null) //If an enemy or an object with the obstacle tag is in this transform's way
        {
            if (Vector2.Dot(right, CurrentTargetDistanceFromTransform) < 0)
                WalkLeft();
            else
                WalkRight();
        }
        else if (currentPlatformEdge != null && currentObstacle == null)
        {
            if (Vector2.Dot(right, CurrentPlatformEdgeDistanceFromTransform) < 0)
                WalkRight();
            else
                WalkLeft();
        }
    }
    else
        WalkTowardsAnyDirection();
}

private void TurnLeft()
{
    Quaternion Rot = Quaternion.Euler(0, -90, 0);
    transform.rotation = Rot;

    lookDirection = -1;

    mRigidbody.velocity = new Vector2(0, mRigidbody.velocity.y);

    turnedLeft = true;
    turnedRight = false;
}

private void TurnRight()
{
    Quaternion Rot = Quaternion.Euler(0, 90, 0);
    transform.rotation = Rot;

    lookDirection = 1;

    mRigidbody.velocity = new Vector2(0, mRigidbody.velocity.y);

    turnedRight = true;
    turnedLeft = false;
}

private void WalkLeft()
{
    isIdle = false;

    if (!isIdle)
    {
        if (!turnedLeft)
            TurnLeft();

        mRigidbody.velocity = new Vector2(-walkSpeed * Time.fixedDeltaTime, mRigidbody.velocity.y);
    }

    if (leftMostPlatformEdge != null)
        currentPlatformEdge = leftMostPlatformEdge;
    else
        currentPlatformEdge = null;
}

private void WalkRight()
{
    isIdle = false;

    if (!isIdle)
    {
        if (!turnedRight)
            TurnRight();

        mRigidbody.velocity = new Vector2(walkSpeed * Time.fixedDeltaTime, mRigidbody.velocity.y);
    }

    if (rightMostPlatformEdge != null)
        currentPlatformEdge = rightMostPlatformEdge;
    else
        currentPlatformEdge = null;
}

protected void WalkTowardsAnyDirection()
{
    if (randomNumber == 0)
        WalkLeft();
    else
        WalkRight();
}

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Platform"))
    {
        leftMostPlatformEdge = collision.gameObject.transform.GetChild(0).transform;
        rightMostPlatformEdge = collision.gameObject.transform.GetChild(1).transform;

        WalkTowardsAnyDirection();
        return;
    }
}

private void OnCollisionExit(Collision collision)
{
    if (collision.gameObject.CompareTag("Platform"))
    {
        leftMostPlatformEdge = null;
        rightMostPlatformEdge = null;
    }
}

```

# Answer
I have no idea why it works, but when I use:

```
    if (currentObstacle != null) //If an enemy or an object with the obstacle tag is in this transform's way
    {
        if (Vector2.Dot(right, CurrentTargetDistanceFromTransform) < 0)
            WalkRight();
        else
            WalkLeft();
    }
    else if (currentPlatformEdge != null && currentObstacle == null)
    {
        if (Vector2.Dot(right, CurrentPlatformEdgeDistanceFromTransform) < 0)
            WalkLeft();
        else
            WalkRight();
    }

```

everything works fine on mobile, but the strange movements will be seen on the editor.

My final solution was to use:

```
        if (currentObstacle != null)
        {
            Vector2 CurrentTargetDistanceFromTransform = currentObstacle.position - transform.position;

            if (Vector2.Dot(right, CurrentTargetDistanceFromTransform) < 0)
            {

```

#if UNITY\_ANDROID

```
                WalkRight();

```

#endif #if UNITY\_EDITOR

```
                WalkLeft();

```

#endif

```
            }
            else
            {

```

#if UNITY\_ANDROID

```
                WalkLeft();

```

#endif #if UNITY\_EDITOR

```
                WalkRight();

```

#endif

```
            }
        }
        else if (currentPlatformEdge != null && currentObstacle == null)
        {
            Vector2 CurrentPlatformEdgeDistanceFromTransform = currentPlatformEdge.position - transform.position;

            if (Vector2.Dot(right, CurrentPlatformEdgeDistanceFromTransform) < 0)
            {

```

#if UNITY\_ANDROID

```
                WalkLeft();

```

#endif #if UNITY\_EDITOR

```
                WalkRight();

```

#endif

```
            }
            else
            {

```

#if UNITY\_ANDROID

```
                WalkRight();

```

#endif #if UNITY\_EDITOR

```
                WalkLeft();

```

#endif

```
            }
        }

```

If anyone knows why it works this way, I'll love to hear it
> 0 votes

---
Tags: unity, c#, ai, platformer
---


title: How to make score points based on time

text:
# Question
Title: How to make score points based on time
So the idea is simple.

a) Players why finish the level faster, should get higher score. b) The levels (1 to N) where every next becomes more difficult should impact the score.

So it's kind of mix of "time to complete" and "level number".

If would know the *fastest possible time* the user can complete the level, I would do the fallowing:

a) If player completes the level in *fastest time*, it gets max score 100. b) If it takes, for example, twice as long I divide by 2 and get 50. c) Then I multiple by the level number assuming that every next level is twice as difficult.

Example: Player completes level N two times slower than fastest time, so: Score = 100/2 * N = 50N

But the problem is that I can't really figure out the this *fastest time* for each level, because my game is a complex randomized 4d maze and I have no idea how fast a pro gamer can complete it to define the max score. And without that I have no idea how to calculate the score.

This question is all about: "Can we figure out the score without knowing the *fastest time*"

Any help appreciated.

# Answer
> 2 votes
You could define whater max score you want for any level.

then at the end of the run you give play the score = MAX\_SCORE\_ON\_THIS\_LEVEL / time\_to\_complete.

This way the Max score is known, none can get more than "MAX\_SCORE\_ON\_THIS\_LEVEL", if the dont complete it in less than one second ofc

---
Tags: algorithm, leaderboards, time
---


# Question
Title: Calculating framerate-independent values, for linear, quadratic, and exponential functions
There are a few similar posts, but they only deal with one of the three components I'm looking for, and none seem to handle the case of using a fixed step size (they're all about simulations which use a variable deltaTime).

I'm using a fixed step simulation, and my lifelong (bad) habit has been to eschew units and just directly use parameter values which have deltaT "baked in". Now that I'm trying to add support for different fixed rates, it's biting me in the ass! :/

Here's a simplified example of my code, covering all three cases:

```
run_speed = 2;      //velocity, linear
brake_decay = 0.95; //viscous damping, exponential
gravity = 1;        //acceleration, quadratic

if(button_pressed)  vel_x = run_speed;
else                vel_x *= brake_decay;

vel_y += gravity;

pos_x += vel_x;
pos_y += vel_y;

```

I would like to support different fixed timesteps by scaling my existing parameters:

```
run_speed = 2 * A_to_B_vel;
brake_decay = 0.95 * A_to_B_damp;
gravity = 1 * A_to_B_acc;

```

My question is: if my fixed timestep is currently A ms/tick, and I want to switch to a fixed timestep of B ms/tick, how do I calculate these three new scaling factors, such that the object follows the same curve through space and time?

(I realize that the actual positions will vary between A and B since we'll be sampling the trajectory curve at a different rate, I just want the underlying curve itself to be identical regardless of how we sample it.)

A\_to\_B\_vel: this is the case which has been covered by many other "framerate independent" questions, and it's relatively trivial because the relationship is linear: `A_to_B_vel = B/A`

A\_to\_B\_damp: this seems to have been answered here Frame-rate independant movement with acceleration via the Pow() function. This makes sense since it describes an exponential curve; I'd still appreciate someone breaking down the formula though, because the answer given there involves "referenceFPS" and I'd prefer to stick solely to units of time, ie ms/frame, not frame/sec. (and it's not clear that I can simply substitute one for the other into the formula they give)

A\_to\_B\_acc: this is where it gets confusing! According to the above answer, this should be treated similarly to A\_to\_B\_vel (ie scale by the frame duration), however this is definitely wrong, since I've implemented it and it doesn't work. i.e `A_to_B_acc = B/A` doesn't work. My calculus is very rusty, but I would imagine that the scaling factor needs to involve a dT\*dT term somewhere, since acceleration changes position quadratically.

Additionally, if anyone could point me towards a resource which explained the underlying calculus here, I would really appreciate it.

Thanks for your time! :) Raigan

# Answer
The equation of motion under constant acceleration is:

$$\vec p (t) = \vec p\_0 + \vec v\_0 \cdot t + \frac {\vec a} 2 t^2$$

So if you didn't have your drag, you could modify your code like so...

```
if(button_pressed)  vel_x = run_speed;
else               // TODO //

pos_x += vel_x * dt;
pos_y += vel_y * dt + 0.5 * gravity * dt * dt;

vel_y += gravity * dt;

```

Note that we add gravity to the velocity *after* computing the position, so that we don't double-dip and count gravity twice in our position calculation: once on its own, and once inside the velocity.

To convert your constants from your old time step `referenceTimestep` to the new one `dt`, you'd just multiply them by the ratio:

```
run_speed = reference_run_speed * dt / referenceTimestep
gravity = reference_gravity  * dt / referenceTimestep

```

Unfortunately, adding drag makes this much more complicated.

This kind of exponential drag has the form:

$$\begin{align} \vec v (t) &= \vec v\_0 \cdot b^t\\ \frac {d \vec v(t)} {d t} &= \vec v\_0 \cdot \ln(b) \cdot b^t \end{align}$$

Where \\$ b \\$ is a braking ratio constant, describing what fraction of the velocity should remain after one second. If it's the only thing acting on velocity as above, then we can integrate that just fine.

$$\begin{align} \frac {d \vec p(t)} {d t} &= \vec v(t) = \vec v\_0 \cdot b^t\\ \vec p(t) &= \frac {\vec v\_0} {\ln (b)} b^t + \vec c = \vec p\_0 + \frac {\vec v(t) - \vec v\_0} {\ln (b)} \end{align}$$

But as soon as velocity is changing according to this braking ratio *and* a constant acceleration due to gravity simultaneously, things get a *lot* more complicated.

$$\frac {d \vec v} {d t} = \vec a + \vec v\_0 \cdot \ln (b) \cdot b^t\\ \vec v(t) = \frac {\vec a \cdot e^{b^t} \cdot Ei(-b^t)} {\ln b} + \vec c\cdot e^{b^t}$$

This is according to Wolfram Alpha. That \\$Ei\\$ there is the Exponential Integral, one of those nasty transcendental functions we usually have to approximate by summing terms from an infinite series, but one not common enough to be included in our standard gamedev math libraries.

If we try to integrate this to get a closed-form expression for our position, Wolfram gives up and just leaves the integral unevaluated:

$$\vec p(t) = \int\_1^t\left( \frac {\vec a \cdot e^{b^s} \cdot Ei(-b^s)}{\ln(b)} + \vec c\_1 e^{b^s}\right)d s + \vec c\_2$$

So, approximation is your only hope here.

I'd say your best bet is to compute position using the kinematic equation for constant acceleration as above, which assumes no braking affects the velocity over the time step. That's wrong, but it's only a *little* wrong if your braking is gradual and your timestep is short.

Then you can compute your velocity using the integral above if you feel like using a math package that lets you compute the exponential integral. Or you can approximate it stepwise:

```
if(button_pressed)  vel_x = run_speed;
else                vel_x *= brake_decay;

```

Where:

```
brake_decay = pow(reference_brake_decay, dt / referenceTimestep);

```

Again this is only a little wrong, and it's a lot cheaper. Since perfect consistency with different timesteps is off the table anyway, I'd say this is a reasonable compromise.
> 2 votes

---
Tags: movement, frame-rate, fixed-timestep
---


# Question
Title: How can players randomly - and secretly - choose 5 cards out of 25 that match a specific condition
So this is a less a coding question and more a 'there's gotta be a way'...

I have a Clue-like logic/deduction board game that has 25 cards - 5 of each color and 5 of each taste. Each card is unique, and has a unique combination of color and taste.

Just like in Clue, I want to have players randomly choose some cards that make up the answer they're trying to discover through logic and deduction. In previous versions, one side of the cards (the back side) had the taste of the card, and the correct answer would have exactly one of each taste. After some playtesting, a suggestion was made to have the correct answer have 5 cards, including exactly one card of each color and taste...

So that's what I'm trying to do. Players need to secretly determine this for themselves by using just some playing cards. One side needs to have the actual combination of color and taste on it, but anything can be on the back to make it work. I've tinkered with numbers and bar-code-like graphics, but anything's possible here (numbers shouldn't be easily memorized, naturally, and the backs of the cards should be able to remain visible without this system giving away what's on the other side...

# Answer
I think any method with identifying symbols on the backs of the cards is likely to fail.

With just 25 symbols, it would be very easy for players to accidentally memorize a telltale clue of one or more of the cards, spoiling the game for themselves, even if they're actively trying not to notice.

I've seen games that try to obfuscate this information by using fluorescent ink revealed by a UV light, or overlapping patterns you need to look at through a coloured filter, so you only clearly see the pattern at the designated "setup" or "check" time, and can't easily use it to track a card throughout play. But for a mystery game like this, leaking that info at setup time is already enough to spoil the puzzle.

What I'd propose instead is a shuffling approach.

Start by laying out the cards face-up, in a 5x5 matrix, with cards of the same taste all in a row, and cards of the same colour in a column. Let's say it looks like...

```
AV  AW  AX  AY  AZ
BV  BW  BX  BY  BZ
CV  CW  CX  CY  CZ
DV  DW  DX  DY  DZ
EV  EW  EX  EY  EZ

```

Turn each card over while keeping it in its place in the matrix. Now the matrix should look like this:

```
⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜

```

But the players might still remember which row was which taste, or which column was which colour. So now we'll shuffle them, like a shell game. Slide one row out and move it to one end or the other:

```
                                         ⬜⬜⬜⬜⬜     ⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜                ⬜⬜⬜⬜⬜                                 ⬜⬜⬜⬜⬜
            ⬜⬜⬜⬜⬜                                 ⬜⬜⬜⬜⬜    ⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜                ⬜⬜⬜⬜⬜                ⬜⬜⬜⬜⬜    ⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜                ⬜⬜⬜⬜⬜                ⬜⬜⬜⬜⬜    ⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜                ⬜⬜⬜⬜⬜                ⬜⬜⬜⬜⬜    ⬜⬜⬜⬜⬜

```

Then do the same for a column, and repeat. You can select which row/column to slide each time using a dice roll, rather than leaving it up to the players.

Each time we do one of these shifts, we preserve the fact that each row contains a single taste, and each column contains a single colour, we just switch which one is which in a way that - hopefully, after enough shuffles - your players lose track of.

To make these shuffles easier, you could stack each column into a deck. Then swap the positions of these five decks a few times. Then unpack back to the matrix and stack each row into a deck, and swap the decks around again. You just need to make sure you use the same stacking order in all decks during packing and unpacking (eg. always left-to-right / top-to-bottom). Flipping the order in one deck will make an invalid answer.

Another trick you can use is to have each player take a turn applying a row or column shuffle while the other players are occupied with something else, so no one player can keep track of where every row/column got moved to. This way you can get to complete uncertainty with fewer swaps, where you'd need a higher number to throw off a player with a sharp eye and good memory who can watch the whole process.

After our shuffling, we have a permuted matrix that maybe looks a bit like this, if we looked up from under the glass table:

```
BX  BW  BY  BV  BZ
DX  DW  DY  DV  DZ
EX  EW  EY  EV  EZ
AX  AW  AY  AV  AZ
CX  CW  CY  CV  CZ

```

Now your players choose a random card from the matrix to add to the answer, keeping it face-down so no one sees it. Again you could use dice to make this choice. This leaves us with...

```
BX  BW  BY  BV  BZ   Answer: DW
DX      DY  DV  DZ
EX  EW  EY  EV  EZ
AX  AW  AY  AV  AZ
CX  CW  CY  CV  CZ

```

Now they remove every card in the incomplete row and column and add them to the deck of clues.

```
BX      BY  BV  BZ   Answer: DW
                     Clues:  BW EW AW CW DX DY DV DZ
EX      EY  EV  EZ
AX      AY  AV  AZ
CX      CY  CV  CZ

```

Slide the remaining cards to return to a square matrix, and repeat:

```
BX  BY  BV [BZ]    Answer: DW
EX  EY  EV  EZ     Clues:  BW EW AW CW DX DY DV DZ
AX  AY  AV  AZ
CX  CY  CV  CZ

EX  EY  EV    Answer: DW BZ
AX [AY] AV    Clues:  BW EW AW CW DX DY DV DZ BX BY BV EZ AZ CZ
CX  CY  CV

EX  EV   Answer: DW BZ AY
CX [CV]  Clues:  BW EW AW CW DX DY DV DZ BX BY BV EZ AZ CZ EY CY AX AV

[EX]     Answer: DW BZ AY CV
         Clues:  BW EW AW CW DX DY DV DZ BX BY BV EZ AZ CZ EY CY AX AV EV CX

Answer: DW BZ AY CV EX
Clues:  BW EW AW CW DX DY DV DZ BX BY BV EZ AZ CZ EY CY AX AV EV CX

```

This procedure ensures you get exactly one of each flavour and one of each colour in the answer pile, and all the remaining cards in the clue pile.

If you find this runs a bit long, you can also abbreviate it. Once you have a shuffled matrix, just take one diagonal into the answer deck and the rest into the clue deck:

```
[BX] BW  BY  BV  BZ   Answer: BX DW EY AV CZ
 DX [DW] DY  DV  DZ   Clues:  BW BY BV BZ DX DY DV DZ EX EW
 EX  EW [EY] EV  EZ           EV EZ AX AW AY AZ CX CW CY CX
 AX  AW  AY [AV] AZ
 CX  CW  CY  CV [CZ]

```

If your initial shuffle was enough to mix up your players' memory of which row/column is which, then this is just as good. But you might find randomizing at the end involves easier manipulations than the row/column shuffling, so splitting your randomizing between the two phases might help the setup phase go quicker.
> 1 votes

---
Tags: game-design, algorithm
---


# Question
Title: Why do some games have different builds in different platforms/regions?
I'll try to keep things brief and provide some context. I was playing MineCraft one day and this question popped into my head. I was thinking about some of the things that the Bedrock edition of the game had for example, yet the Java edition lacked. One example would be that Java doesn't allow for the use of dyes with cauldrons, but in Bedrock? No problem. Conversely, the *"Illusioner"* mob from the illagers can be found in Java, yet is exempt from Bedrock.

To provide another example, I recently stumbled across a mobile game called Seven Knights, created and developed in South Korea, later ported and localized for global release. It is my understanding that the Korean version of the game is quite a' ways ahead of the global release. From the number of heroes, to the length of the narrative, and the number of items, the Korean version is planned fairly far ahead. I find this to be a rather odd thing to do.

So I'll ask, why is this done? Why do developers have different builds of the same game in different platforms/regions? Would it not make more sense to simply port everything as is and *then* localize it if need be? Why split up the builds or only port/localize part of the content?

# Answer
Players from another country would have another culture and another set of expectations.

Considering that, the localized version could have censored content. Or might even have changes that lower or increase the difficulty.

You will also find bug fixed released with the localized version first. That may happen if the developers did the fixes, while they were working in the localization.

There was also the case of company changing the intelectual property attached to a game. They decided that the original was too obscure for an international audience.

---

Sometimes the game splits because of the platforms and not the localization.

If you have built a game in such a way that it can only run on some platforms... To port it, sometimes it is worthwhile to built it again from the ground up. And you might find you cannot support everything in the ported version. Resulting in a new game with a ton of shared content, and the same intellectual property. As a result, you have split your player base...

Players from another platform would have another set of expectations too.

You could bring a compatible version to your original set of platforms. But, there would be people still playing the old incompatible game. If that old version is very popular, you might be stuck supporting two versions of the game. Even releasing updates for both.

Once you have different teams working on them, they are going to push forward a different set of features.

If you want to keep those features inline, consider... Some platforms and tools would make some features easier to develop. Different teams would have different skills sets. Also, it can be detrimental to force a set of features on the developers. Instead, it is good idea to let the developers follow their motivation when evolving the game.

Once the versions have diverged as I mention above, uniting them into a single one, takes a lot of effort. In particular if you do not want to cut features in the name of compatibility. If it goes well, the company would offer players to migrate without losing anything. *And that is a tall order for Minecraft, because mods.*

---

When talking about online games, sometimes the developer company does not localize it. Instead they license it to third parties who localize it, and provide their own servers.

While the licensee are paying the developers for the game, they recover the investment from the player purchases... And, often the licensee will mod the game on their own accord. For example adding features their players demand. Business logic suggest to keep their players happy and buying.

Oh, and those modifications could mean a hard time upgrading to a new upstream version. When the developers release a new version, it likely breaks the licensee changes. Now, they have a few options:

* Drop their changes, and stick with the version from the developers.
* Lag behind while they reimplement those changes in the new version.
* Stick with the old version and their changes.
> 1 votes

# Answer
Games ported to different platforms could have a different development team depending on it. This means that both teams need to communicate about the update changes, it also would have to deal with publishers and acceptment phases on consoles, which in turn could lead to less frequent updates to consoles.

In some cases, the game needed to be build from the ground up (playing with only a controller is much different than playing with mouse and keyboard) which means the console version can be entirely different from the original source code, but still plays the same.

Different countries also have different policy rules, and may need to review or sensor the game if it's contents violates their policy. This can also lead to different changes on each version.

I do not know if this all is the same case for Minecraft though.
> 0 votes

---
Tags: cross-platform, porting, localization
---


# Question
Title: AddListener will not listen to onClick event
Based on this question on the Unity forum, I've made this code to instantiate a button and add an `onClick` event.

```
// Setting some other component properties right of the prefab.

shopTurretItem.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
    UnityEngine.Debug.Log("Click");
});

Instantiate(shopTurretItem, transform);

```

The variabele `shopTurretItem` is my prefab type of `UnityEngine.GameObject`.

The problem is that the log `Click` will never be shown. If I add breakpoints on the first code line, the compiler will stop the code. If I place it into the closure, it'll never be hit if I click on that button.

This is the inspector of my prefab `shopTurretItem`.

What's wrong with this code?

# Answer
> 1 votes
# Code-added events will never show in the inspector

This is not a problem. They're added at runtime, they work, and you can do so much more with them than you can in the inspector, so why do you care that they don't show up?

If the event isn't working, that's because you added the event *to the prefab* not its clone:

```
GameObject go = Instantiate(shopTurretItem, transform);
go.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
    UnityEngine.Debug.Log("Click");
});

```

Note you can also simplify this by using imports:

```
GameObject go = Instantiate(shopTurretItem, transform);
go.GetComponent<Button>().onClick.AddListener(() => {
    Debug.Log("Click");
});

```

# Answer
> 1 votes
Judging by your code, isn't it that you are subscribing (adding a listener) to the Prefab's onClick event? why don't you add listener to the instantiated button?

```
UnityEngine.UI.Button newButton = Instantiate(shopTurretItem, transform) as UnityEngine.UI.Button;

newButton.onClick.AddListener(() => {
    UnityEngine.Debug.Log("Click");
});

```

# Answer
> 1 votes
Also, since I have done this before, make sure that you have an event handler for your canvas. I had this issue once and discovered that it was all down to creating the canvas and UI buttons at runtime.

# Answer
> 0 votes
I was having similar problems with unity ide v 2020. After much research I noticed render mode of all my canvas component were set to "Screen Space Camera". I switched the render mode to "Screen Space Overlay" and the click listener started working.

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


# Question
Title: How do I sort edge tiles for a hex grid in order to draw a border?
I am trying to sort the edge tiles of a region in my hexagon map. Once it is properly sorted, I can then try to walk through them and attempt at creating a Civ style border map, but I can't seem to figure out the sorting.

Right now I just have a simple line renderer that represents my results. Red portion of the gradient represents the start of the line.

It comes quite close at times.

I tried playing around with checking the direction I was coming from to change the neighbor sort, but haven't had any luck. I added a Stack so that I can walk back if I hit a dead end. Sometimes it works, but depends on the direction it was coming from.

Don't necessarily pay too much attention to the coordinates themselves. I've gone through the entire https://www.redblobgames.com/ docs and can easily convert from a 2D grid, to Unity's Offset, and to Cube coordinates. This particular code is initially the coordinates from a `int[,]` that was used in the procedural generation of the map.

```
public void CalculateEdgeTiles(ref int[,] regionMap)
{
    EdgeTiles = new HashSet<MapCoord>();
    if (Tiles == null)
        throw new Exception();

    MapCoord startingEdgeTile = null;

    foreach (var tile in Tiles)
    {
        foreach(var neighbor in tile.Position.ToHexOffsetCoordinateRing(1, true))
        {
            if (regionMap[neighbor.x, neighbor.y] != tile.RegionId)
            {
                EdgeTiles.Add(tile);
            }
        }
    }

    var sortedTiles = new List<MapCoord>();
    var queue = new Queue<MapCoord>();
    var stack = new Stack<MapCoord>();

    queue.Enqueue(EdgeTiles.First());

    var walkingBack = false;
    MapCoord previousTile = null;
    while (queue.Count > 0)
    {
        var currentTile = queue.Dequeue();
        if (sortedTiles.Contains(currentTile))
            continue;

        if (!walkingBack)
        {
            sortedTiles.Add(currentTile);
            stack.Push(currentTile);
        }

        var foundNeighbors = new List<MapCoord>();

        foreach (var neighbor in currentTile.Position.ToHexOffsetCoordinateRing(1, true))
        {
            var tile = Tiles.FirstOrDefault(x => x.Position == neighbor);
            if (tile == null || !EdgeTiles.Contains(tile) || sortedTiles.Contains(tile))
                continue;

            foundNeighbors.Add(tile);
        }

        if (previousTile == null)
            previousTile = currentTile;

        bool addedNeighbor = false;
        var neighborQuery = previousTile.Position.y < currentTile.Position.y
                                ? foundNeighbors.OrderByDescending(x => x.Position.x + x.Position.y)
                                : foundNeighbors.OrderBy(x => x.Position.x + x.Position.y);
        foreach (var neighborTile in neighborQuery)
        {
            addedNeighbor = true;
            queue.Enqueue(neighborTile);
            break;
        }

        walkingBack = false;
        //If we added nothing, pop the stack and start walking back to check the next neighbor.
        if (!addedNeighbor && EdgeTiles.Count != sortedTiles.Count)
        {
            walkingBack = true;
            queue.Enqueue(stack.Pop());
        }

        previousTile = currentTile;
    }

    EdgeTiles = new HashSet<MapCoord>(sortedTiles);
}

```

I'm hoping I am just missing a simple trick or I was just dumb on one section of the code. Any info is appreciated.

# Answer
The usual approach here is to pretend like you're solving a maze blindfolded: keep your left hand in contact with the wall, and follow its contours until you reach the exit (or in this case, until you return to your starting point)

Assuming we start with some tile in the region we want to outline, but not necessarily on the edge of that region, we can keep moving in some arbitrary direction until we find a tile with a neighbour in a different region. Make this our starting point (call this our "standing" tile, because it's the one we're standing on), and store the tile in the other region we're touching with our left hand (call this our "held" tile, since we're holding our hand on it)

**Rotate your feet:**

As long as you can do so without leaving your current region, rotate your "standing" position counter-clockwise around your "held" tile. This represents following the wall around a convex corner. At each step, we add our standing tile to the edge list.

**Rotate your hand:**

If rotating around your "held" tile would make you leave your region, then instead rotate your "held" tile clockwise around your "standing" tile until this would make your hand enter your standing region. This represents feeling your way around a concave corner.

We can work our way around the whole map, alternating between these two moves, following one as far as we can before switching to the other.

When we return to standing on our starting tile, holding the same tile we were when we started, we've completed our circuit and have all the edge tiles in the correct sequence in our list.

Note that we may return to the same tile more than once over the course of the search, but with our hand on a different neighbour. That's why we need to check both the standing and held tile match our starting state before we can conclude that we've finished tracing the whole edge.

As a bonus, if you keep a list of tiles our hand visits, this gives you the outer border tiles in the containing region(s). Or, if you keep track of each {standing, held} pair you encounter along the way, that gives you the ordered list of edges between this region and its neighbours.

---

This method will not on its own discover holes in your region, if it can have a doughnut shape with a different region nested inside it. To be sure you've found all border tiles in a region that can contain holes, you'd first do a depth-first search or flood fill to get all connected tiles in the region, and note all the neighbouring region tiles you discover along the way.

Pick one of them to place your hand at and trace your first contour, using the method above, keeping track of which tiles your hand touches along the way.

After you're done, check your neighbouring collection again: are there any your hand didn't touch? If so, trace a contour starting with your hand on that tile, and repeat, until your hand has visited every neighbour.
> 7 votes

# Answer
I see you already have an answer to your question, but I'm going to add another answer for anyone who's trying to solve a simpler variant of the question.

Civilization puts borders *between* hex tiles when the owner of the tiles are different. The simplest algorithm is to look at the edges between tiles:

```
let H : iterate over all hexes
  let N : iterate over the neighbors of H
    if H and N are owned by different civilizations, draw a border

```

Here's what it looks like:

You can draw these line segments individually, without linking them up. Note that it handles peninsulas and single-hex cells without any trouble. No special cases needed. Try it out with this interactive demo.

Note that you'll end up drawing each border twice, once for A→B and once for B→A.

If you don't want to draw each border twice, only visit the northwest, west, and southwest neighbors instead of visiting all six.

Alternatively, move the drawn border slightly inside the hex so that you can draw both of them, possibly in different colors:

If you need to link these up into a chain, it's easiest if you try to keep a given civilization on the left side of the chain. Pick any edge where the left side is the given civilization, and the right side is owned by someone else. Look at the yellow arrow #1 in this diagram, where the left side is the blue civilization:

The endpoint of this edge will be a vertex. A vertex is where three hexes meet. Two of these hexes you've already been looking at. Look at the hex in front of you. Is it owned by blue? No. Then turn left.

Now look at the cyan arrow #2 in the diagram. The left side is the blue civilization. The endpoint is where three hexes meet. Look at the hex in front of you. Is it owned by blue? Yes. So turn right.

If you keep the current direction as an int 0…5 then turning left/right will involve ±1 mod 6.

By following the edges one by one you will form a complete chain where you have returned to the original point. I think this works for any shape, no special cases.
> 5 votes

# Answer
I thought I was too smart for my own good. After many, and I mean, many hours of fighting this, I had to fall back to DMGregory's answer in the fullest. Every single time I thought I had it, there some weird generation that gave me a new angle and direction that would not be caught. I was very stubborn walking only the edge cells.

### You have to walk the outside!

If you're working with the possibility of single tile peninsulas, there is no choice. I did not truly realize this and was sure it could be done because I had
looked at this guide https://dillonshook.com/hex-city-borders/

For Civ style borders that do not have single tile peninsulas or really odd shapes, it works great. But for what I am doing, any shape is a possibility.

Here is a literal translation of DMGregory's answer in code which I hope is easy enough for others to follow. You can combine this with the guide linked above and the author's github gists.

```
static List<Vector3Int> FindHexCubePerimeterLoopOutside(List<Vector3Int> cubeCells, Vector3Int startCell)
{
    var perim = new List<Vector3Int>();
    var footCell = startCell;

    var startHandCell = footCell.GetNeighborCube(HexDirection.E);
    var handCell = startHandCell;

    if (cubeCells.Any(x => x == handCell))
        throw new Exception("Start Cell Must be the top right most cell");

    var handMovedFromStartingLocation = false;
    var finished = false;

    //Yes, this happened to me. Still refining my actual regions and merging is apparently flawed.
    if (cubeCells.Count == 1)
    {
        Debug.LogWarning("Only 1 Tile Perimeter");
        return cubeCells;
    }

    perim.Add(startCell);
    do
    {
        var footMoved = false;

        //The starting direction is always relative to the hand
        foreach (var footDirection in CounterClockwiseDirections(handCell.CubeCoordDirection(footCell)))
        {
            var newFootLocation = handCell.GetNeighborCube(footDirection);
            if (cubeCells.Any(x => x == newFootLocation))
            {
                if (newFootLocation == footCell)
                    continue;

                //It's possible and common that we ended up crossing a single body of water
                //The tile muse be connected
                if (footCell.HexCubeDistance(newFootLocation) > 1)
                    continue;

                footCell = newFootLocation;
                perim.Add(newFootLocation);
                footMoved = true;
            }
            else if (footMoved)
                break;
        }

        var handMoved = false;

        //The starting direction is always relative to the foot's.
        foreach (var handDirection in ClockwiseFromDirections(footCell.CubeCoordDirection(handCell)))
        {
            var newHandPosition = footCell.GetNeighborCube(handDirection);

            //Just like the other distance check, we need to make sure that if the hand position is back to the original position
            //that the current foot cell is a neighbor because it is possible that we are walking back out of an inlet.
            if (newHandPosition == startHandCell && footCell.HexCubeDistance(startCell) <= 1 && handMovedFromStartingLocation)
            {
                finished = true;
                break;
            }

            if (cubeCells.All(x => x != newHandPosition))
            {
                if (newHandPosition == handCell)
                    continue;

                handMovedFromStartingLocation = true;
                handCell = newHandPosition;
                handMoved = true;
            }
            else if (handMoved)
            {
                break;
            }
        }

        if (!handMoved)
            throw new Exception();

    } while (!finished && perim.Count < MaxPerimeterResult);

    if (perim.Count >= MaxPerimeterResult)
        Debug.LogError("Cancelled out of the perimeter loop. Stuck.");

    var lastCell = perim.Last();
    if (lastCell == startCell)
        perim.RemoveAt(perim.Count - 1);

    return perim;
}

```

It would be too much to show all of the code and I tweaked a lot of it to use cube coordinates, but the hard part is done. You just need to translate this to be whatever coordinate system you are using. If you do, the actual drawing of the border from the linked guide should just fall right in.

Here's the results.
> 1 votes

---
Tags: unity, tilemap, hexagonal-grid
---