# Question
Title: Messy results from simple cellular automata algorithm?
I wrote something that will first randomly populate a square a with grass tiles, and then from there it will calculate tile types from each tile's surrounding tiles. My ultimate goal is generate a terrain that somewhat resembles an island.

My first step:

Then I use cellular automata / box filtering to smooth out the terrain (thanks Arcane Engineer):

where results are far from smooth, at least according to some examples I've seen online.

Here's the code:

```
private void SetupTiles()
{
    //get reference positions
    int centerRow = chunk.size / 2;
    int centerCol = chunk.size / 2;

    // Loop through the chunk and add tiles
    for(int row = 0; row < chunk.size; row ++)
    {
        for(int col = 0; col < chunk.size; col ++)
        {
            //Water - 0
            //Grass - 1

            //Create TILE
            //default tile is water
            Tile tile = new Tile(col, row, chunk.tileSize, tileType.Water, GetRandomWaterTexture());
            //since the island is smaller than chunk,
            //check if current index is within island size.
            if(row >= border && row < (chunkSize-border) && col >= border && col < (chunkSize-border))
            {
                //Randomly assign tiles type
                //TODO: This random system is not very good...
                if(MathUtils.random(100)>50)
                {
                    tile.texture = GetRandomGrassTexture();
                    tile.type = tileType.Grass;
                }
            }

            //add tile to chunk.
            chunk.tiles[row][col] = tile;
        }
    }

    //Initialize smoothedChunk with water
    //At this point, chunk is randomly filled with grass, and smoothedChunk is just water.
    for(int i = 0; i < chunkSize; i++)
    {
        for(int j = 0; j < chunkSize; j++)
        {
            Tile tile = new Tile(i, j, 8, tileType.Water, GetRandomWaterTexture());
            smoothedChunk.tiles[i][j] = tile;
        }
    }

    //TODO: Smoothed island is not really smooth...
    //Smooth out chunk
    SmoothMap();
    //Set centre tile for camera positioning
    centreTile = chunk.GetTile(centerRow, centerCol);
}

private void SmoothMap ()
{
    //first loop, get surrounding tiles for each tile in chunk
    //we are excluding the outer most edge
    for(int r = 1; r < chunkSize-1; r++)
    {
        for(int c = 1; c < chunkSize-1; c++)
        {
            //if current tile is not null
            if(chunk.tiles[r][c] != null)
            {
                //Get its surrounding tiles.
                //At this point, smoothedChunk is still empty.
                chunk.tiles[r][c].surroundingTiles = GetSurroundingTiles(r, c, chunk);
                //Debug info
                //System.out.println("Position: " + chunk.tiles[r][c].row + ", " + chunk.tiles[r][c].col);
                //System.out.println("Current tile type: " + chunk.GetTileCode(r, c));
                //System.out.println("Neighboring tiles: " + chunk.tiles[r][c].surroundingTiles);
                //System.out.println();
            }
        }
    }

    //second loop, smooth tiles according to their surrounding tiles
    for(int r = 1; r < chunkSize-1; r++)
    {
        for(int c = 1; c < chunkSize-1; c++)
        {
            //Write into smoothedChunk
            //can the threshold be a variable?
            if (chunk.tiles[r][c].surroundingTiles >= 4)
            {
                smoothedChunk.tiles[r][c].texture = GetRandomWaterTexture();
                smoothedChunk.tiles[r][c].type = tileType.Water;
            }
            else if (chunk.tiles[r][c].surroundingTiles < 4)
            {
                smoothedChunk.tiles[r][c].texture = GetRandomGrassTexture();
                smoothedChunk.tiles[r][c].type = tileType.Grass;
            }
        }
    }

    //copy tiles over from smoothedChunk to chunk,
    //because we still want to use chunk for everything.
    for(int i = 0; i < chunkSize; i++)
    {
        for(int j = 0; j < chunkSize; j++)
        {
            chunk.tiles[i][j] = smoothedChunk.tiles[i][j];
        }
    }
    //don't know the difference between the loop above and
    //chunk = smoothedChunk;
}

```

Does anybody have any idea why my results are so... unsatisfactory?

If I could achieve something like this I would be really happy (excluding the color variation):

# Answer
> 3 votes
You require more effective smoothing methods. Google "cave generation" and you will find many. Also if you haven't already begun, some research on cellular automata will be beneficial.

This issue boils down to the way in which you treat each cell in your `SmoothMap` algorithm. At the moment all you do is count neighbours around the current cell, provided the current cell is itself already land, and act accordingly. This is a *naive* generation algorithm, and not the most intelligent way of adjusting the map because all you are doing is evaluating *count* and not *structure*.

**Counting neighbours (Quantitative analysis)**

You can get a bit further with neighbour-counting alone, than you are at present: Consider even cells that are currently water (unlike at the moment where you only consider land cells for neighbour-comparison). If it has a certain number of neighbours that are land, then fill this central cell with land as well. This in itself gives much more smoothing: it fills up tiny ponds with land.

If you can make what you want with just neighbour-counting, I suggest you do so, as it is a lot simpler than what follows below, BUT structural analysis (below) can provide much more control.

**Expansion / dilation and contraction / constriction**

You can see this in my other answer which I posted in the comments. It is perhaps not the most efficient way, but it is one alternative to smoothing and creating more rounded forms. It works, and is relatively simple. But there is a considerable loss of fine details, maybe more than you want.

**Structural evaluation of neighbours (Qualitative analysis)**

As I said in my previous answer to you, if you want to smooth and keep joins between islands etc. more effectively, you need to re-examine *how* you work with neighbours.

What you need now is a function that can go around in a circle (say clockwise from north) and examine each *group* of adjacently-populated neighbours. For example:

```
* * *
0 X *
* * 0

```

Here you can see that there is a group of 4 adjacent neighbours toward the northeast side, and 2 toward the southwest. Your algorithm might produce something like

```
0 * *
0 X 0
0 0 0

```

You can see that what we've done here is to *erode* by taking the "ends" off each segment - we took both ends (1 & 1) off the strip of length 2 at the southwest, leaving just water. We took both ends off the strip of length 4 at the northeast (1 & 1) leaving just 2.

Another way might be to say anything 2 or bigger always survives, so

```
0 * 0
0 X *
* 0 *

```

would become just

```
0 0 0
0 X *
0 0 *

```

Also, you'll notice I've been putting an X at the current position (to say we don't care what's there) but what if that becomes important to the adjacency in the previous example? Now this

```
0 * 0
0 * *
* 0 *

```

actually becomes

```
0 * 0
0 * *
0 0 *

```

instead, preserving a sort of land-bridge, as compared with the previous example which does not.

To allow you to find groups of adjacent neighbours, in order, use something like this:

```
Vector2 offsets[] = new Vector2[]
{
    //CLOCKWISE:
    new Vector2( 0,-1), //north
    new Vector2(+1,-1), //northeast
    new Vector2(+1, 0), //east
    new Vector2(+1,+1), //southeast
    new Vector2( 0,+1), //south
    new Vector2(-1,+1), //southwest
    new Vector2(-1,-1), //west
    new Vector2(-1,-1)  //northwest

};

...

//walk clockwise around neighbours and find (start of) adjacent groups
for (int d = 0; d < 8; d++)
{
    Vector2 offset = offsets[d];
    Tile neighbour = tiles[centre.x + offset.x, centre.y + offset.y];
    //etc.
}

```

I think you will perceive that there are many ways to work on this. Ideally, take your time, play, experiment and familiarise yourself with different ways of recognising different neighbour segments and how to evaluate them structurally and then act on those structures.

**Box filters: A reminder**

Remember that box filters don't have to be 3x3. They can be 2x2, 5x5 or whatever you want (`n`x`n`). Be aware however, that the larger `n` is, the higher the cost of the algorithm across the grid. That means it will be slower to run. But you can potentially get more control with a higher `n`.

Remember to do filter-passes interactively as in the previous code I gave you, e.g. hit spacebar to see how it looks at each step, rather than just running the filter 8x and hoping for the best. Then you can eventually settle on your final `numPasses` figure to hardcode in.

**NOTE**: I haven't gone to the extent of writing code for you as I did last time, because now you need to explore and really understand the cellular automata you are working with, and experiment yourself with the code to achieve those goals, in order to fine tune the generation algorithm to get the exact look and feel that *you* want. I'm happy to provide pointers. Besides that, cellular automata are a powerful tool and are worth gaining a deeper insight into for any game dev.

# Answer
> 1 votes
Repeat applications of b678/s345678 (aka the 4-5 rule) is probably the most common solution. Usually, the algorithm iterates until the output doesn't change from the previous step, though you may want to stop before that depending on your needs. As per the comments, increasing the number of iterations of your code may give you better results. It's not clear to me whether or not your rules guarantee an eventual stable result, so initially I'd recommend manually adjusting the iterations.

It's very common to pair a 'pure' cellular automata (CA) algorithm with some additional logic in order to get reliable, high quality results. Generally speaking the options usually fall into one of two categories (or a combination thereof):

**Constructive techniques** apply some logic either before or after the CA runs in order to constrain the result in some manner. For instance, you might start with the b678/s345678 CA to generate your initial island system. After that that you might check it for connectivity & use additional logic to merge subsets of islands until you get an acceptable result.

**Generate and test techniques** rely on statistics & probability to get a desired outcome. Essentially, you run your CA & then examine the result. If it's meets your criteria, you accept the result. Otherwise you rerun the CA. In order to make this a little more deterministic, you might create up to N different solutions & select the best one.

The other approach is to make the CA less naive by evaluating more than just the neighbor count; it may be arguable as to whether or not it's still a CA at that point. Again, the goal is to find ways to constrain the results to fit your needs. Since situations vary, you'll need to do some research & some experimenting.

---
Tags: java, procedural-generation, random, grid, filtering
---


# Question
Title: Directly pass from transform feedback buffer to fragment shader
I am building terrain using a lod algorithm and deferred cascaded shadowmaps. The tessellated terrain is about 6,000,000 triangles. I tried this using 2 methods.

1st method: Both the deferred shadow program and the drawing program use tessellation shaders to tessellate the terrain. The tessellation stage for each program is exactly the same.

2nd method: I have 3 programs. The first program tessellates the terrain and stores it on the GPU using transform feedback. The second program uses the transform feedback buffer to render to shadow depth buffer. The third program uses the transform feedback buffer to draws the scene. This way I avoid tessellating the terrain twice.

