# Question
Title: Unreal C++ Detecting new Key Down during current Key Hold
I am currently working on a combat system and I wanted to be able to have key combos to execute combat moves and such, and I am detecting key input type as well for example, if the key is tapped, or long pressed.

I use this line below to record the time a key is pressed, and time when the same key is released, so I can differentiate whether the key is just a quick tapped or long pressed.

> FPlatformTime::Seconds();

and when the the game detected a key press, it will execute the function below, using a timer and stopped on released.

```
//Long Press
void ABasePlayerController::StartRepeat(UFunction* FunctionNamesToCall, FKey KeyInput)
{
  //Execute if Timer is still active
  if (IsKeyDown != false && GetWorld()->GetTimerManager().IsTimerActive(RepeatTimerHandle) && WasInputKeyJustPressed(KeyInput))
  {
     CalledFunction.Broadcast(FunctionNamesToCall, KeyInput);
  }
}

```

The problem is when I wanted to make a key combination, and I stopped this function, whenever a new Key is pressed, the new key will be considered as a **Long Pressed** as well. My current codes only able to register input types after the key is released, and I wanted to be able to make a charging combo as well.

For example when I'm holding a **Tab** and I tap a new different key, both keys will be considered as a **Long Pressed**, while the expected result supposed to be **Long Pressed** **Tab** key, and the new pressed key is a simple quick tap.

Any ideas? Thanks!