To my surprise, the 2nd method was actually much slower until I started using the separation of the tessellation phase to tessellate the terrain less frequently. Now the methods are about the same fps, but in the 2nd method the terrain mesh is being updated less frequently.

Shouldnt the 2nd method be faster even if I tessellate every frame like the first method? The only thing I can think of is that the passthrough vertex shaders for the shadow and main program both have to copy 6,000,000\*3 vertices even though they are just passthrough shaders. In the first method, the data would be passed right from tessellation shader to the fragment shader. So...

Does a passthrough vertex shader use the transform feedback buffer data directly, or does it copy every single vertice (even though it's the same), and use the copied data?

```
...
{
    out_position = in_position;
    out_normal = in_normal;
    out_uv = in_uv;
}

```

Is there any way I can speed this up?

Thanks in advance :)

Edit:

I should note that the example is for the shadow program, the geometry shader applies different mvp matrices, culls, and asigns layers.

In the main program, I use gl\_Position=mvp\*in\_position; to allow gl to cull back facing triangles, but the normals and uvs are still passthrough.

# Answer
> Does a passthrough vertex shader use the transform feedback buffer data directly, or does it copy every single vertice (even though it's the same), and use the copied data?

"the same" as what?

You told OpenGL to write 18 million vertices to a buffer object. Then you told OpenGL to render 18 million vertices which are stored in a buffer object. *Twice*. So that's what OpenGL is going to do.

How is it going to be able to render those 18 million vertices without reading them from memory? That's 36 *million* reads of vertex data. If your vertex data takes 32 bytes per vertex, that's over 1GB of data reading. Every frame.

Remember: the principle performance gain of tessellation is that you're reading and processing *less data*. By doing transform feedback reads of tessellated data, you're losing some of those performance benefits. Indeed, since transform feedback cannot generate optimized index lists, this will be *lower* in performance than if you had hand-tessellated the data and optimized it.

The reason your double-tessellation version is sometimes faster is because the cost of reading the expanded data twice (not to mention the cost of writing it) has exceeded the cost of doing the tessellation twice. And having to use a GS in your shadow render certainly isn't helping performance.
> -1 votes

---
Tags: opengl, transformation, shadow-mapping, level-of-detail
---


# Question
Title: Constantly Checking Collisions and OnTriggerEnter
Ok so i wanted to ask a basic question. suppose i have an edge collider 2d,

Fact - if i add the OnTriggerEnter() into my code. it will check for trigger enters constantly.

Now, If the edge collider exists but i don't put OnTriggerEnter(), will the game still check for trigger enter collisions? or will it not check for them?

# Answer
The physics system is always checking for collisions. `OnTriggerEnter` is there to receive events when a collision does happen, and that collision involves a trigger. If you're attempting to optimize, you should remove the collider. Removing the endpoint for the events is an optimization, but that's mostly from not having to run the code contained in the `OnTriggerEnter` event handler.

In other words, Unity's checking for collisions will not increase or decrease based on `OnTriggerEnter`.
> 1 votes

---
Tags: collision-detection
---


# Question
Title: iOS 9.3.5 WebSocket connection always closes with code 1006
I'm working on an app that uses a LabVIEW implemented server on the backend that is proxied via apache. It works great on desktops and android devices but on iPhone and iPad the websocket connection always fails and provides code 1006 in the close event. (No reason)

The request as received in LabVIEW:

```
GET /r9000_ws HTTP/1.1
Host: localhost:54663
Origin: http://192.168.1.191
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: ucoJ2G1XNSntZAOBCfG+uQ==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (iPad; CPU OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13G36 Safari/601.1
X-Forwarded-For: 192.168.1.193
X-Forwarded-Host: 192.168.1.191
X-Forwarded-Server: localhost
Upgrade: WebSocket
Connection: Upgrade

```

And the response I'm sending back:

```
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: NUDL0C4/691VkogIvxQRHM1xJA8=

```

I have tried this in both google chrome and safari on an older iPad. Unfortunately due to the fun of WebSocket security I can't get any useful information on where the failure resides. Thanks to anyone that can see what I'm missing!

# Answer
> 2 votes
In my case the problem was the line endings being generated in part of the response header I was creating in LabVIEW. I had a pre-built string that included everything but the base64 handshake, and then manually added the line endings to the end. The first 3 lines only ended with \r instead of the necessary \r\n. I discovered the discrepancy when checking the http traffic with Wireshark.

Everything except iOS was happy to accept the malformed line endings.

---
Tags: ios, websocket, ipad, http
---


title: Unity Pixel Perfect Rotation

text:
# Question
Title: Unity Pixel Perfect Rotation
I'm making a pixel-art game in Unity. The sprites are set to 16 PPU, and currently to guarantee that the pixels scale nicely (integer intervals), I'm setting the Camera's orthographic size.

In 16x9 aspect ratio on a 1920x1080p monitor, this gives me an orthographic size of 8.4375, effectively scaling up my art 4x.

The problem comes with rotations. When you rotate the pixel art using a standard rotation shader, the shader considers *screen* pixels but not the *art* pixels. I know there are solutions to this problem on the Asset store, but I'd like to create my own (I have checked other stack posts on this subject, but there doesn't seem to be a solution).

Currently, I have a rotation shader that rotates the vertices in the vertex function. However, like I mentioned above, this rotates in screen pixels. One idea I had was to first scale the sprite down to its art pixel dimensions (by scaling the vertices in the vertex shader), then rotate it, then scale it back up (in another pass?). I couldn't figure out how to make this work, and I'm not sure if it's the most efficient way.

Another idea I had was to create a copy of the texture that's being rotated in a script, save it in a larger texture, then handle all my rotations within the new texture (using `SetPixels` and `Apply`). This would ensure that the rotations are being done in art pixels, but is probably slower (and more inconvenient) than using a shader.