# Answer
> 1 votes
If I'm understanding it correctly, you have a single timer but many buttons that could be pressed. Why not have N timers, where N == Number of Buttons. This may sound daunting and gross; but it's quite easy to manage with a map (which is called a Dictionary in C# or Python.)

Then use the keys that you're checking for as the inputs to the map, with the timer being the piece of data being stored. Now you have a (constant time!) algorithm for managing any number of timers and it doesn't take much code to access/modify the timers.

This would probably be a map\< FKey, FPlatformTime \> if I'm reading your types correctly. Simply start, stop, and access your timers in the map via the FKey being pressed and voila.

---
Tags: c++, input, unreal-4, combat
---


# Question
Title: What colour space or mixing algorithm should I use for "watercolor-like" colour mixing in-game?
I want to make a game where the player creates potions out of coloured ingredients, and I think the RGB or HSV colour spaces would be confusing for players expecting (red + yellow = orange, red + blue = purple).

RYB (red-yellow-blue) seems the closest to what I want:

However, I don't want to hard-code the colours, as some ingredients are randomly generated or have impure colours. Also, I'd like to represent the "locations" of potions of objects on the colour space on a 2D "map". How would I implement this in code? E.g. mix two RED items with one BLUE item and one GREEN item.

# Answer
To answer your question succinctly, RYB (red, yellow, blue) would be most intuitive and closest to mixing physical colors, aka pigments, which blend subtractively.

To understand the mixing behavior of RYB color-space, see both the color wheel diagram in the question, as well as the color tree below. For your use case it seems to me it would be simplest to implement hard coded blending, roughly following these RYB principles.

However, since you mentioned you are opposed to implementing hard coded blending, if you want this mixing behavior to be dynamic you can use CMYK color space, which is a subtractive color model used primarily for printing. Blending two CMYK colors will behave analogously to pigmentary blending

With this approach however you may be restricted by the CMYK color space, which is rather compressed and can be difficult to convert to and from while preserving color.

For a visualization of the problem of converting between color spaces you could check out this video overview of color spaces, as well as this color space comparison diagram.

For those who care to go a bit deeper, read on.

---

As the question hints at, there are a variety of color spaces and blending types. To design the gameplay mechanic you have described I believe you are looking for **pigment color / subtractive color blending**.

The wiki page on pigments has far more details about the physics and theory behind the perception and behavior of these but the birds-eye overview of pigment color can be summarized in a few points:

First, when visible light mixes, it becomes white. This is called additive blending. When pigment mixes, it becomes black-ish. This is called subtractive blending.

Secondly, by defining primary colors (ideally distributed relatively evenly along the emission spectrum, commonly RBY, RGB, CMY etc) these colors can be mixed to create a color space. (You can mix them additively or subtractively but in this case we are looking at subtractive blending) Mixing primaries you can make secondary, tertiary, quaternary, etc... Folks rarely bother beyond quaternary colors because they all devolve into browns and various earth-tones the deeper you go, asymptotically approaching black. This will happen regardless of the primary colors, but choosing more evenly distributed primary colors will reduce the severity of this effect.

Color science and color theory are massive fields and you can go far deeper into the specifics but I think for feeling out the basic mechanics of the game all you need is that primary color based mixing behavior, which is demonstrated both in the diagram you included in your question, as well as in the chart below.

I would say hard coding this blending would be the simplest solution to give you flexibility for making a variety of potion colors, regardless of their distribution along the color space, while avoiding degenerating into muddy tones, but if you really want dynamic blending you can get it through CMYK color representation.

CMYK is primarily used for printers, and is subtractive, as opposed to RGB and most other color repesentations typically used in digital displays, which are additive. The wiki page for CMYK goes into more detail but basically if you add 2 CMYK colors they will give you the pigmentary blending behavior you are looking for.

Note though, if you are currently coloring your potions with RGB, Hex, etc you will need to convert to CMYK, do the blend, then convert back to whatever your normal color representation is to apply it to the new object, but this can be trickier than it sounds.

Blending CMYK colors can be difficult due to CMYK's limited color space, so your colors may get squished when converting back and forth, eg:

`RGB(A) != RGB(B) but CMYK(A) == CMYK(B)`

You can experiment with the compression of converting to and from CMYK and see the specific formula for implementing the conversion in this RGB-\>CMYK converter.

To understand the weird behavior here it helps to see a visualization of the color space, check out this video.

You can also look at the difference between CMYK and other color spaces representable colors this color space comparison, as well as this video overlaying several color spaces in 3D, demonstrating the gamut issues with CMYK conversion.

That should be more than enough theory, so for a bit of practical exploration, check out some of the other answers with code samples, or try comparing various colors with the Google color picker.
> 6 votes

# Answer
As pointed out in other answers, the colour wheel most of us are familiar with doesn't match the way that pure light mixes - which is what's easiest to model with our usual representations of colours in a computer program.

With pure light wavelengths, yellow and blue are complimentary in our vision system, and blending them yields black (if subtractively mixing CMYK inks for example) or a neutral grey (if additively mixing emission from computer screen phosphors, or even a rapidly-spinning disc as shown in this example from the Dimensions of Color):

But it's still true that many substances that our players are familiar with in everyday life obey different colour mixing rules - due to more complicated physical & chemical interactions in their constituents. For (some) paint, yellow and blue does indeed make green, as shown in this example from CharM:

Modelling these fine-scale interactions is likely waaaay more complicated than we want to get for most games, but we can hack it a bit to give our players a more familiar experience.

One strategy is to convert the colour to a familiar HSV space, then apply some biases over that space to warp it the way we want. For example, we can shift the hues around so that yellow sits equidistant between red & blue, taking the place of green:

On the left you can see the standard HSV colour wheel, with red, green, and blue equidistant, which places blue and yellow as complementaries, opposite one another on the colour wheel. Taking an average between them gives us a neutral grey, as it does when mixing coloured light.

On the right, we've smushed the hues around, so that blue is opposite orange instead (its conventional complementary in painting colour theory), and yellow takes the place of green. Now when we take the average of yellow and blue, we land not in the grey middle of the disc, but in a decidedly green hue.

Here's how this colour transformation might look in code (using Unity C# as an example):

```
Vector3 ToPigmentSpace(Color color) {
    // Convert RGB color to standard Hue Saturation Value (range 0-1 each).
    Color.RGBToHSV(color, out float h, out float s, out float v);

    // Change hue to degrees for ease of intuition.
    h *= 360f;

    // Compute a shift that will stretch the orange range
    // until yellow reaches the 120 degree mark,
    // and compress the cyan/teal range so blue stays at 240 degrees.
    float hueShift = Mathf.Clamp01(h > 90f ? 2.0f - h / 120f : h / 60f);

    float shifted = (h + 60f * hueShift) * Mathf.Deg2Rad;

    // Model the colour as a point in a spindle, with the bright hues
    // around the outer rim, and the greyscale running up the z-axis.
    Vector3 pigmentSpace = new Vector3(
                       s * Mathf.Cos(shifted),
                       s * Mathf.Sin(shifted),
                       v - 0.5f * s);

    return pigmentSpace;
}

// Convert back from our pseudo-pigment spindle space to an RGB color.
Color FromPigmentSpace(Vector3 pigmentSpace) {
    // The hue & saturation are expressed in the XY plane.
    var chromaticity = (Vector2)pigmentSpace;

    // Saturation is our radius from the grey axis.
    float s = chromaticity.magnitude;
    // Value is our height along the spindle, treating saturated colours as max.
    float v = pigmentSpace.z + 0.5f * s;

    // Decode our shifted hue angle into degrees.
    float shifted = Mathf.Atan2(chromaticity.y, chromaticity.x) * Mathf.Rad2Deg;
    if (shifted < 0f)
        shifted += 360f;

    // Undo the hue shift to bring us back to standard HSV space.
    float hueShift = Mathf.Clamp01(shifted > 150f ? 4.0f - shifted / 60f : shifted / 120f);
    float h = shifted - 60f * hueShift;

    // Convert from HSV back to RGB.
    return Color.HSVToRGB(h/360f, s, v);
}

```

To mix these, you can do something like this:

```
Vector3 pigmentSpace = Vector3.zero;

foreach(var ingredient in ingredients) {
    float weight = ingredient.weight / totalWeight;
    pigmentSpace += ToPigmentSpace(ingredient.rgbColor) * weight;
}

Color result = FromPigmentSpace(pigmentSpace);

```

> Also, I'd like to represent the "locations" of potions of objects on the colour space on a 2D "map".

You can use the 3D "pigment space" defined above as your map coordinate system. Just discard the z axis (roughly corresponding to value), and what remains is a 2D space describing a colour disc, 1 unit in radius, with the pure hues along the outside and neutral grey in the middle.
> 2 votes

# Answer
The red-yellow-blue color circle invented by Le Blon in the 1720s is incorrect. You can't create perfect green by mixing equal parts blue and yellow. Creating a perfect magenta with red and blue is even harder - you usually end up with a muddy purple. And if you mix all three, you don't get grey, you get brown.

People already noticed that in the 18th century when it was introduced. They attributed that to the limitations of the pigments they had back then. But nowadays we know that it wasn't the pigments which were wrong, it was the theory. Unfortunately it refuses to disappear from the literature and is even still taught in some art schools.

The physically correct color model for subtractive color mixing is actually Cyan - Magenta - Yellow:

But how do we represent this color model in software when our monitors work by additive color mixing of Red, Green and Blue?

When you want to mix two CMY colors, you can actually do the same as with RGB. You just calculate the sums of all three color channels:

```
c = color1.c + color2.c
m = color1.m + color2.m
y = color1.y + color2.y

```

Contrary to RGB, these channels do not represent light, they represent darkness. The default state in the CMY color model is white, and adding color makes the image darker. Add enough color to reach maximum saturation on all 3 channels, and you get black.

You can then convert the final CMY colors to an RGB color using the following algorithm:

```
r = 255 - c
g = 255 - m
b = 255 - y

```

By the way, some graphic APIs support subtractive color mixing out-of-the box. When they do, you can usually input your source colors in RGB.
> 1 votes

# Answer
In order to have both intuitive and minimal effort coding this, I would go for blending in a linear RGB color space, by means of multiplication. I'd expect this to behave very intuitively.

I would suggest trying this approach (pseudo code):

```
vec3 mix_potions(vec3 i1, vec3 i2, float amount1, float amount2) {
    i1 = pow(i1, 2.2); // raise each R,G,B component to power 2.2
    i2 = pow(i2, 2.2); // to linearize the values.
    float mix_amount = min(amount1, amount2); // how much will mix?
    amount1 -= mix_amount;
    amount2 -= mix_amount;
    vec3 mix = mix_amount * i1 * i2 + amount1 * i1 + amount2 * i2;
    mix /= max(max(mix.r, mix.g), mix.b); // renormalize one component to 1
    mix = pow(i2, 1.0 / 2.2); // apply gamma companding again
}

```

The renomelization is will make your mixed colors bright, which is of course optional.

Alternatively try additive blending for experimentation:

```
vec3 mix = i1 * amount1 + i2 * amount2; // additive mixing (non-watercolor like)

```
> 0 votes

---
Tags: game-design, game-mechanics, color, visualization
---


# Question
Title: Model colors look much better in blender than Unity (LWRP), how to fix bad colors in Unity LWRP?
I made some models in blender 2.8:

After importing them to Unity, they look much worse:

Still the same material as in blender, I use the LWRP and have had nothing but issues with it, the lack of AO being one. Is there something I'm missing because it should not look this much worse in the Game Engine?

# Answer
AO is an expensive effect, so of course it's not supported in LWRP.

It sounds like you aren't baking your textures. Generally it's not a good idea to import material settings directly from Blender:

* Some settings can't be imported, so your material often will look different in Unity. Blender is primarily designed for pre-rendered graphics, while Unity is designed for real-time graphics. This means that Blender has all kinds of texture and lighting settings that have no equivalent in Unity.
* You often end up with one mesh that uses 5 - 10 different materials, which makes the mesh more expensive to render
* After importing enough models, your project will get filled with an overwhelming number of imported materials, making it nearly impossible to find a specific material with the search bar.

Texture baking refers to creating a UV-mapped texture from the material and lighting settings that you have configured in your 3D modeling software (Blender in this case). This is the only way you're going to be able to recreate the look of AO without an expensive post-process shader. Gradients, patterns, AO, etc can all be baked into a single albedo/diffuse texture, which is inexpensive to render. If necessary, you can also bake specular, normal maps, etc.

Texture baking is an essential skill for any 3D artist working with a game engine. If you don't know how to bake textures, you should learn this immediately: https://docs.blender.org/manual/en/latest/render/cycles/baking.html
> 1 votes

---
Tags: unity, graphics, blender
---


# Question
Title: How to calculate a perfect Super Mario speedrun?
I've dedicated my time to Super Mario lately, so eventually I ended up watching some speedruns.

I thought to myself, how could one calculate the perfect set of minimal in-game movement?

I considered comparing the time needed to pass to a certain point, for example if there are two paths to take. If I wanted to write a program to measure and calculate those values for me, how would I proceed?

# Answer
This is a shortest path problem, albeit of a strange sort.

Although usually we use pathfinding algorithms to find routes through space, where each node in the search space corresponds to a physical location, they actually work just fine on more general graphs too.

In this case, each node in the search space is one snapshot of state the game could be in on a particular frame:

* The time / number of frames elapsed since the level started
* The position and velocity of Mario in the game world
* Whether Mario is big or small (or has the fire flower, or...)
* The state of each dynamic tile in the level (broken bricks, revealed note blocks...)
* The position and velocity or AI state of each item / enemy currently being simulated (goombas, koopas, mushrooms, piranha plants, thwomps, bullet bills, projectiles)
* The time remaining on any special effects, like star power or P-switches

You start with just one node: the stat of the game on the first frame after the level has loaded. Mario and all items are at their initial spawn points.

From a given node, you can compute neighbouring nodes by evaluating what game state occurs on the next frame for each possible combination of inputs that might occur in this frame:

* Player presses nothing
* Player presses right
* Player presses left
* Player presses jump
* Player presses down
* Player presses both right & jump
* Player presses both left & jump
* ...

Now we have a start node and a way to compute neighbouring nodes, so we can start exploring the space of all possible play trajectories using graph search algorithms.

The downside is, this state space is HUGE. With just the options below, we have a branching factor of 7, more if there are additional inputs we need to include like pressing the B button for the fire flower. So the total number of states to search is (in the worst case) \\$7^\text{frames}\\$, which explodes exponentially.

We can rein this in if we can find a good heuristic - a way to evaluate which nodes are the best candidates for the outcome we want, closest to our goal. If our goal is to reach an x coordinate corresponding to the end of the level, then a decent heuristic is to measure Mario's x distance from that point, and divide by the maximum distance Mario can travel in one frame. That gives us our most optimistic estimate for how many frames away from our goal we are, and we can prioritize searching from nodes that are closer to that goal.

With this heuristic in hand, we can use the A\* algorithm to search through the game state space to find the most optimal sequence of inputs to reach the goal in as few frames as possible.

Granted, this will still be computationally intensive. I haven't run the numbers to confirm how tractable this is. You may find you can only handle simple Mario levels in a reasonable amount of computing time, depending on how efficiently you can construct neighbouring game states and detect when a game state has already been visited by a different input sequence. But this at least gives you a framework with which you can attack the problem.
> 3 votes

---
Tags: algorithm, optimization
---


title: Fastest way to get all adjacent tiles?

text:
# Question
Title: Fastest way to get all adjacent tiles?
What is the fastest way to get all adjacent tiles in a two-dimensional array of tiles, converted into a single-dimensional array?

If you don't know the answer, then the fastest way to do it in a two-dimensional array would be fine as well.

I tried the following, but it does 9 calculations, which is 1 too much when it comes to optimization.

```
for(int x = -1; x <= 1; x++) {
  for(int y = -1; y <= 1; y++) {
    if(x != 0 || y != 0) {
      Tile adjacent = Tiles[current.x + x, current.y + y];
    }
  }
}

```

# Answer
What you are proposing is pretty much the fastest; as determining wether or not you are on the same tile would probably be more costly than just doing it. Doing it 9 times.

But as an alternative; consider if you will a space/time tradeoff.

Instead of doing this calculations at a critical time, do them when you are reading the map into memory; storing in each tile the location of their neighbours. It requires more space in memory per tile; but it does save time when doing lookups. If you have an application-wide enum (or similar) for directions, even better; then you could do something like:

```
aNeighboringTile = current.neighbors[NORTH];

```

The tradeoff can be tuned to use either cardinal neighbours only, or both cardinal and diagonal neighbours; the former being tighter and the latter being faster.

A question that you seriously need to consider, of course, is wether or not this is *actually* necessary, or if your current approach in practice is fast enough.

If you are *already* facing slowdowns due to the extra calculation; then it is likely that the only thing that will give any speedup is pre-calculating neighbors.

**Edit:** This can of course be compined with Gajet's suggestion to use a constant array of the index deltas to search to eliminate the extra calculations during generation/loading.
> 2 votes

# Answer
If I am iterating through a 3D array of tiles and I care about the neighbors, I maintain an index of each neighbor for quick access. I also store an empty row for neighbors outside of the array. Your code would only be more simple with a 2D array. I apologize for the mess, this is prototyping code. Most complex conditionals is only performed for the first cell of each row. It also has code for reading neighbors cells of neighboring arrays.

```
    static short empties[256] = {0};
    short *down, *up, *east, *west, *north, *south;
    short *tiles = this->tiles, *tile = this->tiles, *empty = &empties[0];
    int index = 0, skip; // Skip is cells skipped.

    for (int z = 0; z < SEGMENT_DEPTH; ++z)
    {
        down = (z == 0) ? empty : (tile - SEGMENT_WIDTH * SEGMENT_HEIGHT);
        up = (z == SEGMENT_DEPTH-1) ? empty : (tile + SEGMENT_WIDTH * SEGMENT_HEIGHT);

        for (int y = 0; y < SEGMENT_HEIGHT; ++y)
        {
            south = (y == 0) ? ( (this->south) ? &this->south->tiles[z * SEGMENT_WIDTH * SEGMENT_HEIGHT + SEGMENT_WIDTH * (SEGMENT_WIDTH-1)] : empty ) : (tile - SEGMENT_HEIGHT);
            north = (y == SEGMENT_HEIGHT-1) ? ( (this->north) ? &this->north->tiles[z * SEGMENT_WIDTH * SEGMENT_HEIGHT] : empty ) : (tile + SEGMENT_HEIGHT);
            skips = 0;

            for (int x = 0; x < SEGMENT_WIDTH; ++x, ++tile, ++skips)
            {
                if (*tile == 0)
                    continue; // skip empty tiles

                up += skips, down += skips, south += skips, north += skips;
                west = (x == 0) ? ( (this->west) ? &this->west->tiles[z * SEGMENT_WIDTH * SEGMENT_HEIGHT + y * SEGMENT_HEIGHT + SEGMENT_WIDTH - 1] : empty ) : (tile - 1);
                east = (x == SEGMENT_WIDTH-1) ? ( (this->east) ? &this->east->tiles[z * SEGMENT_WIDTH * SEGMENT_HEIGHT + y * SEGMENT_HEIGHT + 0] : empty ) : (tile + 1);
                skips = 0;

                if (*up != 0 && *down != 0 && *west != 0 && *east != 0 && *north != 0 && *south != 0)
                    continue;

                // . . . DO WORK HERE . . .

            }
            up += skips, down += skips;
        }

```
> 0 votes

# Answer
I normally use this:

```
    //- start at your left tile.
    int x = -1;
    int y = 0;
    for (int i = 0; i < 4; i++) {

        USE THE (x,y) ADJACENT TILE HERE.
        Debug.Log(x + ", " + y);

        //- this will set x,y to the bottom tile.
        if (x == -1 && y == 0){
            x = 0;
            y = -1;
        }
        else {
            //- this will set x,y to the top tile.
            if (y == -1) {
                x = 0;
                y = 1;
            }
            //- this will set x,y to the right tile.
            else {
                x = 1;
                y = 0;
            }
        }

```

It's not the prettiest code, but it only uses 7 calculations. The first loop uses 1, the second loop uses 2, the third loop uses 2, and the fourth loop uses 2. After 4 loops, the output is `(-1,0)`, `(0,-1)`, `(0,1)`, `(1,0)`; all four directions around a center point of `(0,0)`.
> 0 votes

# Answer
The reason it is checking 9 tiles is because it is also checking the middle tile. IT's funny, because I came up with the exact same solution. And you should be proud, as it's a fairly elegant one. anyway, the line that interests you is the `if( ... !( rowOffset == 0 && colOffset === 0 ))` this makes sure that you skip the "middle" tile. Heres a simple function that I wrote for a CS200 class. it returns all 8 surrounding tiles as an array. It's in Java, but it can easily be adapted to the language of your choice.

```
    String[] rtrn = new String[ 8 ];
    int index = 0;
    int offsetRow, offsetCol;

    // Offset the rows by -1, 0, 1
    for ( int rowOffset = -1; rowOffset <= 1; rowOffset++ ) {
        offsetRow = row + rowOffset;
        // Offset the columns by -1, 0, 1
        for ( int colOffset = -1; colOffset <= 1; colOffset++ ) {
            offsetCol = col + colOffset;
            // Make sure the coordinates are on the board &&   skip the "center" tile.
            if( !outOfBounds( arr, offsetRow, offsetCol ) && !( rowOffset == 0 && colOffset == 0 ) ) {
                // Set the next value in the return array
                rtrn[ index ] = arr[ offsetRow ][ offsetCol ];
                index++;
            }
        }
    }
    return rtrn;

```

here is the outOfBounds function

```
    // Below 0 or greater than the array bounds are a no-go
    boolean tooSmall = ( row < 0 || col < 0 );
    boolean tooBig   = ( row > ( arr.length - 1 ) || ( col > arr[ 0 ].length - 1 ) );

    return ( tooBig || tooSmall );

```
> 0 votes

---
Tags: xna, xna-4.0, performance
---


# Question
Title: Why does my Enemy A.I stop moving when it hits the wall, and how to fix it?
I am making my 2D platformer game at the moment, and I am still a beginner. I saw this tutorial on youtube in which he showed how to make an enemy a.i move. He manages to move it but he didn't show how to flip the enemy once it hits the wall because when it does, it doesn't move. How do I fix this?

Ps: He used a gameObject to flip the enemy.

**Here is an example of the error I am facing**

---

## **Enemy Script**

```
public float speed;
public float distance;
private bool movingRight = true;
private Rigidbody2D myBody;
public Transform groundDetection;
public LayerMask ground;

private void Start()
{
    groundDetection = this.transform;
    myBody = GetComponent<Rigidbody2D>();
}

void Update()
{
    transform.Translate(Vector2.right * speed * Time.deltaTime);

    RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, 2f, ground);

    if (groundInfo.collider == false)
    {
        if(movingRight == true)
        {
            transform.eulerAngles = new Vector3(0, -180, 0);
            movingRight = false;
        }
        else
        {
            transform.eulerAngles = new Vector3(0, 0, 0);
            movingRight = true;
        }
    }
}

```

# Answer
> 1 votes
**The Cause**

There are two possible issues here:

* The first is that if your 'if' statement is *never* being reached (groundInfo.Collider == true) then of course your enemy just keeps walking in the direction they're going and never turns around. *I highly suspect this is the case.* Your ground collision logic should have no bearing on your 'turning around' logic.
* The second is that if your 'if' statement is *always* being reached (groundInfo.Collider == false) then since Update is called rapidly in succession, on the first call your code says "Oh, you're moving right? Well.. turn around!" and on the second call your code says "Oh! You're moving left? Turn around!" So every time you update you are just having them turn around. I would expect this to result in them "jiggling" rather than being just stuck to the wall, but I don't see the code here that actually modifies their position.

---

**How to get more responses**

We have no context as to what class is holding this Update function. Is this "transform" you're modifying the enemies' vector? Is this vector a member of the enemies' class?

Also, I can guarantee you haven't run your code in a debugger (or at least, with breakpoints) and as such I should be loathe to assist you. Run your code in a debugger so you can see which lines of code you're actually hitting. It's a good possibility that your whole if-statement is being skipped and if you're going to be writing software much in your life you need debugging as one of your top skills (if not the top skill!)

---

**The Solution:**

To fix this you need to test something more robust like "If I'm touching the wall *AND* I'm facing the wall, turn around instead"; because currently it's an infinite loop that says "If I'm touching the wall, turn around."

Additionally you need to disassociate your ground-collision logic from your 'turn around' logic.

Finally, I'd also get rid of the extraneous if statement altogether as you are doing the same thing in each case. Something more like:

```
movingRight = !movingRight;
transform.eulerAngles.Y += 180;

```

You want as few if-statements in code as you can possibly manage. Every if statement is a case you have to test for and thus more difficult to validate is working properly. It's also harder to validate by eye.

What's more? Every if-statement you have in your code is a possible bad-branch prediction which can cause immense slowdown in your problem; as if a bad-branch is predicted it can result in invalidating the cache lines that were associated with that branch. See here for some information on bad prediction. All you really need to know is that you should be in the habit of questioning if/how to remove any 'if' statement you write. Some are required, but the less the better.

# Answer
> 1 votes
```
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, 2f, ground);

```

It looks like you are casting a ray straight down and filtering for "ground," and if this returns false (e.g. there is no ground) then turn around. This works when the game piece gets to the edge, but not when it hits the wall (there is ground, the result is true, do nothing)

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


# Question
Title: i don't understand what i am doing wrong. (line 29)
my problem is that i can't use elipse in line 29 ore someting like that. line 29 = elife player\_choice == '2':

# Answer
> 2 votes
There is an else wrong indent in line 21. Add one more tab to it and in its code block. After try to rebuild.

Python use identation to make code blocks.

# Answer
> 0 votes
add one more tab before **elif** and prew lines.

Tabs is very impotent in python

the same numbers tabbed mean code in the same logical block

in your case **if** and **elif** is in different blocks but must be in the same

---
Tags: python
---


# Question
Title: Can I use the 2d physics engine in a 3d game (or viceversa) in Unity?
This is entirely for performance. The 2D physics are less expensive, but I require 3D for some scenes. I never need both at the same time. I know you can have 2D with an orthographic perspective in a 3D engine, but what I want is really the physics engine. Also, is there a way of turning off these engines? I´ve made most collisions from scratch and am only using them for some raycasts at the beginning and for some collider/rigidbody.casts in not every, but a lot of frames (If I understand correctly, they are calculated from the physics engine in each FixedUpdate()).

# Answer
Yes, you can use both at the same time. Though, you can only have 2D physics interactions with the 2D physics engine. The models are separate from the logic of the physics engines, so your objects can even have 3D models but 2D physics. Your raycasts can be separate from the physics engine too.

You can just turn the 2D rigidbodies on or off. That will enable/disable physics for certain objects. If you want all 3D or 2D physics to be off you can do that too if you have Unity 2017 or later.

The main problem you're having is probably moving the game-objects that have physics enabled on them. Even just rotating an effector will have performance impact.

In my game, I usually had 10+ effectors and I was mistakenly rotating the whole game-object when I just wanted to rotate the model (sprite, because it was 2D) of the game-object. So, my game would constantly re-calculate the physics for each effector on screen and it'd have a huge performance impact. After 20 objects or so, it would have about 1 frame per second on my phone. Then I separated the physics and the sprites of the game-objects, the game had no problems having 50+ objects at 30FPS on my phone.
> 1 votes

# Answer
First of all, are you sure that the framerate of your game is affected by unnecessary physics calculations? Have you measured it using the Unity profiler? It's usually not worth the time to chase imagined performance problems when you have no profiler data to confirm that they actually matter and no profiler data to compare to in order to check if your improvements actually improved things.

But let's assume that you did profile and did find out that 3d physics calculations are indeed a relevant performance eater.

> Can I use the 2d physics engine in a 3d game?

Certainly. The 2D physics engine works very similar to the 3D physics engine, just that it neither considers nor changes the z-coordinate of game objects. You can have a `*Collider2D` and a `Rigidbody2D` on an object which also has a `MeshRenderer` and is rendered by an angled perspective camera.

> Also, is there a way of turning off these engines?

In order for a game object to be handled by the physics engine, it needs a rigidbody (2D or regular). So if you don't want to use the build-in physics, just don't add rigidbodies to your game objects. When there are no objects in your scene with rigidbodies, then the physics engine is *technically* still on, but won't do anything and its resource consumption will be negligible.

However, keep in mind that the physics engine is also responsibel for calling the `OnTrigger*` and `OnCollision*` Events and will only call them when at least one of the objects involved has a rigidbody. If you still want to use these events but don't want these objects to get moved by the physics engine either, give them rigidbodies, but make them kinematic (For 2D rigidbodies, set their body type to "Kinematic"; For 3D rigidbodies, enable the "is Kinematic" checkbox).
> 0 votes

---
Tags: unity, 2d, 3d, performance, physics-engine
---


# Question
Title: Trying to Access Components of an Object in another class
I think my C# is a bit lacking here but I am trying to access a component in a list of objects in another class. I am trying to access UnitController from MultiSelectClient and I'm not sure how to do this. I can remove the objects from the list but I can't seem the access each one even if I try a ForEach loop, I can't wrap my head around it.

```
UnitController.SelectedUnits //Is the list I'm trying to access.

```

Ive tried doing

```
UnitController.SelectedUnits.Find/FindAll(gameObject)//but that returns an error

```

This is where the list is defined

```
public class UnitController: MonoBehaviour
{
    bool clicked = false;
    bool dragging = false;
    //public float speed = 10f;
    //public float rotationSpeed = 10f;

    public LayerMask groundLayer;
    public NavMeshAgent playerAgent;

    public static Vector3 mouseDownPoint;
    public static Vector3 mouseUpPoint;
    public static Vector3 currentMousePoint;

    public static Rect selection = new Rect(0, 0, 0, 0);
    private Vector3 startClick = -Vector3.one;
    public Texture2D selectionHighLight;

    public static List<GameObject> SelectedUnits;

    public RaycastHit firstRay;
    public RaycastHit secondRay;

    private void Start()
    {
        SelectedUnits = new List<GameObject>();
    }

```

This is the script that needs to access it. At least I want to be able to iterate through the list and access each unit in the list and its components.

public class MultiSelectClient : MonoBehaviour
{
    public bool Selected = false;
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
            camPos.y = Screen.height - camPos.y;

            //if inside the cameras drag selection area then mark player as selected
            Selected = UnitController.selection.Contains(camPos);

            Debug.Log("Selected");
            if (Selected)
            {
                addTo();
            }
            else
            {
                UnitController.SelectedUnits.//something
                UnitController.SelectedUnits.Remove(gameObject);

            }
        }

    }
```
</code></pre>

# Answer
```
public class MultiSelectClient : MonoBehaviour
{
    public bool Selected = false;
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
            camPos.y = Screen.height - camPos.y;

            //if inside the cameras drag selection area then mark player as selected
            Selected = UnitController.selection.Contains(camPos);

            Debug.Log("Selected");
            if (Selected)
            {
                addTo();
            }
            else
            {

                foreach(var Unit in UnitController.SelectedUnits)
                {
                    Debug.Log("Running loop");
                    Unit.transform.Find("SC").GetComponent<MeshRenderer>().enabled = false;
                }
                UnitController.SelectedUnits.Remove(gameObject);

            }
        }
    }

```

I just had to define where the foreach loop had to find the variable.
> 0 votes

---
Tags: unity
---


# Question
Title: Terms of integrating 3rd party sdk and libraries in your engine
I am developing my own engine and integrating Bullet Physics.

Now Bullet Physics is open source under Zlib license. My concern is, can original owner change the license later on to paid and how it can affect the games which already released with my engine? Do I need to strip out all the code related to Bullet Physics?

Same questions I'd like to know for free engines like Unity & Unreal.

Thank you.

# Answer
**Disclaimer: I am not a lawyer**, so to be on the safe side, you might want to contact one. **All information is supplied without guarantee.**

There is a wikipedia article about Software relicensing which you probably should check out.

Also on the opensource guide on the legal guide section 6 "What if I want to change the license of my project?" you can see that actually changing a license is not always that trivial.

If a library version comes with an opensource license, I personally would expect, that only on a version update it might change. So I would expect you do not have to strip out all the code related to it, if you do not update the library in that case.

Btw. you should check not only the Bullet Physics license, but also the licenses of the used libraries inside of Bullet Physics.

Unity and Unreal may be free to use in the beginning, but you will have to pay for using them if your game is not for free and you earn enough money with it.
> 1 votes

---
Tags: software-engineering, licensing
---


# Question
Title: Do multiple small script files use more RAM than one bigger script file?
So I'm still new to making games that have a baseline for computer resource usage and I'm confused with my question. I can't find an answer anywhere on the internet so I'm here.

Simple Question:

> Which uses more resources? x10 small scripts or x1 mega script?

Detailed Question:

> Would x10 small scripts that consist of about 70 - 100 lines of code, be more resource consuming than x1 mega script containing about 700 - 1000 lines code?

# Answer
Scripts themselves take almost no RAM. You pretty much only have the cost of storing the CPU instructions (a few kilobytes at most, if your script is massive) and that's only once, it doesn't matter how many times the script is duplicated.

For comparison, a single bitmap sprite can to take up several *mega*bytes. It's your assets that are going to be taking up RAM.
> 2 votes

# Answer
When your game is compiled into bytecode, then all the script files disappear and are mixed into one giant mush of instructions (gross oversimplification, but it helps to get the idea). So it rarely matters how you organize your code across files for performance or memory consumptions. What matters is what that code actually does.

So when you wonder how to organize your sourcecode, then priority number one should always be readability or maintainability. See also the current hot network question "What are the benefits of multi-file programming?" on software engineering stack exchange

If you want to reduce the RAM footprint of your project, then you have to look at the actual content of your scripts and how you use them.

* Every component of every game object has a bit of management overhead. So having one large MonoBehaviour will often be slightly more memory efficient than lots and lots of small MonoBehaviours which do the exact same thing.
* This memory consumption is *per instance* of your script. If you put a MonoBehaviour on 1000 game objects, then it consumes 1000 times the amount of RAM if it's only on 1 game object (again a slight oversimplification, but it's a usable rule of thumb).
* But the actual memory footprint of each MonoBehaviour instance depends on how much data it actually stores in its public, private and protected member variables. A component which has just a single integer will consume a lot less RAM than a component which contains a large array of long strings. So if you have some MonoBehaviours which contain a lot of data but that data is only required by a small subset of objects in your game, then extracting that data into a separate component which you then add more selectively can save you memory.

But in most real-world Unity projects, the main contributors to memory consumptions are not C# scripts. They are the build-in Unity components and the assets they use. So before you start to look at the memory footprint of your own scripts, first consider if you really need all of your assets, which Unity components you put on your game objects and if you use those components in a memory-efficient way. For example, did you know that every single time you change a `material.color`, Unity creates an entirely new Material asset in memory?

If you would like to know which parts of your game contribute for how much memory consumption, then you can use the Unity Profiler to find out.
> 1 votes

# Answer
i think there is no exact relation between lines of code and ram usage. scripts are translated to lower level instructions in many levels and in the end those instructions are fed to the cpu based on defining that which functions ore which part of code should be run in the same time.

ram is used to store data like variables in programm and stores files from hard disk to be accessible when needed
> 0 votes

---
Tags: unity, c#, architecture, resource-management
---


# Question
Title: How do you technically represent a procedurally-generated map in the scene?
I've always wanted to create the type of map generator they use in Kingdoms and castles. Basically you provide a seed, and it generates land/water/trees/resources. Their maps are also completely flat (except water seems to be 1-2 positions down, which I assume would make it easier.

However I do not know where to look for guidance for this type of system, I am wondering if anyone can explain the logic of how that type of system works, or even better, point me to a tutorial that could get me started.

While there are tutorials on perlin noise and the like, I never really understood how to connect it to a proper tile, and what properties that tile should have, does it need colliders? is each tile a gameobject? If not, how do I create tiles with trees/rocks that I can gather? and so on.

# Answer
I myself am a procedural loving person and I have done a lot of PCG. From experience, I can say that procedural generation is too broad to define on "how to do it". There are lots of ways on how you can approach reaching some goal. That is a part of fun in procedural generation that every algorithm has something of its own and unique in some degree.

Of course we can generalise some things and look at some common approaches. But first let's ask a question: "what is procedural?".

> A lot of stuff I write here is opinion based. I am trying to share what I understood from a few projects with procedural generation. So I don't think it's ideal or something that defines PCG.

What I mean by this is that procedural isn't random. It utilises randomness in order for it to be procedural? More or less - yes. But I like to think about the result being procedural, what you get in the end is procedural. Placing a few objects at random places, I wouldn't call it procedural, but generating a map of objects placed randomly, following some rules to make sense - that is what I think is procedural.

I will try to define general approaches and try to guess the specific approach that was taken to generated this map from an example that you have shared.

---

**Noise generation based.**

Developers frequently take this approach because there is wide variety of different forms and shapes of textures that are being generated and they serve for different purposes allowing for generation of all kinds of shapes. Very common is to use textures for generating height maps for terrain `0` being at lowest point and `1` being at the highest point on the terrain.

Textures are just random numbers from `0f-1f` at each pixel. How those random numbers are generated for textures depends on the rules set for generating such a texture. So basically you can do the same thing just with random number generation without using a texture, but sometimes you want to save that data, to speed up some processes, to have a visual representation and so on... This is when textures are handy.

---

**Just random.**

The most common one and a base for everything else. Just using random numbers for indices and values to randomly place some object, extend it in some direction, create random positions for mesh vertices...

Nothing is truly random in most `Random` modules. They are just mathematical functions that will give the same result provided the seed for them was the same.

---

**Fractal based.**

Beautiful forms that generate itself from the same rules.

Wiki:

> There are two major methods of two dimensional fractal generation. One is to apply an iterative process to simple equations by generative recursion. The other main method is with Iterated Function Systems consisting of a number of affine transformations.

---

**Other.**

`Maze`, `Dugeon`, `Random Tree`, `L-System`...

PCG Algorithms

> There are lots of algorithms not to only generate maps, objects, and 3D. But text, dialogues, behaviours, story chain...

---

**Example from question.**

The approach I would take to generate this kind of a map.

Setting up `Random` module to take an `int/long seed`. Based on this `seed` we will get random values from our module that would change the world to some extent every time we change the seed and regenerate everything.

First thing that we would need is a tile map. Just a map that represents a grid of tiles `Tiles[10,10]`. It could be a 3D one and more `Tiles[10, 1, 10]`, we could even store some other information in that array, it doesn't really matter. But for this one I would choose a 2D tile map as this is enough. Tiles are not necessary `GameObject`s or even `class`es \[I usually make them classes or structs\]. They are just convenient containers holding data about tile, like its position, indices position in array that holds them and other valuable data for your type of generation.

Generate `river`, `lakes`, `grass`, `sand` tiles. For each of the tile type you could define it's own rules of generation. `Generate river by using some algorithm that would simulate behaviour of river`.

Then I would scatter resources like trees, rocks and everything natural. I would generated them on some tiles defined by some rules. Like `pick a random location, place tree, trees grow close one to another, close to water, place some more trees until its enough and still under limited number of trees`.

Then I would generate roads by using path-finding algorithm like `A*` for simplicity. Or I could first generated buildings - then generate roads. Or first generate the castle, then everything else. It all depends on the result we would like to see in the end.

It's really that simple and there are no things like generate neat texture then generate everything else based on this texture - it's still possible though, if you need this.

---

**Colliders.** They are widely used during process of generation. Usually to simplify rules or provide tools for human interaction with generation.

For example,

1. you could use colliders to check if something overlaps or can fit in during placement \[when you don't have strictly defined bounds or you can't utilise those bounds to achieve your generative goal\].
2. you could use colliders to allow designer to meddle in how something is generated. \[Blocking tiles, marking them walkable, allowing generation on them, setting some rules for the area...\].

---

> It's easy to create something procedural. But it's hard to make it fun and less repetitive, once you master generation, you have to master another field. And that is generating something unique and quite different from previous experience. You can see many patterns of repetitiveness in lots of games.

*In the end. Everything that PCG is can be boiled down to randomness, just random numbers. It's the way we use those numbers is what defines the shapes and forms of content we can create with them. And from those we create algorithms, techniques and new ways of morphing those random numbers into sets of other types of randomness.*
> 4 votes

# Answer
As with everything in Unity, there is no one way to do things.

Using a full-fledged game object to represent each empty tile *can* be a viable approach if you have rather small maps. But if you aim for a very large game world (perhaps even infinite), then the memory, CPU and GPU overhead of many small individual game objects gets too large and you will run into framerate issues.

You can drastically increase the limit of how many simple game objects you can get away with by using the new DOTS architecture and representing tiles as lightweight Entities instead of full-fledged game objects. That means if you are brave enough to face DOTS it in its current (late 2019) half-finished, spotty documented and poorly understood state.

If your terrain is entirely 2d and consists of square tiles with hard edges, then you could implement it as a Tilemap. Just because it is intended to be a 2D component does not mean that you can not use it as a spacial plane in a 3d scene.

If your terrain is 3d, then you could use the Unity 3d Terrain system for it. While the usual way to use 3d terrain is via the editing tools in the Unity editor, you can also create a terrain entirely procedural via scripts by changing its `terrainData` property.

If the aesthetics of the Unity terrain component aren't suitable for your game and you would like to have more control over the exact terrain geometry, then you could create your map as one single GameObject with a procedurally generated mesh.

And then there are of course assets on the asset store you can buy to save development time. Disclaimer: I didn't use any of these assets, so I can not vouche for their quality. But two assets which look quite promising to me are Terrain tile editor and Tycoon Tile.

> does it need colliders?

That depends. Do you want to use rigidbody physics? Most citybuilder games do not have much use for the physics engine, so the terrain doesn't really need a collider. But if you do use physics, then you need to give your map a collider in order to prevent objects affected by gravity to fall through it. Do you want to use the Unity pathfinding system? Then you also need colliders.

* If your terrain is flat, then a single BoxCollider will do the job.
* The TileMap Component can create its own collider based on the tiles it consists of, but that collider is intended for 2D game objects which move across the tilemap, not for 3d objects colliding with the tilemap as a whole. However, if you have entities which are objects in your game which are supposed to navigate the 2d terrain and can not move across every kind of tile, then the TileMap collision system could be of use to you.
* The Unity Terrain system already comes with a collider.
* If your terrain is a procedural mesh, then you will have to use a MeshCollider for it. If your terrain is large and complex, then you might have to break up your MeshCollider into multiple ones for performance reasons (mesh colliders with high polygon counts can become performance hogs).
> 2 votes

---
Tags: unity, procedural-generation, perlin-noise
---


# Question
Title: <Missing LoadingScreenManager.LoadScene> even though it's not?
What was once a smooth loading screen, is now a frozen screen. From my main menu, it usually skips the loading screen and dives into the gameplay (which isn't too bad) but the real issue, is if you're in the help menu and chose 'Play' from there.

It'll load into the loading screen, then freeze.

From the inspector under the slider, it shows:

Now, I have the loading Screen Manager and it's script set up, so I'm not sure why it's doing this. What I would like to do is to get it working again, whether I stick to sceneBuildIndex or go by sceneName but the problem here, when I try either one, it doesn't seem to have any real changes at all.

Here is a copy of the full script from a tutorial I followed when I was just starting out:

```
// LoadingScreenManager
// --------------------------------
// built by Martin Nerurkar (http://www.martin.nerurkar.de)
// for Nowhere Prophet (http://www.noprophet.com)
//
// Licensed under GNU General Public License v3.0
// http://www.gnu.org/licenses/gpl-3.0.txt

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public class LoadingScreenManager : MonoBehaviour
{

    [Header("Loading Visuals")]
    public Image loadingIcon;
    public Image loadingDoneIcon;
    public Text loadingText;
    public Image progressBar;
    public Image fadeOverlay;

    [Header("Timing Settings")]
    public float waitOnLoadEnd = 0.25f;
    public float fadeDuration = 0.25f;

    [Header("Loading Settings")]
    public LoadSceneMode loadSceneMode = LoadSceneMode.Single;
    public ThreadPriority loadThreadPriority;

    [Header("Other")]
    // If loading additive, link to the cameras audio listener, to avoid multiple active audio listeners
    public AudioListener audioListener;

    AsyncOperation operation;
    Scene currentScene;

    public static int sceneToLoad = -1;

    // IMPORTANT! This is the build index of your loading scene. You need to change this to match your actual scene index
    private static int loadingSceneIndex = 4;

    public static void LoadScene(int levelNum)
    {
        Application.backgroundLoadingPriority = ThreadPriority.High;
        sceneToLoad = levelNum;
        SceneManager.LoadScene(loadingSceneIndex);
    }

    void Start()
    {
        if (sceneToLoad < 0)
            return;

        fadeOverlay.gameObject.SetActive(true); // Making sure it's on so that we can crossfade Alpha
        currentScene = SceneManager.GetActiveScene();
        StartCoroutine(LoadAsync(sceneToLoad));
    }

    private IEnumerator LoadAsync(int levelNum)
    {
        ShowLoadingVisuals();

        yield return null;

        FadeIn();
        StartOperation(levelNum);

        float lastProgress = 0f;

        // operation does not auto-activate scene, so it's stuck at 0.9
        while (DoneLoading() == false)
        {
            yield return null;

            if (Mathf.Approximately(operation.progress, lastProgress) == false)
            {
                progressBar.fillAmount = operation.progress;
                lastProgress = operation.progress;
            }
        }

        if (loadSceneMode == LoadSceneMode.Additive)
            audioListener.enabled = false;

        ShowCompletionVisuals();

        yield return new WaitForSeconds(waitOnLoadEnd);

        FadeOut();

        yield return new WaitForSeconds(fadeDuration);

        if (loadSceneMode == LoadSceneMode.Additive)
            SceneManager.UnloadScene(currentScene.name);
        else
            operation.allowSceneActivation = true;
    }

    private void StartOperation(int levelNum)
    {
        Application.backgroundLoadingPriority = loadThreadPriority;
        operation = SceneManager.LoadSceneAsync(levelNum, loadSceneMode);

        if (loadSceneMode == LoadSceneMode.Single)
            operation.allowSceneActivation = false;
    }

    private bool DoneLoading()
    {
        return (loadSceneMode == LoadSceneMode.Additive && operation.isDone) || (loadSceneMode == LoadSceneMode.Single && operation.progress >= 0.9f);
    }

    void FadeIn()
    {
        fadeOverlay.CrossFadeAlpha(0, fadeDuration, true);
    }

    void FadeOut()
    {
        fadeOverlay.CrossFadeAlpha(1, fadeDuration, true);
    }

    void ShowLoadingVisuals()
    {
        loadingIcon.gameObject.SetActive(true);
        loadingDoneIcon.gameObject.SetActive(false);

        progressBar.fillAmount = 0f;
        loadingText.text = "LOADING...";
    }

    void ShowCompletionVisuals()
    {
        loadingIcon.gameObject.SetActive(false);
        loadingDoneIcon.gameObject.SetActive(true);

        progressBar.fillAmount = 1f;
        loadingText.text = "LOADING DONE";
    }

}