Note: Rendering to a back buffer and then scaling up everything is not a solution for me (this isn't a purist pixel art game, I just want pure pixel art rotations).

Any ideas? What approach should I take? I don't need the code written out for me, I just need an approach that'll work. Thank you!

Here is an example of what I'm talking about (credit for images goes to this stack overflow post, although it didn't have the solution I'm looking for).

Rotation on screen pixel level

Rotation on art pixel level

This is not a duplicate of this stack post. The solution that was accepted in that post does not perform rotation on the *art* pixel level, and because of that, it's not a valid solution in my case.

# Answer
> 1 votes
Ok, so I ended up getting a working solution. My algorithm is very loosely based off of the RotSprite algorithm (same idea without all the bells and whistles). The rotation is done on a `Texture2D` in a script I called `PixelRotate`. This is probably more inefficient than using a shader, but I couldn't figure out how to get the shader to work.

Step by Step explanation:

1. Create a copy of the sprite texture with transparent padding included. This ensures that when you rotate the sprite about its center none of the corners get cut off.
2. Use a modified Scale2x algorithm (implementation taken directly from link below, same one that's used in RotSprite) to scale up the sprite 8x (Scale2x is called three times).
3. Perform the rotation using standard Nearest Neighbor scaling while also simultaneously scaling the image back to its original size.

Notes:

* Since all rotations can only be done about the sprite's center (because the rotations take place inside a `Texture2D` with a limited size), rotating about a pivot point is more tricky. The way I handled it was allowing the user to specify a pivot point in PIXELS based on the ORIGINAL sprite, not the padded version. The function allows you to pass in by reference a `Vector3` called local. This vector represents the translation in WORLD units that the sprite must undergo for the rotation to successfully be completed about the specified pivot. All you have to do is add `local` to the sprite's `transform` after the rotation is finished.

Images:

As you can see, the algorithm isn't perfect. The outline of the sprites often times get messed up when you rotate. Any suggestions for improvements are much appreciated!

Code: https://pastebin.com/hSWuZFi3

Enjoy!

Sources:
Discussion on the RotSprite algorithm - https://pixelation.org/index.php?PHPSESSID=okvmle4tigkomqpjuu7uivchk5&topic=10510.10
Scaling code used in RotSprite - https://github.com/alteredgenome/grafx2/issues/385
Detailed description of RotSprite - http://forums.sonicretro.org/index.php?showtopic=8848&st=15&p=159754&#entry159754

---
Tags: unity, rotation, pixel-art
---


# Question
Title: Noticeable quality loss on texture captured using Graphics.Blit vs Shader output directly to a mesh
I'm currently using a GPU shader to generate a texture. I want to be able to capture the output of this out I'm using Graphics.Blit to output the shaders result to a `RenderTexture(GPU Memory)` and then using `Texture2D.ReadPixels(System Memory)` to grab the data from the `RenderTexture`.

So far I've got it almost perfect, unfortunately, I'm noticing a significant difference in quality between a plane that uses the shader output directly and a plane that uses the `Texture2D` returned from my method and applied to the shared material.

The process of my static method is as follows:

1. Check if the static material variable is set. If not, create a new instance using the shader and assign it to, the static material variable, otherwise reuse the existing one.
2. Create a RenderTexture that uses the same width and height scale as the `plane (128x128)` using `RenderTexture.GetTemporary()` which uses `ARGB32`, Linear colorspace and 0 depth buffer.
3. Set the material keywords and properties based on method input. Call `Graphics.Blit()` with null, `RenderTexture`(from 2) and material (from 1). Create a new Texture2D with the same dimensions as the render texture, `ARGB32` and using linear colour space.
4. Called `GetPixels()` on the above `Texture2D` with parameters, of a new Rect of `(0,0)` and render texture dimensions and 0 for offsets.
5. Call `Apply()` on the `Texture2D` and return it. I then use a simple editor script for the class that adds a button to call the above static function and then apply the output to the material of the object the script is on.

I don't know what's causing the quality loss, I've added a screenshot of what I'm currently getting below. The left plane is steps detailed above and the right plane is with the shader applied directly to a plane. Both use the same shader properties and keywords.

I don't normally post questions but I've tried everything I can think of to get the quality of texture to match the shader output. I'm wondering if I'm misunderstanding something about how the shader works or if it's a formatting issue. Any ideas are appreciated, thanks.

# Answer
When you draw a piece of geometry with a shader directly, the GPU evaluates that shader once for every screen pixel the geometry covers. (Or more, if you're using SSAA) Every single one of those evaluations can return a distinct value, giving you sharp, crisp edges and smoothly curving gradations limited only by your screen resolution.

When you render the output of that shader into a texture using something like Graphics.Blit, you get one evaluation of the shader per texel in the texture. This could be a greater or lesser number, depending on your texture resolution and the size you'll ultimately be drawing the geometry to the screen.

In this particular example, you mentioned that your texture is 128x128 texels - fairly small by modern standards.

Measuring the screengrab you posted, it looks like the quad you're rendering occupies a region of the screen between 450-550 pixels square.

So the direct shader rendering on the right, getting evaluated once for every screen pixel, has close to 4 times the resolution as the render-to-texture version on the left.

In contrast, the rendered texture has only one texel to sample for every 16 (4x4) screen pixels being drawn, and the GPU has to magnify & interpolate the texels with bilinear filtering to fill in the gaps, leading to the noticeable staircase shapes and fuzzy edges.

So, things you can do:

1. Stick to rendering materials directly on the surfaces you want to display them on, when you can.

This is the case that all our texture filtering & antialiasing hardware & algorithms are designed to handle best, and it gives you full detail at whatever resolution the object happens to be drawn at.
2. Where you need to write a result to an off-screen buffer, try to size that buffer appropriately to the size/density of texture detail you ultimately want to display on screen.

This might entail changing the buffer size as objects & the camera move around your scene - to avoid excess rendering objects that are tiny on-screen, and blurry results for objects that appear large. Fortunately, you don't need to GetPixels the result onto a Texture2D to use them - you can slap a RenderTexture straight onto the object you want to draw and save yourself some copying / texture management when juggling multiple sizes.
> 2 votes

---
Tags: unity, shaders, textures, rendertexture
---


# Question
Title: Monogame Effect World Translation Z and alpha in objects not visible behind
I have an effect in each triangle and rectangle:

In the triangle class I have:

```
Effect.World = worldScaling * worldRotation * worldTranslation;
Effect.Alpha = Opacity;

triangle = new[]
{
    new VertexPositionColor(new Vector3(X0, Y0, 0), EFill),
    new VertexPositionColor(new Vector3(X2, Y2, 0), EFill),
    new VertexPositionColor(new Vector3(X1, Y1, 0), EFill),
};

```

where EFill is a solid Color.

In the Rectangle class the equivalent.

Now I set the example to the following:

```
background = new Quad(new Vector2(0, 0), new Vector2(1000, 1000), "Red", "White", 0, camera);
background.Opacity = 0.2f;
WindowPanel.Children.Add(background);

triangle = new Triangle(0, -50 + 90, 20, 0 + 90, -20, 0 + 90, "Black", "Red", 1);
triangle.Translation.X = 160;
triangle.Translation.Y = 160;
triangle.Translation.Z = -10;
triangle.Opacity = 0.5f;
WindowPanel.Children.Add(triangle0);

```

But I do not see the triangle when it is behind the rectangle. (If I exchange the Z to the rectangle, the triangle is like the image)

I am new in the '3D' Monogame environment and I read a lot of documentation that could be outdated about AlphaBlend, Depth, etc. and I do not know what exactly applies and what do not.

So the triangle and the rectangle have alpha but are like independent of each other when rendered.

Any idea how to solve this?

# Answer
> 1 votes
Following and advice from @CaitVonSith, I changed the drawn order, first draw the triangle and then the rectangle and it is working like expected

Case Rectangle Z = -10

Case Triangle Z = -10

Also works on 3D rotations.

---
Tags: 3d, xna-4.0, monogame
---


# Question
Title: Why is this Procedural Content Generation while that other isn't?
I'm reading the online Procedural Content Generation book and on chapter 1, page 2 there's one example of what PCG is and another of what PCG is not and I can't tell them apart.

This is PCG according to them:

> game engine middleware that rapidly populates a game world with vegetation

This is NOT PCG according to them:

> a game engine capable of integrating automatically generated vegetation

Also on page 1 they explicitly said they do not consider a game engine PCG

> A key term here is “content”. In our definition, content is most of what is contained in a game: levels, maps, game rules, textures, stories, items, quests, music, weapons, vehicles, characters, etc. **The game engine itself is not considered to be content in our definition.**

My guess is the PCG example is a code in a game (or it could be a code that adapts to any game) that recognizes the game map and populates it with vegetation according to it. And the not PCG example for me would be like an option available from the game engine were the developer can add the vegetation offline via the user interface.

The last one is a very very wild guess from me, I'm pretty sure I'm wrong cause at first glance they both sound like PCG. Please help me differentiate them.

# Answer
**By way of analogy**

A circuit does not generate power. A light bulb does not generate power. A battery does not generate power. None of the things which *use or store generated power*, are power generators.

A gasoline-driven generator *is a power generator*. A solar panel setup *is a power generator*. *They* can be expected to spontaneously generate when they are kicked off. Other things can *use* that power they generate: fridges and TVs and PCs and heaters and light bulbs.

Likewise, any code or program that *actually generates content itself at runtime* is PCG. The rest are just *users* of that procedurally-generated content (PGC). Now,

*Procedural Content Generation*

is not the same as

*Procedurally-Generated Content*

PGC is the resultant artifact of a process (program) which engages in PCG.

PCG is developed (programmed) to a point where it can autonomously produce content to some or other specification, but in (typically) countless variations; PGC is generated thereby as *one single* variation of the otherwise limitless possible content spaces within that broader algorithmic specification. PGC's are *finite* and *static* once generated. PCGs deal with *infinity* (or near enough).

**Addressing specifics**

"Procedural Content Generation" refers to code / applications which generate content.

Any game can be considered a PCG game *if, at runtime* it dynamically generates new content via part of its instruction set.

If you (or your engine) use(s) some other program code that generates content, then include that content as part of your game at *compile / build time*, then your game (and it's code) is NOT PCG. Hence:

> a game engine capable of integrating automatically generated vegetation

...is not PCG, since that engine itself does not produce new content at runtime, it simply uses generated content from elsewhere, that has been manually included by artists, designer or devs.

> recognizes the game map

PCG has nothing to do with recognition. It has to do with doing the active work of creating content. Generally PCG applications produce their own format of data that they can already understand and work with. They do not typically read in outside sources, although when they do, that is just plain old program logic... not PCG as such. PCG is all about *generation*. Hence PCG and not PCR :)

**Historical perspectives**

What we consider "content" in this context generally covers those things which, in the past, humans have *had* to produce by themselves. For example in the '70s and '80s, pretty much every game (with the exception of a very special few) had to have its art, its storyline, its music, its character and planet names, and suchlike, produced by a human being. That was the *polar opposite* of PCG.

PCG began when game programmers realised that instead of the rigmarole of hiring artists, musicians, writers etc. - and then still having to integrate their work with the code, or worse yet, doing all of that work themselves *as well as coding* \- they could instead write programs to generate all that stuff for them. Those efforts were some of the first truly PCG functions, modules, and programs. A perfect example is the original XCom / UFO, where the game's code generates a completely unique level for you before combat. Earlier still (1979) was Temple of Apshai.

Elite was a different case: *some* of its content was generated when the game was under development; not only was that code written by the very same authors, but also that pre-generated content was typically used at runtime of `elite.exe` (i.e. when you the player ran the game) by *further generators which were part of the game's code*, creating the world you played in.

A newer example is Minecraft (and other games inspired by it) where the world literally generates around you as you walk toward the horizon, thanks in large part to modern computing power. Compare this to Rogue or Moria played on a PC-XT in the 1980s, for which you might have to sit sometime waiting for the level to generate! (depending on your chosen game settings).

Not all PCG is historically rooted in the games industry. For example, there are those who write fiction generators. For example, Ken Perlin in the field of graphics and computational geometry created the Perlin Noise algorithm, for which he was later given an academy award. For example, the musician Brian Eno has for a long time engaged in procedural generation of musical scores. And as another example, non-digital boardgames like HeroQuest/Warhammer Quest long ago invented procedural dynamics for creating a different gameboard on each play.
> 27 votes

---
Tags: procedural-generation, terminology, content-generation
---


title: Collider / coroutine timer issues

text:
# Question
Title: Collider / coroutine timer issues
Now this may be a physics issue as it seems more of a collider issue - specifically using multiple box colliders inside 1 empty gameobject. Oh and aplogies about the lengthy thread.

My game (for my degree dissertation) consists of two 3D levels the players walks around and each level consists of 4 zones. What i want to do is start and stop individual timers for each zone so i can work out how long they spend in each area.

I have sussed this part using coroutines to do my timers (see code below) and the whole things works as intended except that the issue is, as these zones are made up of multiple box colliders in an empty gameobject (say one zone is an L-shaped, meaning its made up of 2 cuboids), each zone is not exactly simple shapes. Basically a maze of 10x10 floors (planes), set out in a maze like fashion with various zones (see image below). For each of these zones, i have an empty gameobject with multiple box colliders to make up the volume of each zone. These are set to IsTrigger so that the player can wander through but doing so trigger the OnTriggerxxx() events to start and stop the coroutines.

The trouble is where these box colliders join internally inside the same zone. The timer stops when the player crosses from one collider to another, even though they're in the same game object (zone) and therefore compound. The timer either stops or it seems to multiply the timer speed when you cross between collider borders, multipling each time a boundary is crossed, so walking backwards and forwards between colliders makes the timer keep going faster and faster and obviously not correct time data.

So questions are: Is there something i can add to the OnTriggerStay() events to keep the timers going or to stop the build up of speed in the timers? Which is obviously a build up of the triggered coroutines stacking on each other, escalating the speed of the clock whenever the player keeps crosses ANY colliders.

or......

Is there a way to correct the issue with the colliders? Like create them as one single collider? This by far seems the most obvious issue. If i could make a single collider the shape of the zone, so like a 3D L-shape or other bespoke shape. Think tetris in 3D as a maze, similar shapes basically.

This is the script i've written for the timer routine. I bet its something really obvious haha.

Thanks,

Paul..

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

public class AreaTime_A : MonoBehaviour {

    private float startTime;
    public Text timerText;
    public Text timerText_HW;
    public Text timerText_ST;
    public Text timerText_IZ;
    public Text timerText_OUT;
    private bool TimerOn = false;
    private bool TimerOn_HW = false;
    private bool TimerOn_ST = false;
    private bool TimerOn_IZ = false;
    private bool TimerOn_OUT = false;

    public int minutes;
    public int seconds;
    public int seconds_HW;
    public int minutes_HW;
    public int seconds_ST;
    public int minutes_ST;
    public int seconds_IZ;
    public int minutes_IZ;
    public int seconds_OUT;
    public int minutes_OUT;

    // Use this for initialization
    void Start () {

        startTime = Time.time;
        TimerStart();
    }

    void Awake () {
        DontDestroyOnLoad (this);
    }

    void Update () {
    }

    public void TimerStart() {
        TimerOn = true;
        StartCoroutine (TOTAL_Timer());
    }

    public void TimerEnd() {
        StopCoroutine (TOTAL_Timer());
        TimerOn = false;
        TimerOn_HW = false;
        TimerOn_ST = false;
        TimerOn_IZ = false;
        TimerOn_OUT = false;
    }

    private IEnumerator TOTAL_Timer() {
        while (TimerOn) {
            yield return new WaitUntil (()=> TimerOn);
            seconds++;

            if (seconds == 60) {
                minutes++;
                seconds = 0;
            }
            timerText.text = minutes.ToString() + ":" + seconds.ToString();
        }
    }

    private IEnumerator HW_Timer() {
        while (TimerOn_HW) {
            yield return new WaitUntil (()=> TimerOn_HW);
            seconds_HW++;

            if (seconds_HW == 60) {
                minutes_HW++;
                seconds_HW = 0;
            }
            timerText_HW.text = minutes_HW.ToString() + ":" + seconds_HW.ToString();
        }
    }

    private IEnumerator ST_Timer() {
        while (TimerOn_ST) {
            yield return new WaitUntil (()=> TimerOn_ST);
            seconds_ST++;

            if (seconds_ST == 60) {
                minutes_ST++;
                seconds_ST = 0;
            }
            timerText_ST.text = minutes_ST.ToString() + ":" + seconds_ST.ToString();
        }
    }

    private IEnumerator IZ_Timer() {
        while (TimerOn_IZ) {
            yield return new WaitUntil (()=> TimerOn_IZ);
            seconds_IZ++;

            if (seconds_IZ == 60) {
                minutes_IZ++;
                seconds_IZ = 0;
            }
            timerText_IZ.text = minutes_IZ.ToString() + ":" + seconds_IZ.ToString();
        }
    }

    private IEnumerator OUT_Timer() {
        while (TimerOn_OUT) {
            yield return new WaitUntil (()=> TimerOn_OUT);
            seconds_OUT++;

            if (seconds_OUT == 60) {
                minutes_OUT++;
                seconds_OUT = 0;
            }
            timerText_OUT.text = minutes_OUT.ToString() + ":" + seconds_OUT.ToString();
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "HW_Collider")
        {
            TimerOn_HW = true;
            StartCoroutine (HW_Timer());
            timerText_HW.color = Color.yellow;
        }
        else if (other.gameObject.name == "ST_Collider")
        {
            TimerOn_ST = true;
            StartCoroutine (ST_Timer());
            timerText_ST.color = Color.magenta;
        }
        else if (other.gameObject.name == "IZ_Collider")
        {
            TimerOn_IZ = true;
            StartCoroutine (IZ_Timer());
            timerText_IZ.color = Color.green;
        }
        else if (other.gameObject.name == "OUT_Collider")
        {
            TimerOn_OUT = true;
            StartCoroutine (OUT_Timer());
            timerText_OUT.color = Color.blue;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.name == "HW_Collider")
        {
            TimerOn_HW = false;
            StopCoroutine (HW_Timer());
            timerText_HW.color = Color.white;
        }
        else if (other.gameObject.name == "ST_Collider")
        {
            TimerOn_ST = false;
            StopCoroutine (ST_Timer());
            timerText_ST.color = Color.white;
        }
        else if (other.gameObject.name == "IZ_Collider")
        {
            TimerOn_IZ = false;
            StopCoroutine (IZ_Timer());
            timerText_IZ.color = Color.white;
        }
        else if (other.gameObject.name == "OUT_Collider")
        {
            TimerOn_OUT = false;
            StopCoroutine (OUT_Timer());
            timerText_OUT.color = Color.white;
        }
    }

    void OnTriggerStay(Collider other)
    {
        if (other.gameObject.name == "HW_Collider")
        {
            timerText_HW.color = Color.yellow;
        }
        else if (other.gameObject.name == "ST_Collider")
        {
            timerText_ST.color = Color.magenta;
        }
        else if (other.gameObject.name == "IZ_Collider")
        {
            timerText_IZ.color = Color.green;
        }
        else if (other.gameObject.name == "OUT_Collider")
        {
            timerText_OUT.color = Color.blue;
        }
    }
}

```

# Answer
This happens because you're **not** stopping the coroutines that you started in the first place, because you have no reference to them.

In order to fix the problem, you need to declare `IEnumerator` variables that will store the reference to the coroutines, so that you can stop the exact same one referenced by the variable.

Like this:

```
IEnumerator totalTimer;
IEnumerator hwTimer;
IEnumerator stTimer;
IEnumerator izTimer;
IEnumerator outTimer;

void Awake() {
    totalTimer = TOTAL_Timer();
    hwTimer = HW_Timer();
    stTimer = ST_Timer();
    izTimer = IZ_Timer();
    outTimer = OUT_Timer();
}

```

Then, when you need to start and stop one of those coroutines, just use, for example when starting and stopping `TOTAL_Timer()`, `StartCoroutine(totalTimer)` and `StopCoroutine(totalTimer)`.
> 1 votes

# Answer
I suggest tracking the count of colliders from each zone that the player is in with `OnTriggerEnter` and `OnTriggerExit`, and only starting or stopping a coroutine in `Update`.

The code you posted in a comment will start a new timer if the timer is running, not if it isn't. A small change would fix it. Try this for your Update:

```
void Update() {
    if (Count_HW > 0) {
        if (!TimerOn_HW) {
            TimerOn_HW = true;
            StartCoroutine(HW_Timer());
        }
    } else {
        if (TimerOn_HW) {
            TimerOn_HW = false;
            // coroutine ends automatically
        }

        // bonus: with this kind of enter/exit code, it's always good to check for "impossible" conditions

        if (Count_HW < 0) {
            Debug.LogError("Somehow, we exited " + -Count_HW + " more HW colliders than we entered!");
            Count_HW = 0;
        }
    }

    // same idea for the other timers
}

```
> 0 votes

# Answer
Do your coroutines really stop when you do stopcoroutine? You might have to save them like Coroutine coroutine1 = StartCoroutine(1); and then stop it with StopCoroutine(coroutine1);
> 0 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: Determine terrain type and worldobject placement techniques
I'm currently researching the techniques of generating a procedural map. I've already found some methods regarding the mesh generation (e.g. variations of noise like perlin, simplex and cell, midpoint displacement and diamond square).

The next step for me is to determine the terrain type. The most easy way is probably matching a static value to the height value (e.g. everything below 0.2 is water, everything between 0.2 and 0.3 is sand, everything between 0.3 and 0.5 is grass, etc.). To make a more advanced version I can use temperature and moisture values for the biomes. I'd very much like to know other techniques to determine this.

I also want to place objects (like rocks, trees, plants) on the map, however I can not seem to find different techniques to research/implement this. I probably just don't know the name of the global technique to find specific techniques. I found the use of fractal noise with a variable for the probability, but I'd like to know more techniques.

So, let me know some of your techniques.

# Answer
> 1 votes
If you want to place 100 trees per square-kilometer, then the easiest solution would look something like this (pseudocode):

```
for (int i = 0; i < 100; i++) {
     position.x = randomValueBetween(0.0f, 1000.0f);
     position.y = randomValueBetween(0.0f, 1000.0f);
     placeTreeAt(position);
}

```

This will usually give you results which look sort-of-OK at first glance. However, there are a few problems here:

1. There will be *exactly* 100 trees per square-kilometer. This might or might not matter for your game.
2. Clustering illusion. While the distribution of your trees will be perfectly randomly distributed (assuming you use a good RNG), it might not *look* random. This might not be so bad with purely cosmetic trees, but it might be worrisome with objects where tight clusters are bad for gameplay (like player start locations in a battleroyal game).
3. It will place trees where there shouldn't be trees. You might see trees sticking out of rocks, growing on steep slopes, in the middle of a lake or even two trees so close together that their trunks intersect each other.

The first point is rather easy to fix if necessary: Just add a random number to the number of trees you want to generate:

```
int numberOfTrees = 100 + randomValueBetween(-10, 10);

for (var i = 0; i < numberOfTrees; i++) {
     position.x = randomValueBetween(0.0f, 1000.0f);
     position.y = randomValueBetween(0.0f, 1000.0f);
     placeTreeAt(position);
}

```

The last two points can be fixed by checking if the randomly generated position is actually a valid position to place a tree:

* are there already enough trees in an `x` meter radius around it?
* is it physically possible for a tree to exist at this position?

When the position is not valid, one option is to just skip it. This means you can no longer rely on the number of trees per chunk to be constant. Biomes which have a less "tree-friendly" geography will have less trees than the number of trees says it should have.

Alternatively you can run the loop until you found 100 *valid* positions, but keep in mind that this might take a while in very tree-unfriendly terrain (or even forever if there aren't 100 valid tree-positions at all in the chunk). So you might also want to set a maximum number of retries.

```
const int numberOfRetries = 10;
int numberOfTrees = 100 + randomValueBetween(-10, 10);

for (var i = 0; i < numberOfTrees; i++) {
     for (var j = 0; j < numberOfRetries; j++) {
         position.x = randomValueBetween(0.0f, 1000.0f);
         position.y = randomValueBetween(0.0f, 1000.0f);
         if (treeCanBePlacedAt(position)) {
             placeTreeAt(position);
             break;
         }
     }
}

```

---
Tags: procedural-generation, procedural
---


title: Is Trigger Colliders not ignored

text:
# Question
Title: Is Trigger Colliders not ignored
I am working on a 2D Plattformer with melee attacks. The player is using a Kinematic Rigid Body and a Capsule Collider. Movement (even in slopes), jumping and and collission are working fine. My problem is that when swinging the axe I am animating a Box Collider 2D with IsTrigger set to true. But it is still not ignored and are pushing the player.

For movement and collissions I use the following code:

```
void Movement(Vector2 move, bool yMovement)
{
    float distance = move.magnitude;
    if(distance > minMoveDistance)
    {

        foreach (var item in hitBuffer)
        {
            if (item.distance > 0)
                Debug.DrawRay(item.centroid, item.normal, Color.red, 0.5f);
        }

        int count = rb.Cast(move, contactFilter, hitBuffer, distance + shellRadious);
        hitBufferList.Clear();

        for (int i = 0; i < count; i++)
        {
            hitBufferList.Add(hitBuffer[i]);
        }

        foreach (var item in hitBufferList)
        {
            Vector2 currentNormal = item.normal;
            if (currentNormal.y > minGroundNormalY)
            {
                grounded = true;
                if (yMovement)
                {
                    groundNormal = currentNormal;
                    currentNormal.x = 0;
                }
            }

            float projection = Vector2.Dot(velocity, currentNormal);
            if (projection < 0)
            {
                velocity = velocity - projection * currentNormal;
            }

            float modifiedDistance = item.distance - shellRadious;
            distance = modifiedDistance < distance ? modifiedDistance : distance;
        }
    }

    rb.position = rb.position + move.normalized * distance;
}

```

I suspect it might have some thing to do with the raycast being cast also from the animated box but I do not know if this is the case and how I could test it. I have setup a filter that I pass in to the rb.Cast but even with useTriggers set to false it does not make any difference.

Any feedback that could point me to in the right direction would be very helpful!

# Answer
> 2 votes
I solved the problem by not using RigidBody.Cast that uses all attached colliders but instead using a Collider.Cast so I only got back collission for that specific collider.

---
Tags: unity, collider
---


title: How to achieve game server redundancy?

text:
# Question
Title: How to achieve game server redundancy?
The game I'm developing has a simple game server which stores inventory and hero data for each user, as well as deciding the outcome of some random events. The server interacts with PostgreSQL and responds to HTTP queries. It runs on EC2 and Microsoft Azure, but these hosts sometimes become unreachable for a few minutes, and one week the EC2 server froze every day. What are the strategies to make sure a server is always available?

Non-solution: Multiple servers with their own databases, and the client will try to connect to a different server after a timeout. Of course, their data will be absent if it's a different server.

Solution 1: As above, except whenever player data changes, that change is stored, and each player's data is replicated to the other servers (bidirectionally). The disadvantage is that this solution is "home grown" and prone to mistakes.

Solution 2: One primary server (let's leave sharding for later), and one or more backup servers, with the database being replicated. When the primary server becomes unreachable, a backup server is made into the primary server. Problems: this needs additional technology for directing queries to the right server, and also to decide when a backup server needs to be promoted to primary. Can this "manager" also hang? It sure can if it's on AWS! That would bring the whole system down.

Solution 3: We could pay for database hosting with some guarantee of reliability, and have multiple servers but just one database. We would assume the database is reliable (but still back it up). The user could connect to any reachable server, and the servers would not need to worry about having stale data, since there will be only one database. (Again, sharding is a separate problem, and we could just multiply the whole setup without fundamentally changing its architecture.)

So how is reliability achieved when individual servers aren't reliable? I like solution 3 for its simplicity, if a 3rd party database can be relied upon.

# Answer
I have done your Solution 3 in the past, and it worked quite well.

We then had an arbitrary number of server machines inside the server farm, each of which was running one or more pieces of the game server software (which we had split up into about ten different programs, each handling different tasks). We had one "Object Request Broker", which clients would query about where to send particular types of network request. If one server went down for some reason, the ORB server would notice after a few seconds, and would send clients to a different server instead. This made things really flexible, in terms of upgrading servers or adding and removing capacity. The only 'fragile' pieces in the system were the data stores (which were a database and a couple of other bits of short-term storage which were also shared between an arbitrary number of servers)

Note, though, that all of this used a physical server farm, not a cloud-based one (cloud-based computing wasn't yet a thing back then). Downtime was almost entirely at our own discretion, apart from infrequent calamities like network outages, power failures, or crashes. If a cloud outage takes all your servers out at once, it doesn't really help you that you had several of them; it's a little bit of different situation where we were in control of the downtime ourselves, and could take machines down and do maintenance on them one at a time so that server remained up pretty reliably even through maintenance periods.
> 2 votes

# Answer
I agree that option 3 is the way to go - this is a pretty standard setup and requirement of resilient web hosting, and not something that you should really have to write yourself.

For full resiliency you'd be looking at a step-up such as:

1. A load-balancer (ideally more than one, on a Virtual IP and fronted by a high-availability service to health check the load-balancers and route traffic as needed).
2. Multiple servers running your Game Server application (again, ideal hosted in different locations).
3. A Database Server (ideally that offers replication, with replication into a second location).

Obviously, these services can get fairly expensive, but AWS or Azure should offer you some free options to get started - both of these offer solutions to create multiple copies of your application either within the same "region" but in different parts of the data centre with traffic automatically loadbalanced or in multiple "regions" and then either balance traffic between them or have one as a "hot standby".

But as you note you could start by using a reliable database host and calling that from all your servers - typically, a reputable host will have a fairly reasonable service level agreement for Databases, so you might be able to get away with a single database server for your application - or you could look into something like MongoDB Atlas which offer a free 3 node replicated instance to get you started.

What you should also do is try and work out why your EC2 nodes are freezing - is it AWS networking/infrastructure issues (for example if you're only running one instance, AWS will have to move/stop-start your application when performing updates to the underlying hosts - scaling out to multiple instances in different availability zones should reduce this) or is it that your application is crashing or hanging (could be any number of reasons, but deadlocks and data connections are typically good starting points, followed by memory leaks).
> 2 votes

---
Tags: server, databases
---


# Question
Title: Multiple Mesh Renderes with Matrices. (Direct X11, C#)
im just confused: Im trying to render 2 cubes instead of one. So in my main class i have my WORLD matrix. Then if i render the mesh the camera is multiplying all matrices with the worldProjectionBuffer etc... But how do i add the MeshRenderer´s world matrices to the of the Camera? And how do i add them to the Buffer then? :/ Please help me!

Creating the Buffer:

```
worldViewProjectionBuffer = new SharpDX.Direct3D11.Buffer(device1, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

```

Setting the Buffer:

```
context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

```

The Camera is updated every Frame:

```
currentCamera.Update(context, worldViewProjectionBuffer);
OnFrameUpdate();
renderer.Draw(context);

```

The Update of the Camera is recreating the matrices, but how would i add 2 other world matrices to the camera?

```
internal void Update(DeviceContext context, SharpDX.Direct3D11.Buffer worldView)
        {
            viewProjection = Matrix.Multiply(view, projection);
            worldViewProjection = world * viewProjection;
            worldViewProjection.Transpose();
            context.UpdateSubresource(ref worldViewProjection, worldView);
        }

```

And the MeshRenderer has it own world matrix - but how do i add the vertices from the model to it?!

```
 public sealed class MeshRenderer : BaseRenderer, IDisposable, ICloneable
    {
        private Model mesh;
        private Material material;
        private Matrix world;
...

```

Thank in Advance,

Best Regards, Kerbo

# Answer
So, to be short, there are a few ways. But you are almost there with your current approach.

Probably the best way to get over the line is to add an additional Matrix to your constant buffer, say call it "meshMatrix". This is the only one you will need to update each time you want to render a model.

In your Vertex buffer, just multiply your WVP matrix by meshmatrix. Each time, before you render the next model, update your constant buffer. Do not modify your WVP matrix after you have set it, its used to project the world (basically), after that, your mesh matrices allow you to place and orientate objects in that world.

On a side note: If you declare your constant buffer in your shader with row\_major, you wont need to execute a "Transpose" call in your CPU.

Now, in your vertex shader, you should be multiplying each vertex by the mesh matrix and then the WVP matrix in your constant buffer.

Simple vertex shader code

```
    struct VertexIn
{
    float4 pos : POSITION;
    float4 uv : TEXCOORD0;
};

struct VertexOut
{
    float4 pos : SV_POSITION;
    float4 uv : TEXCOORD0;

};

// Vertex Shader
VertexOut VSMain(VertexIn input)
{
    VertexOut output = (VertexOut) 0;
    input.pos.w = 1.0f;
    output.pos = mul(input.pos, meshmatrix);
    output.pos = mul(output.pos, wvpmatrix);

    output.uv = input.uv;

    return output;
}

```

Each draw call you make, it pass the vertex buffer through and you need to multiply out the vertices, they are not permanently modified in your vertex buffer.

For light reading to understand more on your rendering pipeline, I recommend a couple of microsoft pages that will come in handy. these discuss index buffer and probably what you want to know more about, that being "Instance buffers".

DrawIndexedInstanced \- Draws a mesh using its vertex buffer, index buffer and positioned in the world using an instance. (There is a lot more prep to get this to work, but its worth it). Rendering Pipeline \- Just to highlight that vertex buffers may not be the only place you may end up using matrices.

Post more questions on this forum if you have follow ups.
> 0 votes

---
Tags: c#, directx11, sharpdx
---


# Question
Title: How can I un-bloat my player input processing in my text based game?
I'm writing a text based game, and I hit a snag with the user commands processing: so far I have a huge hardcoded ifelse block, and that does not seem good or scalable.

With single word non session commands it is easy:

```
> quit

```

Here I know I simply have to quit; but when it comes to multi word commands, like:

```
> help skills
> use bag
> take sword from bag

```

the `if`/`elseif`/`else` pattern is so cumbersome and not scalable.

Also, with regards to commands in one session, like so:

```
> open box
> look inside box
// you see next items inside box: one, two, three
> take one

```

how can I process different options depth, when each command received from client is processed from the beginning? How to respond with "first you must open box to take items from it" if user enters "take one" without prior "open box"?

How can I organize and process user input efficiently here?

# Answer
> 5 votes
I'd be tempted to write this as a lexer-parser pair, like a script interpreter / compiler front-end.

The lexer reads the string, cuts out the next "token" to handle, skipping over whitespace or irrelevant punctuation, and standardizing the vocabulary of tokens (say, flattening to lowercase or merging synonyms/spelling variants/permitted typos).

The parser can then act on a higher level, describing the sequences of tokens it expects/accepts for particular commands.

The style of lexer I've used in the past exposes two ways of processing the next token:

* **Expect** checks to see if the next token matches a particular criterion. If it does, it consumes it and advances to the next token. If it doesn't, it generates an error.

We can use this for transitive verbs like "Take" by expecting an object word to follow, and complaining "Take what?" if this expectation is not met.
* **Accept** checks if the next token matches a criterion. If it does, it consumes it and skips ahead to the next token after it, otherwise it does nothing at all.

This is good for allowing optional words like "Take screwdriver" or "Take the screwdriver" without a big combinatoric explosion of if/else branches for every possible phrasing.

Similar to abathur's answer, I'd recommend storing a list of command tokens paired with a function pointer / delegate representing the action it performs. Then you can search your array of commands for a match for the first token, and fire off the appropriate logic. If you pass the lexer down into that command, it can use it to recursively check the subsequent tokens as needed.

So we might have something like this:

```
CommandResult TakeCommand(Scene scene, Lexer Lexer) {
    // Optional A / An / The / That / This
    lexer.Accept(Token.Articles);

    // You can extend this to handle things like
    // "Take one of / take two / take all"
    // if(lexer.Accept(Token.Quantifier)) ...

    // Or specific flavours of item...
    // "Take the big blue screwdriver"
    // while(lexer.Accept(Token.Descriptor))...

    // Check that they provided an object to take.
    if(lexer.Expect(Token.Identifiers) == false)
        return CommandResult.Error("Take what?")

     // Validate that the named thing is an inventory item.
     var item = GetInventoryItemFromToken(lexer.consumedToken);
     if(item == null)
          return CommandResult.Error("You can't take that.");

     // Validate that there is such a thing in this scene/context.
     if(scene.ContainsItem(item) == false)
          return CommandResult.Error("There's no {0} here.", item.canonicalName);

     // Finally, defer the actual inventory operation to the scene
    // (it might want to implement special rules,
    // like "you can't just take George's false teeth,
    // you'll have to offer something in trade!" or
    // "as soon as you lift the idol, the whole temple
    // begins to shake..."
    return scene.Take(item);
}

```

Now you can wire up your commands something like...

```
parser.RegisterCommand(Token.Take, TakeCommand);

```

Depending on your setup, you may be able to treat these command mappings as data & modular action components, rather than hard-coding them all.

# Answer
> 2 votes
Caveat: I'm not sure this recommendation really un-bloats your input processing, (in some sense it can make it worse), but it does enable you to modularize and better understand it.

Let's start with an overly simple explanation of how command-processing works on an old MUD I admin for:

1. User input arrives, and we perform transformations based on any user-defined aliases or nicknames (i.e., if the player types `ef` and `alias ef = 'eat current_food'` and `nickname current_food = apple`, we'll transform the command down to `eat apple`).
2. Next we replace/transform any globally defined aliases (`n = north`).
3. Then we take the first "word" as the command, and start asking various objects (in a defined sequence) if they'd like to handle this command by calling some specific method with the command and arguments. If one object returns false, we ask the next.

This model is simple, and it gives you a great amount of flexibility. There's some start-up and computational inefficiency, but I think the trade-off is worth it. We give a *lot* of objects a chance to handle the command; here's a rough example in pythonic pseudocode:

```
global_commands = {
    "take": TakeCommand(),
    "use": UseCommand()
}

def process_command(input_string):
    input_string = player.replace_nicknames(input_string)
    input_string = player.replace_aliases(input_string)
    input_string = global_command_replaces(input_string)

    command, arguments = input_string.split(maxsplit=1)

    if not find_command(command, arguments):
        print("no such command")

def find_command(command, arguments):
    if find_command_in(player.inventory, command, arguments):
        return True

    if find_command_in(player.environment.inventory, command, arguments):
        return True

    if player.environment.do(command, arguments):
        return True

    if player.do(command, arguments):
        return True

    if command in global_commands:
        if global_commands[command].do(arguments)
            return True

def find_command_in(items, command, arguments):
    for item in items:
        if item.do(command, arguments):
            return True

```

All of these objects get to make their own decisions about what does/n't work, and you may be able group some common features/functionality together with inheritance or just common patterns. This also enables you to override global commands in local instances where you want something special to happen.

# Answer
> 1 votes
When I developed my text-based RPG in Ruby, I had a module that parses input into `<verb> <arguments>` pairs. Then arguments are passed over to module that runs processing of each verb separately, such as:

```
module Parser
  @@UNKNOWN = "Don't know this command"
  @@NO = "Hmm?"
  def Parser.parse(str, player) # what, from
    str = str.gsub(/^\s*/,"").gsub(/\s*$/,"")
    unless str == ""
      action, params = str.split(/\s/, 2)
      suc = false
      Commands::LIST.each do |k, f|
        if k=~/^#{Regexp.escape(action)}/i
          $log.info [action, params]
          eval("Commands.#{f}(player, params)")
          suc = true
          break
        end
      end
      player.send @@UNKNOWN unless suc
    else
      player.send @@NO
    end
  end
end

```

Here is snippet of the commands module `commands.rb`:

```
module Commands

  LIST = {
    "look" => "look",
    "tell" => "tell",
    "say" => "say",
    "save" => "save_base",
    "north" => "go_north",
    "south" => "go_south",
    "west" => "go_west",
    "east" => "go_east",
    "down" => "go_down",
...
  def Commands.scan(player, *a)
    player.scan
  end

  def Commands.tell(creature, *args)
    to, msg = args[0].split(/\s/, 2)

    if (pl = Player.find({:name => to})) && pl.online? && pl.visible_for(creature)
      if pl == creature
        creature.send "You wanna talk to yourself?"
        return false
      end
      creature.tell(pl, msg)
    else
      creature.send "There is nobody called #{to} here."
    end

  end

  def Commands.say(creature, *args)
    str = args
    creature.say str[0]
  end

```

---
Tags: architecture, text-based
---


# Question
Title: How do I make my game (without performance problems) not stutter?
I've made a game that has gameticks every 1/60 seconds. These gameticks take very little time to calculate (\< 0.5 ms).

The game is written in Javascript and uses requestAnimationFrame (rAF). rAF fires roughly a few milliseconds (how many is determined by what the browser thinks is necessary) before (mostly) every frame output to the monitor.

The code does the following every rAF:

* get a timestamp
* figure out how many gameticks should have happened at that timestamp, and (if needed) run enough to catch up
* render state after latest gametick to screen

This works fine most of the time. It runs at a consistent 60 gameticks/second, regardless of what the screen is doing (good for syncing multiplayer). It handles any framerate. The game looks smooth except, sometimes, the timestamps happen to be right around the boundary for new gameticks.

```
frame 10: gametick 2.01 (renders gametick 2)
frame 11: gametick 2.99 (renders gametick 2)
frame 12: gametick 4.01 (renders gametick 4)
frame 13: gametick 4.99 (renders gametick 4)
frame 14: gametick 6.01 (renders gametick 6)

```

When this happens, it stutters horribly. How do I make it avoid stuttering needlessly?

# Answer
> 1 votes
What you're experiencing is called judder - it comes from a mismatch between the rate at which motion is updated and the rate at which it's displayed/sampled.

Sometimes a sample falls immediately before an update, making it seem like the object has frozen in place momentarily, sometimes it lands just after an update, making it seem like the motion has skipped ahead.

The most surefire fix for this, as mentioned in the comments, is to interpolate the displayed game state between the two most recent state updates, according to how much "loose change" time is left over between the display time and the last update time. This will generally give buttery smooth motion, and good feedback design (timing feedback to the display frame, rather than to the state update) can minimize any impact on perceived latency.

If you don't want to interpolate, then you're stuck with some amount of judder, so the best you can do is try to minimize it.

Since this is effectively a beat frequency between the two periodic processes, it gets most pronounced when the update rate and the display rate are very very similar. This maxes-out the possible error to +- 1 full frame, as shown in your example, and when we get a shortfall back-to-back with a surplus, we can jump two frames at once. And once we get into that dangerous range where display frames are falling just ahead/just shy of the update, rather than safely in the middle, we tend to stay there for a long time, since the rates are so similar.

We can combat that by shortening our game state update's fixed timestep until it's distinctly different from the display rate. This does two good things for us:

1. Shortening the fixed timestep shrinks the maximum possible shortfall/surplus time we can have in a display frame, minimizing the displacement between where a thing should be "now" and where it's drawn.
2. By making the rates different (relatively prime, if we can), we make it much less likely that they'll sit in problematic alignment for an extended period of time. The display frame will tend to fall more randomly within the update cycle, spreading out any judder into a frame here or there, rather than vibrating on several consecutive frames.

---
Tags: javascript, timing, fixed-timestep
---


# Question
Title: Cannot explicitly hide variable member even using "new" keyword
> See the answer by me, this problem is pretty much my own mistakes of miss understandings.

So, here is my problem.

I have parent class called `CameraBehaviour` derived from `MonoBehaviour`

```
public class CameraBehaviour : MonoBehaviour
{
    public MinMax CameraViewRange;

    private Single CalculateViewRange() { ... }
}

```

and have two class `ActionCamera2D` and `ActionCamera3D` derived from `CameraBehaviour`

```
public class ActionCamera2D : CameraBehaviour
{
    [MinMaxRange (2f, 5f)]
    public new MinMax CameraViewRange = new MinMax(2f, 5f);
}

public class ActionCamera3D : CameraBehaviour
{
    [MinMaxRange(20f, 50f)]
    public new MinMax CameraViewRange = new MinMax(20f, 50f);
}

```

as you can see, both the script has `CameraViewRange` with `new` keyword and has different `MinMaxRange` attribute attached on each script, so the limit is will be vary between this script but still using the same `CalculateViewRange` calculation as the parent script.

But it turns out to be not possible, in Unity at least, raising an error:

```
The same field name is serialized multiple times in the class or its parent class.
This is not supported: Base(MonoBehaviour) CameraViewRange

```
* `MinMaxRange` is a custom written attribute for property drawer.
* `MinMax` is a custom struct that store min and max value.

1. > + ~~So, how can I overcome / deal with this problem ?~~
    >     + No, you can't, it's the C# design pattern to prevent that.
    2. > + ~~Is my code pattern here is **`wrong`** ?~~
    >     + Yes.
    3. >
    4. > + ~~Or is this the C# and Unity limitations ?~~
    >     + It's just the C# and Unity Inspector design pattern.

thanks

# Answer
> 1 votes
Well after hours of debugging and searching other solutions, I think it's not possible to do that, I've encountered using `[NonSerializedAttribute]` and `[SerializeFieldAttribute]` but the behaviour is changed as it seems to be different instance with same name.

so the solution ?

1. > * Remove the field from parent class.
>     * Convert the `CalculateViewRange()` into `virtual`.

code :

```
public class CameraBehaviour : MonoBehaviour
{
    protected virtual Single CalculateViewRange() { }
}

public class ActionCamera2D : CameraBehaviour
{
    [MinMaxRange (2f, 5f)]
    public MinMax CameraViewRange = new MinMax(2f, 5f);

    protected override Single CalculateViewRange() { CameraRangeCalculation }
}

public class ActionCamera3D : CameraBehaviour
{
    [MinMaxRange (20f, 50f)]
    public MinMax CameraViewRange = new MinMax(20f, 50f);

    protected override Single CalculateViewRange() { CameraRangeCalculation }
}

```
2. > * Remove the field from child class.
>     * Basically, just give up about the limiting range feature, it seems not possible.

code :

```
public class CameraBehaviour : MonoBehaviour
{
    public MinMax CameraViewRange;
    private Single CalculateViewRange() { }
}

public class ActionCamera2D : CameraBehaviour
{
    ...
    // 2D Specific Functions
    ...
}

public class ActionCamera3D : CameraBehaviour
{
    ...
    // 3D Specific Functions
    ...
}

```
3. > Bonus If you need this not paricularly for Unity / Unity Inspector / Unity Editor, you can use Property with the same name and then explicitly declare the `get; set;` to update the parent's field value.

code :

```
public class ParentClass
{
    public Single FooBar;

    private Single MultiplyFooBarBy2()
    {
        return this.FooBar * 2;
    }
}

public class ChildClass : ParentClass
{
    public Single FooBar
    {
        get => base.FooBar;
        set => base.FooBar = value;
    }
}

// OR which is possibly compatible with Unity Inspector [using attributes]

public abstract class ParentClass
{
    protected abstract Single FooBar { get; set; }

    private Single MultiplyFooBarBy2()
    {
        return this.FooBar * 2;
    }
}

public class ChildClass : ParentClass
{
    //[Range (0f, 1f)] // Untested, but should do
    public Single FieldOfFooBar;

    protected override Single FooBar
    {
        get => this.FieldOfFooBar;
        set => this.FieldOfFooBar = value;
    }
}

```

EDIT :

> Well I should've realized that it's not possible at the very begining.
> You can't override fields. And expecting the parent will get the child's value.

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


# Question
Title: Phaser is not loading the same map created in Tiled software
I have created a sample map using the tiled software. Then tried to load the same on a webpage using phaser.js. But I am not getting the proper result. Is there any mistake in my code or something wrong with the library.

```
    <!DOCTYPE html>
<html>
   <head>
      <title>Basic Platformer game</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <script src="js/phaser.min.js"></script>
      <script src="js/phaser.js"></script>

   </head>
   <body>
      <div id="phaser-game"></div>
      <script type="text/javascript">
         (function() {

            var game = new Phaser.Game(
            800, 600, Phaser.CANVAS, 'phaser-example',
            { preload: preload, create: create, update: update, render: render });

            function preload() {
    game.load.tilemap('map', 'background.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tile2', 'floor2.png');
    game.load.image('player','bot2.png');

}

var map;
var layer;
var marker;
var player;
var currentTile;
var cursors;
var curser;

function create() {
    game.stage.backgroundColor = '#787878';
    game.physics.startSystem(Phaser.Physics.P2JS);

    map = game.add.tilemap('map');

    map.addTilesetImage('floor2','tile2');
    currentTile = map.getTile(0, 0);
    layer = map.createLayer('Tile Layer 1');

    player = game.add.sprite(20, 20, 'player');
    game.physics.p2.enable(player);
    player.body.fixedRotation = true;

    layer.resizeWorld();

    marker = game.add.graphics();
    marker.lineStyle(2, 0x000000, 1);
    marker.drawRect(0, 0, 20, 20);

    cursors = game.input.keyboard.createCursorKeys();
    game.camera.follow(player, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1);
    game.physics.arcade.enable(player);

      </script>
   </body>
</html>

```

And the JSON file is-

```
    { "height":12,
 "layers":[
        {
         "data":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228],
         "height":12,
         "name":"Tile Layer 1",
         "opacity":1,
         "type":"tilelayer",
         "visible":true,
         "width":19,
         "x":0,
         "y":0
        }],
 "nextobjectid":1,
 "orientation":"orthogonal",
 "renderorder":"right-down",
 "tileheight":30,
 "tilesets":[
        {
         "columns":19,
         "firstgid":1,
         "image":"floor2.png",
         "imageheight":385,
         "imagewidth":592,
         "margin":0,
         "name":"floor2",
         "spacing":0,
         "tilecount":228,
         "tileheight":30,
         "tilewidth":30
        }],
 "tilewidth":30,
 "version":1,
 "width":19
}

```

# Answer
Your code by itself looks alright, but it's hard to tell what the problem is without the source images/tilemap files.

Two possibilities come to mind:

1. You have margin/spacing in between of your tiles in the tileset image.
    * The fifth and sixth parameter of the "addTilesetImage" need to be set to the margin and spacing in between of your tiles (which you probably already configured in Tiled).
2. The tileset image isn't properly exported from Tiled, and not 32x32.
    * Phaser assumes your tiles are 32x32 if you don't pass any dimensions to addTilesetImage and the dimensions are not contained in the json file.

See https://phaser.io/docs/2.6.2/Phaser.Tilemap.html#addTilesetImage for more info.

I would've commented to ask for more info / source files, but lack the rep to do so :).
> 0 votes

# Answer
At the very bottom of your json file, I see:

```
"width":19

```

But when I count the tiles across your floorplan, I get 20.

This off-by-one difference can create the kind of row stride error I described in the comment earlier:

> See how all the right features seem to be present, but shifted from row to row to make diagonal lines? That's a symptom that your **row stride is wrong**.
>
> If the diagonals travel to the left from one row to the next, your're reading too many tiles from one row, running into the next, so that it starts midway-along when its turn comes, as though it started too early.
>
> If the diagonals travel to the right, then you're not reading enough tiles from the row, and some of the leftovers get added to the next row, nudging it over so it starts late.
> 1 votes

---
Tags: javascript, tilemap, phaser, tiled
---


# Question
Title: Unity or Monogame or Gamemaker 2 for an experienced application developer?
So i know this question has been hammered down several times but please bear with me.

I used to be a C# .Net application developer but i am no longer employed, i am pretty good at C#.

I want to get into serious game development and i dunno where to start, i used to work with unity occasionally which is a very little and i kinda find it clunky, like it works but somehow it does not feel right and feels kinda clunky. But it works with tiled map editor without much of a hassle.

I Remember using Game maker studio when i was back in college and i found it very good, its a breeze to work with and even have its own tiled map editor, even seems to have some good tutorials, the only con is its price.

I was initially inclined towards Monogame cause of my C# background, but i neither have time nor money and resources to support me for long enough time to be able to code every single thing from scratch and i am kinda in a pretty bad situation overall right now. It just takes too much time to do anything even to make it work with a tiled map editor, and there are very few tutorials or documentation to start with.

It seems like the only option for me is Unity at the moment, cause of ease of access and how easy it is to work with tiled map editor and lots of tutorials.

which one do you guys think is good overall?

Please keep in mind that i am currently unemployed and have very little resources to support myself, and i am a programmer so i don't even know how to compose music and do art for the game and i'd prefer if it provides some asserts to be used so i wont waste time in learning stuff when i cannot afford to spend time.

I will eventually learn them but not now, its not happening now so i prefer something that comes with some sorta free asserts that can be used (mainly music and art), I mean does it even matter if all i am trying to do is earn a decent minimum living?

I just want to make simple 2D NES/Snes style games with multiplayer support.

Thank you.

# Answer
> 1 votes
I have a similar background (experienced software developer, limited art skills, limited budget) and my first impression of Unity was similar to yours, so perhaps I can offer some insight.

### Pricing and platforms

Comparing the three options you presented, I'm inclined to agree that Monogame is not the right choice for a one man shop with limited resources. There's a lot of work to be done up front, and you'll need to be able to buy assets and extensions, so I'll focus more on the two alternatives.

I don't have any personal experience with GameMaker, but looking at the website, it appears to be reasonably close to Unity in terms of available assets (some are available on both stores for the same price) and multiplatform support.

However, the pricing models are quite different.

For **desktop and mobile** platforms, you're looking at

* a $399 upfront investment for Gamemaker Mobile (permanent license) or
* $35 a month (minimum 12 months, i.e. $420) for Unity Plus.

Another thing to consider if you're interested in the mobile market is that Unity comes with monetization support out of the box.

If you want **console support** (Xbox One, Playstation 4), GameMaker is $799 a year for one platform or $1500 a year for both while a Unity Plus license covers all platforms, including PS Vita and several Nintendo systems which GameMaker doesn't support at all.

GameMaker for **Desktop only** is surprisingly affordable ($99 for a permanent license), but I don't know if that's a viable market for what you're planning.

### Workflow and engine capabilities

As a tool specifically designed for 2D games, GameMaker's UI and workflows are arguably more streamlined and the built in support for e.g. tilesets, movement patterns and bitmap editing is commendable. I'm not so keen on the domain specific scripting language, but others might disagree.

Unity relies on add-ons or external programs for some of these functions. Some "no brainer" tasks require a bit more effort and the learning curve is generally steeper. On the plus side, the engine offers a variety of features that would be considered out of scope in a pure 2D environment, but are nonetheless very useful. I'll also add that extending the editor is quick and painless.

Looking at featured projects, there's a tendency for GameMaker projects to feature a retro "pixel art" aesthetic while most Unity 2D games incorporate high resolution sprites or toon shaded meshes. This seems in line with the tools and features offered.

Overall, it comes down to preference. I don't see one option as superior.

### Conclusion

In the end, it comes down to what platforms you are targeting.

For **Desktop only**, **GameMaker** has what you need at a very reasonable price. Leftover money is better spent on assets than on advanced engine features.

If you're aiming at **mobile** platforms, I'd go with **Unity** for the simple reason that you get the option to expand to any other platform (e.g. handheld consoles) at no additional cost.

For **consoles**, **Unity** is my clear favourite. You save about $1100 a year compared to a GameMaker license. Spend a quarter of that on tools and extensions and you've got a pretty decent environment.

---
Tags: unity, 2d, monogame, game-maker
---


# Question
Title: Finding out which Panel was clicked in function
I have a panel with 10 sub panels in it. I am using Event Trigger to intercept the messages from these sub panels OnPointerDown event calls some function in the some script of an Game Object.

Is there a way to know in the function which of the sub panels was clicked. That way I can use the same function for all the sub panels or should I make individual function for each of the sub panels.

# Answer
```
PointerEventData.pointerPress returns The `GameObject` that received the OnPointerDown.

```

So you can do something like this :

```
OnPointerDown(PointerEventData e)
{
  Debug.Log(e.pointerPress.name);
}

```

Edit to answer the question in the comments. You can make the function you are calling in the event trigger require a `BaseEventData` argument. Then you can cast that argument to a `PointerEventData` like in the following example :

```
public void test1(BaseEventData data)
    {
        PointerEventData e = data as PointerEventData;
        Debug.Log(e.pointerPress.name);
    }

```
> 1 votes

# Answer
The easiest way I see is, To attach a small script on each one, when clicked it will call a function and pass as parameter an index indicating which sub panel was clicked.

There is probably a better/more optimized way to go about it if you have many panels, but in the range of 0-10 I think it can work well.
> 0 votes

---
Tags: unity, events
---


# Question
Title: Making objects larger than 1 tile in a pixel art tile map
I'm working on a pixel game, and started creating a little town to test some stuff.

My question is whether there is a way to create bigger objects without having to split them into several parts.

My grass tiles and similar are 16 pixels wide, but how do I build a house for example, I want to stay at 16 pixels with all objects but the house would be far too small this way.

I know I can build it by creating the parts separately, but is there an easier way?

# Answer
You can use any size you want. The software you are using should be able to crop images in proper tiles (16x16 in your case)

This for example can be used in map editors like "Tiled" without any issues. https://opengameart.org/content/mage-city-arcanos
> 2 votes

# Answer
When I was part of a team which developed a tile-based 2d engine, we ran into the same problem. Placing a tree in a way that it layered correctly with player sprites required to place 3 tiles on 3 different layers. This was very tedious and error-prone.

But then we added the ability to add "oversized" tiles. We allowed tiles on the sprite layer to be larger than our tilesize (32px). The lower border of these tiles was alligned with that of normal sized tiles, but the upper border could exceed the tile grid. We ensured the correct draw order by painting the sprite-layer from top to bottom.

This made it possible to place high objects like trees with a single click and have them layer correctly with moving objects.

But there might also be situations where you have a multi-tile object which you don't want to layer with moving objects. A large pond, for example. In this case it is very useful when your map editor allows you to select not just a single tile from your tile palette but allows you to drag a rectangle on your tile palette and then place all the tiles in that rectangle with a single click. This was also useful in combination with oversized tiles. After a while the art department found that 2 tile wide trees allowed more aesthetically pleasing maps than 1 tile wide trees. So a tree now consisted of 2 ovesized tiles, both 96 pixels high. Allowing to multi-select from the tile palette also allowed to place them with a single click.
> 2 votes

---
Tags: pixel-art
---


# Question
Title: How to get time since frame start in Unity for loading purposes
I am building a big world (1000+ game objects). It takes 2s on the device. I am doing it in the background (the world is hidden until fully loaded). I have figured out that I can maintain the FPS of the active scene by switching to coroutines and making `yield return null;`.

The main issue is when to fire `yield return null;`. If I do it too often, then it will slow down the loading. If I do it too rarely, it will reduce FPS on low-end devices.

My idea is simple to detect how much milliseconds have passed since the start of the frame and fire `yield return null;` just after I have spent for example 12ms (to leave some time to render everything else and maintain something near 60FPS).

However, I can not find an efficient way of getting the time since frame start? Unity should have something as the async loading of assets seems to consume just right time to maintain stable FPS.

# Answer
I'll usually use System.Diagnostics.Stopwatch for this.

```
IEnumerator AsyncWorkCoroutine(float millisecondBudget) {
    var watch = new System.Diagnostics.Stopwatch();
    bool workComplete = false;

    long tickBudget = (long)(System.Diagnostics.Stopwatch.Frequency
                             * millisecondBudget/1000f);

    while(workComplete == false) {
        watch.Restart();
        while((workComplete == false) && (watch.ElapsedTicks < tickBudget))
           workComplete = DoSomeWork();

        yield return null;
    }
}

```

But if you're willing & able to work on the bleeding edge Unity versions, you should try looking into the **Job System** to see if it can streamline this for you, or help you take advantage of more cores.
> 8 votes

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


title: Resize big sprites in good way

text:
# Question
Title: Resize big sprites in good way
How to resize 2D sprites in the size of like *400px* to *64px* or *32px* in a way that doesn't make it look pixelated and weird?

# Answer
If you're using Photoshop, and you want resize a sprite, the best way to do it is by going to File -\> Save for web.

And then play with this:

On Image Size, put the desired new width and height and play with the Quality, for resizing Pixel Art Sprites I suggest to use "Nearest neighbor". Once you input the desired size and quality you'll be able to preview the output and then save your image.
> 0 votes

---
Tags: graphics, sprites, pixel
---


# Question
Title: How to use CC photos from Wikimedia properly?
Here is the situation: I want to create a (perhaps commercial) offline trading card game. Like Magic: The Gathering. My game will be about animals. So I want to use CC photos from Wikimedia as an art for each card.

Photos on Wikimedia are under different CC licenses (CC BY 2.0, CC BY-SA 2.5, CC BY-SA 3.0, CC BY-SA 4.0 and so on). I'm not a lawyer, I just want to try to create a game, so before I start I want to be sure:

1. Can I use such photos in a commercial product?
2. How to properly attribute each photo? According to Wiki hints, the usual photo should be attributed in this way:

"By **AUTHOR NAME** from **CITY NAME**, **COUNTRY NAME** \- **PHOTO CAPTION** Uploaded by **USERNAME**, CC BY 2.0, **FILE URL**"

It's not enough space on the card for so long text. Can I print a short text on each card (like "Photo by **AUTHOR NAME**") and also make the web page with full credits for all cards' arts? Or credits should be printed and distributed with each booster?

Thanks in advance!

# Answer
## Commercial Use:

It depends. Some of the permit commercial use, some do not. Generally speaking, if the license type has `NC` in it, the answer is no. Even if it does not have `NC` there may be other restrictions that effective prevent you from you using it in your situation (for instance derivative uses). You'll need to check the license of each & consider your application.

## Attribution:

According to the faq on attribution there is not a set standard:

> CC licenses have a flexible attribution requirement, so there is not necessarily one correct way to provide attribution. The proper method for giving credit will depend on the medium and means you are using, and may be implemented in any reasonable manner. Additionally, you may satisfy the attribution requirement by providing a link to a place where the attribution information may be found.
>
> While the attribution requirements in the license are the minimum requirement, we always recommend that you follow the best practices for the kind of use you are making.

You can read more about the best practices on attribution; here's a summary:

* identify the specific CC license in use
* retain any other legal (copyright, etc) info that was with the orignal work
* double check the details of the legal code for the CC license in use
* make sure your attribution is reasonable and suited to the medium you're working with

## Derivatives:

You didn't ask about this, but it's something you need to consider. The odds are likely that you will need to modify some of the photos in some way to fit your card format (that is to say, you're probably not going to find a bunch of photos at the right size & resolution, all using the same color profile, that you can use straight up). Combining and adapting CC material is another area where you'll need to tread carefully:

> Whether a modification of licensed material is considered an adaptation for the purpose of CC licenses depends primarily on the applicable copyright law. Copyright law reserves to an original creator the right to create adaptations of the original work. CC licenses that allow for adaptations to be shared—all except BY-ND and BY-NC-ND—grant permission to others to create and redistribute adaptations when doing so would otherwise constitute a violation of applicable copyright law. Generally, a modification rises to the level of an adaptation under copyright law when the modified work is based on the prior work but manifests sufficient new creativity to be copyrightable, such as a translation of a novel from one language to another, or the creation of a screenplay based on a novel.

Basically, it hings in part on copyright law which in turn can get complicated, especially if the jurisdiction extends beyond a single country. Make sure the derivatives portion of the license fits your needs.
> 1 votes

# Answer
You could use public domain images instead, and then you won't have to worry about any attribution. There should be plenty of public domain images of common animals.

Pixbay is one of many resources for public domain images. https://pixabay.com
> 0 votes

---
Tags: licensing, card-game
---


title: Side of collision with rotation

text:
# Question
Title: Side of collision with rotation
I have 2 rectangles and I want to know if its a `length` collision or a `breadth` collision. I will also need to know the rectangle that's acting as pivot. I have made a small illustration. Here, V2 is the pivoting rectangle.

# Answer
You could calculate the distance from each point to each line segment.

For both rectangles it would be 8 points and 8 lines, but you only need to test between points and lines on separate rectangles. Once you find the shortest distance from point to line, the rectangle that holds the point is the pivoting rectangle, and you can use the line's index to determine which side it's on.

Here is some material on calculating the distance between a point and a line.

> https://en.m.wikipedia.org/wiki/Distance\_from\_a\_point\_to\_a\_line
> 0 votes

---
Tags: c++, collision-detection, sfml
---


# Question
Title: calculate force betwen two objects like angry birds game
I'm trying to make a game like angry birds. in the game materials break and destroy based on force they receive. really what is the right or best way to implement it in unity?

thank you for helping.

# Answer
> 1 votes
In a Unity collision handler, you can check collision.Impulse to get a vector representing the influence the bodies are imparting to each other to brake the movement / rebound away from one another.

The magnitude of this vector is a good measure of how "intense" the impact is.

It's measured in Newton-seconds, representing the instantaneous change in momentum of the body, so it incorporates both **velocity** (more drastic change in motion = more impulse) and **mass** (heavier objects = more impulse)

---
Tags: unity, physics
---