```

I'm reading the manual here, but I'm not sure if I'm misunderstanding it, or if there's an error in the script:

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html

# Answer
> 1 votes
There’s a lot going on in your question here, but if I’m understanding correctly, the problem you want solved is just that the On Value Changes event can’t find the LoadScene method on LoadingScreenManager.

If that’s the case, my guess is that the problem is that the method is static. Try changing

```
public static void LoadScene

```

To this

```
public void LoadScene

```

And see if it can find it now.

---
Tags: unity, windows, scene
---


title: Generating lakes and rivers on 2D grid

text:
# Question
Title: Generating lakes and rivers on 2D grid
I recently posted a question about how to technically represent a generated terrain similar to the game kingdoms and castles.

I got some great advice and decided to create a 1x1 cube at each coordinate since I will have very small maps, for now 50x50.

I wrote some code to generate terrain, this is super basic atm and simply instantiates either grass or water tiles depending on the noise value at the coordinate:

```
public static class Noise
{

    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, float scale)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];

        if (scale <= 0)
            scale = .0001f;

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float sampleX = x / scale;
                float sampleY = y / scale;

                float perlinValue = Mathf.PerlinNoise(sampleX, sampleY);
                noiseMap[x, y] = perlinValue;
            }
        }

        return noiseMap;
    }
}

public class MapGenerator : MonoBehaviour
{
    public int mapWidth;
    public int mapHeight;
    public float noiseScale;

    [Space]
    public GameObject grassTile, waterTile;

    public void GenerateMap()
    {
        float[,] noiseMap = Noise.GenerateNoiseMap(mapWidth, mapHeight, noiseScale);

        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                if (noiseMap[x,y] >= .3)
                    Instantiate(grassTile, new Vector3(x, 0, y), Quaternion.identity);
                else
                    Instantiate(waterTile, new Vector3(x, -1, y), Quaternion.identity);
            }
        }
    }
}

```

It generate something like this:

Now this obviously does not look like a realistic landscape. My question is, how do I decide which values should represent water, and which should represent grass, in order to get a landscape that makes sense?

What I would like my landmass to look like something that has lakes and maybe rivers, instead of these random puddles you see in the image above, more something like this:

EDIT:

Setting a higher scale value lead to this:

# Answer
Searching for river generation on this same site turns up quite \[a few good results\], notably this answer has some good methods listed

Perlin noise is a good choice for terrain which is a continuous space, but for more discrete shapes like a river you may be better served by a different generation technique like a random walker. You could give the random walker some rules to get a more river-like 2D shape, then overlay that onto your map.

Alternatively since you have already generated some noise based terrain, you could modify the noise slightly so you get more low valleys and then add water to any area below a certain Y value, so the low points would all become rivers/lakes.

Terrain generation has many different possible approaches so experiment a bit and see which method is good for you. For more ideas check out this very thorough Unity terrain generation playlist from Sebastian Lague. He also has a video on hydraulic erosion to create even more natural and less noise-like terrain, but this is likely beyond what you are looking for.
> 1 votes

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


# Question
Title: How to differentiate landing on top of an object from falling down the side?
I am looking for a conceptual solution to my problem. It's a simple platformer-alike game where player can move horizontally during free-fall.

Consider those two cases:

In the first case, from game experience point of view, the player should land on top of the box; and in the other case he hit the left edge, hence the player should fall down.

However, from my code point of view ("real behaviour"), both those collision detection cases are identical. I am not sure how to separate them.

In both cases the vertical velocity is positive (falling down) and the user is moving with some fixed positive horizontal velocity. (moving right)

From a collision-standpoint the two cases are identical, I think. How can I tell whether I should put the player on top of it or let him fall?

# Answer
There are three common ways games sort this out:

1. **Minimum Separation Vector**

Upon a collision, compute the shortest movement that pushes the bodies apart into a non-intersecting position.

If I've crept just 0.1 units into the platform's left side, but my feet are 0.2 units below its top surface, then the shortest movement to resolve the penetration is to shift me 0.1 units directly left.

If the penetration from each face is the same, you can pick one arbitrarily.
2. **Rewind to Moment of First Intersection**

Knowing the penetration depth of the object and its incident velocity, you can compute the moment in its travel this frame that it first contacted the obstacle, and back-track it along its velocity to the moment of contact. This will generally be a diagonal movement, rather than favouring the horizontal or vertical axis exclusively.

That rewound position will sit either wholly to the left, or wholly above, or exactly corner-to-corner in the most extreme case.
3. **"Love the Player"**

For the particular case of the player controller, we might want to use player experience rather than geometry to guide us.

As you say, these two situations look almost identical to the player - if in one case they fall and one they land, based on tiny fractional differences in the numbers, then the mechanic is liable to appear inconsistent, capricious, and frustrating to the player.

Instead, we can choose to make a charitable assumption that honours what the player was *trying* to do: as long as they haven't sunk *too* far below the top of the platform (maybe use their falling speed times half a frame as a threshold), correct them to the top of the platform as though they landed on it, even if a perfectly continuous simulation would have said otherwise.

This will only fudge the player's position by a half a frame's movement, tops, so it generally won't be very noticeable if you choose a suitable threshold, and a landing sprite/animation/dust cloud/sound effect can help sell the landing and mask the fudge factor.

If you want to increase this tolerance range further, you can add a ledge grab state to trigger on near-misses like this and save the player from a fall when they were "close enough" for your game's target experience, even if raw physics disagrees.
> 48 votes

---
Tags: collision-detection, physics, platformer, jumping
---


# Question
Title: Why can't I directly change the position of a prefab using transform.position? (Unity3D)
I am relatively new to Unity, and I am currently working on some code. I am trying to change the position of Unity's standard assets first-person controller using

```
player.position = anotherObject.position + offset;

```

I'd like to add that I am setting the player's position when it collides with a box collider.

However, this isn't working for some reason. I've tried debugging it using print statements before and after the teleportation of the player, and this is what I see:

```
Player position: (0, 2, 0)
Player position after teleport: (32, 2, 0)
Player position one frame later: (0, 2, 0)

```

After one frame, the player returns to it's original position, as if it was never moved.

Here is my code, if it will help you better understand my problem.

```
public class PortalTeleporter : MonoBehaviour {

    public Transform player; // The player
    public Transform receiver; // Receiving portal

    private bool playerOverlap = false; // boolean to store whether player touches the box collider on portal

    void Update(){
        if(playerOverlap){
            Vector3 portalToPlayer = player.position - transform.position;
            float dotProduct = Vector3.Dot(transform.up, portalToPlayer);
            if(dotProduct < 0f){
                float rotationDifference = Quaternion.Angle(transform.rotation, receiver.rotation);
                rotationDifference += 180;
                player.Rotate(Vector3.up, rotationDifference);

                Vector3 positionOffset = Quaternion.Euler(0f, rotationDifference, 0f) * portalToPlayer; // Offset between player and portal
                Vector3 pos = receiver.position + positionOffset;
                print(player.position);
                player.position = pos;
                print(player.position);
            }
        }
    }

    // Triggered when player enters the portal
    void OnTriggerEnter(Collider other){
        if(other.tag == "Player"){
            playerOverlap = true;
        }
    }

    // Triggers when player untouches the portal
    void OnTriggerExit(Collider other) {
        if(other.tag == "Player"){
            playerOverlap = false;
        }
    }

```

Thank you for taking the time to answer my question!

# Answer
So if any of you currently land on this thread in the future and is wondering why your FPController isn't teleporting, I solved this issue by updating my FPController to the latest one on the unity asset store (Not the 2017 one). Hope this helps any of you who had the same problem as I did!
> 1 votes

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


# Question
Title: Balance advantage of having the first turn
I'm developing a game in which two players compete for area domination. Each player can play four moves per turn, ideally conquering four tiles.
**Edit:** Here a little more detail on the mechanics: Each player is given the same amount of cards (about 20). Each card has a value. The board consists of 4x5 tiles which you conquer by placing a card on it. If there already is a card on the tile, your can still conquer the tile but your card must have a higher value than the card on the tile.

The problem is that player two could *technically* (almost) always just undo player ones moves by conquering the same areas immediately. Of course this isn't fun at all and no human player would play this way, but I'm working on implementing an AI opponent, and I've seen the above happen a few times:

* Player one conquers four tiles with pretty low value cards
* player two immediately takes them
* player one takes them back again because not doing so would be a disadvantage
* player two takes them back again etc...

So as you can see, this is definitely not the best strategy as it becomes ridiculously expensive to possess the tiles of interest, but there are strategies or situations in which you might play like this.

How should I balance this? Are there any common design solutions for this problem?

(Having player one play more moves in the first turn would give player one a **huge** advantage as it would allow him/her to conquer highly strategic areas in the first turn. (Unfortunately, the "immediately undo player ones moves" strategy is actually not mathematically bad for player two, but that's another issue))

# Answer
> 2 votes
How to balance the advantage of playing first or second is hard to address in general.

It would largely come down to looking at the mechanics of your game, considering possible ways to benefit a player and doing play-testing to determine which player gets an advantage and how you could potentially get rid of that advantage. Also potentially consider what your game mechanics should look like in general when taking this into account. This may involve tweaking some mechanics to make them stronger or weaker, adding new mechanics or altogether scrapping or redesigning large parts of the game.

Simply playing first is usually a pretty big advantage (especially in a symmetric game), so the second player is often given an advantage, but of course this would depend on the game.

Let's consider the example where the second player can just repeatedly retake any area taken by the first player to win. A few ways to deal with this:

* Simply give the first player more starting moves to offset their disadvantage. Although this may instead allow the first player to simply follow this strategy to win, which isn't any better (except for the first player...).
* Make retaking an area worse or give a bigger benefit to taking an area not occupied by another player.
* Rethink how retaking works. Perhaps you need to have taken adjacent areas first, or it's something that only gets unlocked later in the game or you can do things to make it easier. If there are RPG elements, you could do this by allowing players to "research" weapons, build or upgrade a barracks or train soldiers.
* If all else fails, conclude that the fundamental concept you had in mind for the game just isn't viable because of this, no amount of small tweaking would make it fun and you need go back to the drawing board or even scrap the game altogether.

## "Undoing" a move should not *truly* undo it

If you're able to do a move that completely undoes the move of the other player and resets the game state back to where it was before they moved, this, to me, points to a rather fundamental problem with the underlying design of the game. (It would be worse if your move makes as if theirs never happened but leaves you with some resources on the board, at least if you can do this from the beginning of the game)

Any move made (including undoing) should move the game forward in some way.

In practical terms, this means **an "undo" is more of a strategic counter** that allocates your resources in some way or to the same place in order to hinder your opponent's attempt to gain an advantage there.

Go is the best example I can think of right now. Every move involves placing a stone in turn, so each one progresses the game (well, there are ways to take stones too, but not from the beginning). The second player can choose to place a stone near the stone placed by the first place in order to defend or attack there, or they can place a stone further away to try to gain an advantage on another part of the board.

Chess is also an example. Many moves can be thought of as counters to other moves: from a move as simple as advancing a pawn to block another pawn to defending an piece being attacked. Moves typically move the game forward by opening up the board, moving pawns, which can only go in one direction, or removing pieces from the board and it's a strategic decision whether to try to counter something or to try to gain an advantage somewhere else.

On the subject of chess, it is possible to get back to the same board position repeatedly with some moves, which is why there's a rule stating if a position repeats 3 times it is (or can be) a draw. Go has a similar rule. This is, however, largely an artificial constraint: it's not really a fundamental part of the game and doesn't add anything beyond simply being there to prevent infinite repetition. I would recommend trying to change your mechanics in some other way instead to avoid repetition if possible.

## Undoing a move might be expensive or rare

You could also have *true* undo's, but these are expensive or rare.

A few ways to accomplish this:

* It just costs 2 or more movement points (or whatever resource used for making moves) from your side to undo their move.
* To consider area domination as an example: they take some territory and you might need multiple units to take that territory from them (losing some of those units in the process).
* It costs some other type of resource to take an area from the other player.
* It takes some time to take the territory and in the mean time it's generating resources for the other player (meaning focusing on that too early instead of on gaining resources puts you at a disadvantage).
* A (recently) retaken area produces fewer resources than an area that wasn't occupied before.
* Give players a limited number of undo's (either from the start of the game or by finding some item during that game).
* Similar to the above, attach some cooldown to undoing, so it can only be performed a certain number of times over some time period.

# Answer
> 0 votes
Assuming all tiles are worth the same, conquering an enemy tile is always better than conquering an empty one. Both actions give you a tile, but capturing the enemy also causes them to lose a tile in addition to that. So why would a player ever *not* conquer enemy tiles if they can?

Possible solutions:

* Make attacking more costly. The only two resources you have right now are moves and cards. So what are your options here?
    + One option would be to add a cost in form of discarding another card from one's hand.
    + Another option would be to make attacking cost two moves. This would make the point-per-move turnout of taking empty vs. occupied territory equal again. Player 1 conquers 4 territories, player 2 takes 2 of them, and the score is 2:2 as it should be.
    + Or you could introduce another resource which is used for attacking.
* Make attacking less rewarding. For example, an attack could destroy the enemy card on the tile, but then leaves the tile unoccupied. So the player who wants that tile needs to expend another move to conquer it. If player 2 undos all the moves of player 1, then the game is back at the initial state.
* Make attacking more risky. Instead of higher cards always beating lower cards, introduce an element of chance. A higher ranked card might have a good chance to win against a lower ranking card, but there is still a chance that it fails. In case of a failure, the attacking player might be punished by losing their move, losing their card or both. This turns attacking into a risk/reward mechanic.

---
Tags: game-design, ai, turn-based, turn-based-strategy
---


title: How to use open dota api?

text:
# Question
Title: How to use open dota api?
OpenDota, A community driven platform for DotA 2 matches and players data is the best open-access API in gaming scene. I found no casual tutorial for using its API, So, I decided to make a one. Your feedback is welcome for inquiries or further improvements

Sincerely,

# Answer
> 2 votes
Probably, You came along OpenDota's documention but did not know where to go from there.

As python is popular among data scientists, We shall use it in our tutorial. Python's standard library comes with URL handling module but for convenience I am going to use requests. If *requests* module is not already installed, obtain it via `pip install requests`. See the official installation guide for more details.

start by importing *requests* module by `import requests`

get a webpage from OpenDota's API. Its form is `https://api.opendota.com/api/{entry1}/../{entry n}`. For example, GET /players/{account\_id}/matches is implemented as `r = requests.get("https://api.opendota.com/api/players/107828036/matches")`

Then, you could access the desired content by `r.text`. `print(t.text)` returns raw string. However, processing raw text is tedious and it would be more accessible if data where formed as dictionary. *requests* module comes with JSON parser out of the box by `r.json()`. Usually, r.json() is list, and r.json()\[0\] is the first element of the list which is a dictionary. You could `print(r.json())` for manual check.

Finally, you might wish the write the modified data. Python's standard library comes with JSON writer out of the box. By the way, We could have parsed r.text to a dictionary using it instead of *requests* `r.json()`. Anyway, `import json`. Then

```
with open('<file-name>', 'w') as out:
                json.dump(<dictionary-object>, out, sort_keys=True, indent='\t')

```

where `<dictionary-object>` is `r.json()` in our case. both of `sort_keys=True` and `indent='\t'` beautify the writing by introducing tabs and newlines

Here is a sample code:

```
import requests
import json

r = requests.get("https://api.opendota.com/api/players/107828036/matches")

with open('output.json', 'w') as out:
                json.dump(r.json(), out, sort_keys=True, indent='\t')

```

---
Tags: data, analytics
---


# Question
Title: Loading the map from an image file in C++
For my platformer tile-based game I want to be able to load the game map from an image file.

Consider the following 25x15 px .png *(enlarged)* representing some level:

Assume that each specified color represents different game object. The actual hex values are irrelevant.

Given some input image, my map loading routine should be able to:

* access the image's size in pixels
* read specific \[i, j\]-th pixel's hex value

Is there some general rule which image format should I use? .png, .bmp, .jpg or something else?

# Answer
> 2 votes
If you want to keep things simple, I would pick a format and stick to it.

The two most simplest image formats that I know of are:

* PPM
* BMP
* TGA

It's not that difficult to implement loading of any of these files. I see PPM files used a lot in ray tracing examples because the file format is so easy to handle. If you're the one generating these images, I'd highly recommend PPM to start out with. BMP would be a good alternative, if you won't want to go with PPM.

In terms of libraries, libpng is a popular choice. IMHO, it's interface is terrible and difficult to learn. If you can get over the learning curve though, it's a useful library.

stb\_image.h is another popular choice it seems like. I've never used it, but it's easy to integrate and seems very cross-platform-ish. I can't speak to whether or not it's easy to learn, but it seems like another good choice. It's a single header file that you just put into your project and include it in the files that load image data.

---
Tags: c++, tilemap, maps, image, color
---


title: SIMD and Inverse Tangent

text:
# Question
Title: SIMD and Inverse Tangent
I'm calculating spherical UV coordinates in a loop, trying to get GCC to vectorize the code.

Here's a compile-able example of what it looks like.

```
#include <cmath>
#include <cstddef>

/// Calculates UV coordinates from positions on a sphere.
/// The sphere has a radius of one.
//
/// @param pos_array The 3D sphere positions to get the UV coordinates of.
/// The positions are in the format: x, y, z, w (where w is unused)
//
/// @param uv_array This is where the UV coordinates go.
/// A series of 2D vectors (no padding)
void calc_uv_coordinates(const float* pos_array, float* uv_array) noexcept {

  constexpr std::size_t chunk_size = 256;

  for (std::size_t i = 0; i < chunk_size; i++) {

    const float* pos = pos_array + (i * 4);

    float* uv = uv_array + (i * 2);

    uv[0] = 0.5 + (std::atan2(pos[2], pos[0]) / (2 * M_PI));
    uv[1] = 0.5 - (std::asin(pos[1]) / M_PI);
  }
}

```

But the inverse trig functions are keeping it from being vectorized, as per GCC's report:

```
gcc -c -O3 -fopt-info-vec-missed test.cc

```

Prints:

```
test.cc:16:29: missed: couldn't vectorize loop
/usr/include/c++/9/cmath:145:28: missed: statement clobbers memory: _25 = __builtin_atan2f (_4, _3);
/usr/include/c++/9/cmath:145:28: missed: statement clobbers memory: _25 = __builtin_atan2f (_4, _3);
/usr/include/c++/9/cmath:107:27: missed: statement clobbers memory: _24 = __builtin_asinf (_9);

```

~~Which is understandable, I don't think there's any hardware implementations of those functions~~.

**Edit:** There is for Intel.

In game development, how is this kind of issue dealt with? I could think of two approaches:

* Write a vectorized `atan2` and `asin` that compute many inverse trig values at once
* Write a SIMD-friendly approximation for each function

A quick google search led me here, where I found an atan approximation.

```
inline constexpr float fast_atan_approx2(float x) noexcept {
  return x / (1 + (0.28 * x * x));
}

inline constexpr float fast_atan_approx2(float x) noexcept {
  return (0.9724 * x) - (0.1919 * x * x * x);
}

```

And from the comments, another approximation.

But looking at the graphs, I don't think they're going to be suitable for texture mapping. Here's a picture, where:

* blue is true arctan
* orange is the first approximation
* red is the second approximation

The approximations are only decent in the domain \[-1, 1\]. So just to restate my question, how is this dealt with? Is there a way to vectorize these trig functions? Do people generally just accept the bottleneck?

# Answer
First, you comment that your position values are in \[-1,1\] range, so that approximation would be just fine, no? Also, that approximation functions you show are for atan(x) and not for atan2(y,x). See here for atan2(y,x) approximations.

Second, you could nudge the compiler even more towards SIMD by supplying your input as structure-of-arrays.

```
void calc_uv_coordinates
(
  const float* __restrict__ posx,
  const float* __restrict__ posy,
  const float* __restrict__ posz
  float* __restrict__ u,
  float* __restrict__ v
) noexcept
{
  for (int i = 0; i < 256; i++)
     u[i] = 0.5f + fast_atan2( posz[i], posx[i] ) / ( 2 * M_PI );

  for (int i = 0; i < 256; ++i )
     v[i] = 0.5f - fast_asin2( posy[i] ) / M_PI;
}

```

Note the use of `__restrict__` to tell the compiler there is no overlap between the arrays.

And if the compiler still fails to vectorize, there are always intrinsics if you don't mind hardcoding for the CPU architecture.

Oh, and it also helps to make sure your arrays are aligned on 256 bits, if you can. I use `__attribute__ ((aligned(32)))` for this, or if the memory is dynamic: `posix_memalign()`
> 0 votes

---
Tags: c++, uv-mapping, trigonometry, simd
---


# Question
Title: How to manage game-object script component and values in new updated model in unity
I have several objects/**Models/FBX** that contain different childrens and it attached several `mono-behavior` scripts with different values assigned publicly in the inspector (settings). SO of the assignments are manually drag-and-drop in the inspector.

Now the problem is each time we update the model in the project (FBX in the project) we have to drag and drop the model/FBX **again in the hirarchy**. It means that we have to attach all the scripts again with the values/Data (that we assigned in the inspector) again.

I am currently looking for the right way to do this job. Currently, I place both new and old **Models** in the scene and then one by one I copy-paste the old object's script component into the new objects by viewing every child of an object. Then, I delete the old one model from the hirarchy. It is a very time consuming process. I want to automate it. Just like Unity I should save all the information (Components and assignment) of a game-object in a separate file (meta file custom) and bring them again on button click. But its challenging as i dont know how to save assignments (refrence objects).

Note: *I have to bring the fbx again in hierarchy because sometimes the object not properly update in the scene. Like mesh gets rotate or scaled in weird manner. Or sometime FBX childs are removed or add.*

# Answer
> 1 votes
When creating 3D model you have to take care about naming convention which is very important. Object hierarchy should have proper name and position. In your case there is a 3D model of Train and it has two doors and four windows:

> M\_Train (M = Model/Mesh, Train = name /reference)
>
> * R\_Front\_Door (R = Right)
> * L\_Back\_Door (L = Left)
> * R\_Front\_Window
> * L\_Front\_Window
> * R\_Back\_Window
> * L\_Back\_Window

It is really upto you how you want to name your gameobjects.

Other thing is use only one script and attach it to the parent gameobject. Then attach child objects by finding their names in the parent object to appropriate variable in the script. You can use `GameObject.Find` to find object.

If your 3D modeling tool scale is according to Unity's then it won't scale or rotate or transform. It will always be same as in your 3D modeling tool. See this useful link of how to import from 3D modeling tool.

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


title: LibGDX - Draw rectangular shapes

text:
# Question
Title: LibGDX - Draw rectangular shapes
I'm making a 2d game in which units occupy a dynamic area of the map.

This area will be a rectangular shape like in the following picture. The exact shape will change during gameplay.

How should I draw these shapes?

Should I use a mesh for this? If so, how would I find the vertices of the shapes?

Can I somehow use a "mask" for this? Render a filled rectangular and then subtract those parts which are outside of the shape maybe?

Optional questions: How would I draw a stroke / outline around the whole outer edge of the shape?

# Answer
> 2 votes
I'm not sure, if I understand exactly what you are searching for but it would make your life a lot easier if you would use a grid of squares for the map. You could highlight different regions by simply changing the color of each grid peace that belongs to the area.

Regarding the outline: If you are using just one shape you should look into using Shaders for this. You could star here.

# Answer
> 1 votes
I'm not familiar with libgdx so the exact implementation in it is not something i could provide you. However, the concepts in play are pretty universal.

Assuming several things.

* You only want to fill in the red area as that is how your question sort of reads.
* You have the vertexes of the polygon you're looking to draw.
* LibGDX cannot draw a concave polygon natively.
* The polyons you're looking to draw have axially aligned points (more on that below)

You're looking for a function that can draw a concave polygon. Without that we will have to break the polygon into convex shapes.

An example would look like this with the shape you provided being divided into 5 polygons, Ill go over one but the idea can be carried over for each.

A1 and A3 are the lowest points on the x axis(closest to 0, or they're the most negative)

A2 is aligned with A1 on the x axis.

A4 is aligned with A3 on the x axis.

A2 and A4 are the closest points that are axially aligned to A1 and A3.

Using this logic we've created a simple polygon any graphics library should be able to draw.

Repeat this logic for each cardinal direction, then use the inner most points (A2 and A4) to draw the inside polygon. A simple check to find which points are not on the outside should solve that for you

A1.x \< A2.x \< some further point

Hopefully this quick answer helps in some way!

# Answer
> 1 votes
As long as your shapes (edges of them) are actually AxisAligned the simplest way to draw it is to just draw multiple rectangles. They can overlay each other if they are the same color anyway. This can be as easy as drawing a 1x1 white texture with the desired Rectangle (Position,Size) and the required color. Your provided image would therefore consists of 4 rectangles overlapping each other.

To make an outline, you are basically doing the same but scaling the rectangles slightly in the outline color and after that just draw the actual rectangles over it. This will result in an outline over the whole construct

( I actually assume, that your desired shapes is logically made out of several rectangles anyway, if not and you only have the cornerpoints as in an single shape, other answers go in great detail about how to split them into single rectangles)

---
Tags: libgdx
---


# Question
Title: How to prevent players from using save/load tactics in Roguelike games?
Players can achieve the expected results through continuous saving and loading in rogue-like games.

I am try to reduce this method as much as possible, but don't want to keep players from trial and error at all, which makes the game more difficult.

Anybody could give me some advice in this respect?

# Answer
> 5 votes
Traditional roguelikes solve the save-scumming problem by making the saving system completely automatic. The game auto-saves the player's progress whenever feasible. Especially after something went wrong (including a game over, which deletes the savegame). But the player can not create manual savegames. That means the player can quit the game whenever they want in order to progress it at a later time, but they can not restore it to an older state when they make a mistake.

This system has the advantage that you encourage the player to think carefully about their actions and experience a greater variety of gameplay situations by forcing them to accept setbacks. If done well, this can greatly increase the player's emotional investment in the gameplay.

But on the other hand, it can also be very frustrating for the player to lose a lot of progress due to a stupid mistake.

One way to avoid frustration is to make sure that starting over again doesn't feel too bad:

* Have great replay value, especially in the early game. (most roguelike achieve that with a combination of procedural level generation and a large variety of character options)
* Make sure the player feels like the game is fair. Design your procedural generation in a way that it doesn't create difficulty spikes and avoid random number rolls or hidden information which can instantly kill the player.
* Death should not feel like a complete loss. A common method is to have a progression system where achievements from one run affect subsequent runs.

Another strategy can be to avoid frustration by avoiding player setback altogether:

* Design your game in a way that the player can't die or put the game in an unwinnable state.
* Design your game so the player can easily recover from any setbacks in the game.

**Regarding trial-and-error gameplay**: You *can* have that in a roguelike, but you need to be careful with it to keep it fair. First of all, make sure that the punishment for errors is very light compared to the possible reward. Punishing the player for a mistake when they can not know what's the right thing to do can be very frustrating. Then make sure that it is possible for the player to learn something useful from experimentation. For example, let's say you have different colored potions in your game and the player is supposed to find out which color does what through experimentation. Either make sure there are lots of identical potions in each run or make the colors mean the same thing in every run. That way players have the opportunity to make use of the knowledge they acquired.

# Answer
> 2 votes
To prevent players abusing saveing/loading before progressing, there are a few things you can do on your end. Which one you pick, depends on the game.

* Make saving expensive. Allow the players to save, but only if they have an item. This will make them think twice before saving. Example of a game doing this technique is Resident Evil 2 (2019).
* Limit the functionality of saving. You can for example allow the user to save only when exiting the game, and when they resume the save is "destroyed" or otherwise inaccessible. One example of a game doing this is Ziggurat

Keep in mind that if this for a platform where users have access to the game's files (like a computer) then no matter what you do, there will be a way for a user to "copy-paste" save files. In which case you can't really entirely prevent users from abusing that, but you can only make it harder.

---
Tags: game-design, roguelikes
---


# Question
Title: What Situations is Saving a Game to Main Memory for?
---

I've been reading through Unreal's 'Saving and Loading' guide: Link

Within, they present a capability to save a game to main memory rather than secondary storage:

---

I haven't found any information on where this would ever be used.

The only situation I can fathom for this being useful is to keep data about other load zones in memory so that travelling through load screens into these zones is quicker.

---

Why, When and Where is this technique of saving to Main Memory used instead of saving to Secondary Storage?

# Answer
Sometimes you might want to store your savegame data somewhere else than on the users hard drive. You might offer a cloud save service, for example. In that case you would use `SaveDataToMemory` to create a savegame in a memory buffer and then send that memory buffer to a server via network.

Another possible use-case could be to always keep the last savegame in memory so you can restore it faster in case the player quickloads or dies. Using `LoadGameFromMemory` when you already got the savegame in memory can be much faster than loading the game from the hard drive.
> 15 votes

---
Tags: c++, architecture, unreal-4, savegame
---