# Question
Title: How to combine tiles in a procedurally generated level in 2D tile based maps?
I am developing a 2D tile-based top-down game. It is currently instantiating square objects with a sprite renderer to procedurally generate the map.

Each floor and wall is a 1-unit wide object.

I have two issues with that:

* The memory usage is quite high and it is not efficient (generating maps that are more than 300x300 become really slow)
* There are lights glitches when I have multiple lights in the scene. The borders of the squares become visible as seen in the picture:

* Is it possible to combine all my static elements (floor and wall tiles) in a Mesh object, or another adequate object for that?
* The floors items do not have colliders, as the walls have a box
collider. Does it cause an issue?

# Answer
> 0 votes
for second and third question: try following this aproach . The post make reference to colliders but you can use it with tiles. Essentialy you can use big rectangular quads to enclose the same tiles like this:

Using larger quads reduce the tiled light effect.

---
Tags: unity, 2d, lighting, tilemap, optimization
---


title: Modifying an array of quaternions

text:
# Question
Title: Modifying an array of quaternions
I have written the following function to inter-change 2 specific elements of an array of quaternions:

```
private void ChangeRotations(Quaternion[] rotationsArray)
{
    Quaternion bone1Rot = rotationsArray [(int)Bone1ID];
    Quaternion bone2Rot = rotationsArray [(int)Bone2ID];

    Quaternion temp = bone1Rot;
    bone1Rot = bone2Rot;
    bone2Rot = temp;
}

```

But when I use `Debug.Log` to see if this has taken effect, I realize that the 2 array elements are unchanged.

What am I doing wrong here?

# Answer
You aren't doing anything with `rotationsArray`, you are just swapping the values in `bone1Rot` and `bone2Rot` around.

You need to actually modify the array, something like:

```
private void ChangeRotations(Quaternion[] rotationsArray)
{
    Quaternion temp = rotationsArray [(int)Bone1ID];
    rotationsArray [(int)Bone1ID] = rotationsArray [(int)Bone2ID];
    rotationsArray [(int)Bone2ID] = temp;
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Can instantiated objects have different material/texture?
While I have some experience with simple 2D games, I am new to more process-demanding 3D games. One basic question that has been concerning me recently and for which I am having difficulties to find a proper detailed answer, is the following.

I understand that when we instantiate an object, we are saving memory because the instantiated copy does not have to save mesh memory (like vertices' position, UV cood and normals). So, the instantiated copy only needs to save a transformation matrix in order to properly position, scale and rotate the mesh structure they share with the original mesh.

But can the instantiated copies have different texture or material from the original mesh from which they were instantiated? If so, then it means the instantiated objects actually save with themselves more than transformation matrices. I would love to read more on that, so suggestions are welcome.

# Answer
since you admittedly don't have much experience with 3D and (presumably) OpenGL, I'll give you a "bird's eye" overview of the process.

I'll do my considerations about OpenGL, but the basic reasoning yields for other APIs too.

When you render something with *a modern version* of OpenGL you create objects that will reside into the GPU memory, and then mostly operate on them by reference.

Let's say you want to create a cube with a simple diffuse texture, what you will do is:

1. load the mesh for the cube (or other object) in your program *\[the mesh now resides in your "main" memory and can be directly accessed by your code, and you can do C/Python/whatever stuff on it\]*
2. load the previously loaded mesh into the GPU (by creating a buffer object in OpenGL, and filling it with the mesh data). After this operation, you have 2 copies of your mesh: one in the CPU's memory, and one in the GPU's.
3. release the memory associated with the mesh data in your CPU (*very loosely speaking... pass me this ;-)*), keeping only a reference (nothing more than an int!) of the mesh that still resides in the GPU memory *\[now you cannot "touch the data directly anymore, but you can tell OpenGL/DirectX what to do\]*
4. repeat steps 1. 2. and 3. for the UV (and if required normal) coordinates.

A similar sequence is involved with the texture:

1. load the texture data, e.g. the png/jpg file **\[disk -\> CPU memory\]**
2. create and load a texture in the GPU **\[CPU memory -\> GPU memory\]**
3. release the texture memory, and use the texture by reference using the id returned to you by OpenGL **\[GPU\]**.

The interesting part is that from now you can instantiate how many textures/meshes you want *without spending extra memory to hold each copy*.

It's not very different from what people do in 2D all the time, just with one extra layer between the CPU and the screen: in 2D graphics (e.g. a game rendered with tiles), you load an image, keep it in your CPU memory and then just "copy and paste it" on the video memory by blitting it repeatedly.

Doing 3D graphic you have an extra step, where you load the mesh/texture/whatever in the GPU and get a pointer of sorts for them as a "receipt", before being able to render anything.

About the details of your question:

> While I have some experience with simple 2D games, I am new to more \> process-demanding 3D games.

OpenGL/DirectX and other 3D frameworks are quite often used for 2D games too, and as soon as you get a good grasp of them you'll see why :)

> I understand that when we instantiate an object, we are saving memory because the instantiated copy does not have to save mesh memory (like vertices' position, UV cood and normals). So, the instantiated copy only needs to save a transformation matrix in order to properly position, scale and rotate the mesh structure they share with the original mesh.

100% true.

> But can the instantiated copies have different texture or material from the original mesh from which they were instantiated?

Yes! Unity (and most likely UE) treats the data in a very granular way and allows:

* the same model to be instantiated with different materials
* the same material to be used on different models
* the same texture to be used on different materials
* etc...

and it does this, to mimic the actual memory layout in the GPUs: the "instantiated objects" are just **very complex**, **very high level** constructs based on the same basic bricks used by the GPU to store information, bricks which *get used and reused as much as possible* to limit memory consumption/transfer (and improve performances).

Even a material, for instance, is not a "basic object", in the sense that is actually an OpenGL shader coupled with some textures and other additional data, providing opportunities for more memory/performances optimization.

Therefore, when you instantiate 100 objects using the same model (same geometry), with 100 different 3D transforms (each object will be at a distinct position, and will likely have a unique orientation and scale) and one of two materials (i.e. red and blue, which is a realistic example for red/blue tanks in a "Risk!" game), you are actually using:

* a single shader
* a single copy of the same 3D model (vertices, normal, UV) as 3 buffer objects (arrays of data in the GPU...)
* 100 different modelview matrices (one for each tank).
* two textures

this is a very quick and cursory account, mind you, but it's still reasonably accurate, and yields for low level APIs, like OpenGL/DirectX and for "complex" frameworks/editors like Unity and UE (basically because the hardware they are running on, the GPU, is the same in both cases, and this leads to the existence of what can be seen as a *loosely* "right way" to program it).

Hope this helps!
> 10 votes

---
Tags: opengl, textures, gameobject, materials, instancing
---


title: glDrawElements Crash

text:
# Question
Title: glDrawElements Crash
This is the "init" code of the Renderer class:

```
glGenBuffers(1,&_idVBO);
glGenBuffers(1,&_idEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,_idEBO);
glBindBuffer(GL_VERTEX_ARRAY,_idVBO);

GLint lUV       = glGetAttribLocation(_SID,"inUV");
GLint lPosition = glGetAttribLocation(_SID,"inPosition");

glEnableVertexAttribArray(lPosition);
glEnableVertexAttribArray(lUV);
glVertexAttribPointer(lUV, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glVertexAttribPointer(lPosition, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat)));

```

...and this is the "flush" function:

```
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,_idEBO);
glBindBuffer(GL_VERTEX_ARRAY,_idVBO);
glBufferData(GL_ARRAY_BUFFER,_lVBO*sizeof(GLfloat),_pOriginVBO,GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,_lEBO*sizeof(GLuint),_pOriginEBO,GL_STATIC_DRAW);

glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);

```

The glDrawElements call crashes with error code c0000005, which is caused by memory acces violation i.e. bad pointers. But I do not understand where the problem is. Any ideas? Thanks in advance...

# Answer
One (or more) of your gl calls previous to glDrawElements is not being passed correct information. So when you finally get to glDrawElements it crashes on you because that information is not set properly. Here is what I do to debug that issue:

After each gl call place a `ChecKGLError();` Here is that function:

```
void _CheckGLError(const char* file, int line);

#define CheckGLError() _CheckGLError(__FILE__, __LINE__)

void _CheckGLError(const char* file, int line)
{
    GLenum err ( glGetError() );

    while ( err != GL_NO_ERROR )
    {
        std::string error;
        switch ( err )
        {
            case GL_INVALID_OPERATION:  error="INVALID_OPERATION";      break;
            case GL_INVALID_ENUM:       error="INVALID_ENUM";           break;
            case GL_INVALID_VALUE:      error="INVALID_VALUE";          break;
            case GL_OUT_OF_MEMORY:      error="OUT_OF_MEMORY";          break;
            case GL_INVALID_FRAMEBUFFER_OPERATION:  error="INVALID_FRAMEBUFFER_OPERATION";  break;
        }
        std::cout << "GL_" << error.c_str() <<" - " << file << ":" << line << std::endl;
        err = glGetError();
    }

    return;
}

```
> 2 votes

---
Tags: opengl, c++, graphics
---


title: Unity Renderer.bounds issue?

text:
# Question
Title: Unity Renderer.bounds issue?
I would like to make rend.bounds.max.y be always equal to 20 on collision no matter what, using the script below. But it seems that I can't set it manually and the script has no effect on my GameObject.

Script:

```
public class ClassKey : MonoBehaviour{

void Start()
   {
       rend = GetComponent<Renderer>();
   }

void OnCollisionEnter(Collision col)
   {
       //more code
       rend.bounds.max.y = 20;
       //more code
   }
}

```

What I want to achieve: "Change `rend.bounds.max.y` to 20 when colliding (and keep the new value forever), and let `rend.bounds.max.x` and `rend.bounds.max.z` vary freely when colliding"

The problem: Renderer.bounds is read only... How can I go around this?

# Answer
> 0 votes
Modifying the bounds is impossible for a good reason, which is that the bounds is just an AABB (i.e. non-rotated box) which encloses the entire sprite or mesh. It just shows where, in the form of a box unaffected by rotation, the mesh/sprite reaches. Kind of like a connect the outer dots with lines aligned with the x, y and z axis and is thus just a way of representing it.

Besides, the 'max' you are trying to modify represents the highest coordinate of the bounding box, in other words, generally the right upper corner.

If you intend to actually keep the object at its position, modify transform.position instead.

There's one more thing though: you are probably trying to 'undo' the effect of any collision response. Doing that in this way won't work, because on collision the position is not (necessarily) directly modified. Rather, the velocity and acceleration are modified which in its turn modify the position in subsequent (fixed) updates. If you really want to keep it at y = 20 at all costs, you probably want to try doing this in Update or LateUpdate (the latter makes sure that it is applied after other modifications).

# Answer
> -2 votes
In unity, a vector is implemented as a struct as opposed to a class. One thing this means is that you can not change individual values in a vector by assigning directly as you have done. You need to replace the entire vector with a new one. So:

```
var old = rend.bounds.max;
rend.bounds.max = new Vector3(old.x, 20, old.z);

```

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


title: How can I fix my audio? (prioritize)

text:
# Question
Title: How can I fix my audio? (prioritize)
**When two audio's are played at the same time... the sound is cancelling out. How do I fix this weird phenomenon?**

I have some code where there is audio on button click **and** audio in ten second intervals (in a background service). I have the following code to stop the button audio when the ten second interval plays, and it works fine:

```
public static void myPop(Context context){
    AudioManager manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    if(!manager.isMusicActive()) {       //Only if there isn't any other audio playing
        MediaPlayer pop = MediaPlayer.create(context, R.raw.pop);
        pop.start();
    }
    else{
        Log.v(TAG, "Audio is already playing");
    }
}

```

This works fine, and it stops one audio from playing (pop) to let the other audio play (the one from the background service). Now, I am getting the issue when they both play at the same time. For example, when I tap the button at the **exact** same time as when the audio from the background service is about to start. When they are both played at the same time, the audio just gets cut off.

Is there any way to give a preference to the background service audio? Somehow say that: **If two audio pieces start at the exact same time, I want to let the background service audio to play.**

To think of this visually:

**I want to say that if I have the choice between apples and oranges, pick apples. AKA If I have two audio players playing at the same time, pick one (the apple).**

---

Image source

# Answer
> 1 votes
Each MediaPlayer can play only one audio at the same time (Remember, can you play multiple musics in your music player app?).
But if you want to play multiple sounds you should use SoundPool instead. There you can play sounds with higher priority too.

An example for SoundPool: link

Check this for playing it in background: link

---
Tags: java, android, audio
---


# Question
Title: Is there a terrain generation method where seed data is stored for each chunk instead of surface data?
I'm a web programmer but I do like the idea of working on games at some point. As an enthusiast, I'm curious:

Is there an accepted terrain building practice in which developers create a generation engine which accepts various seed values to control terrain in a non-random environment?

I'm thinking of a method of, instead of storing gigabytes of map data, just storing a couple of megabytes of seed data, different types of seed data values for each chunk of the map, allowing the client to dynamically generate the map of your desired "design" (Not random gen), with only building and structure component configurations to be saved as map data.

Is there a name for this? It seems like it would be a good method of keeping a game's file size small.

# Answer
It certainly is a good method for doing so.

I'm not sure this is exactly what you have in mind, but the PCG wiki describes something similar under "Dynamic World Generation". That name feels like a poor fit to me, so there could certainly be other names for it, but I'm not aware of any.

You might be able to find additional resources by digging around "compression" topics. Generating *specific* game data on the fly given a seed is essentially just very efficient, hyper-specialized compression.

Naming issues aside, this approach has been used for many years in places where you wanted to push around less data, for whatever reason. E.g. the demoscene often uses procedural generation techniques to keep files small.

What limits the applicability of the idea is that quite often, tight data/storage constraints are coupled to slower CPUs. E.g. it's not clear whether generating your worlds is a good idea on a mobile - it's hard enough to keep framerate up when you're *not* generating everything on the fly.
> 1 votes

---
Tags: terrain
---


# Question
Title: Why are textures always square powers of two? What if they aren't?
Why are the resolution of textures in games always a power of two (128x128, 256x256, 512x512, 1024x1024, etc.)? Wouldn't it be smart to save on the game's file size and make the texture exactly fit the UV unwrapped model?

What would happen if there was a texture that was not a power of two?

Would it be incorrect to have a texture be something like 256x512, or 512x1024? Or would this cause the problems that non-power-of-two textures may cause?

# Answer
> Why are the resolution of textures in games always a power of two (128x128, 256x256, 512x512, 1024x1024, etc.)?

As Byte56 implied, the "power of two" size restrictions are (were) that each dimension must be, independently, a power of two, not that textures must be square *and* have dimensions which are a power of two.

However, on modern cards and which modern graphics APIs, this "restriction" has been relaxed significantly such that textures dimensions can be, within reason, just about anything you like. However:

> Wouldn't it be smart to save on the game's file size and make the texture exactly fit the UV unwrapped model? What would happen if there was a texture that was not a power of two?

By ensuring the texture dimensions are a power of two, the graphics pipeline can take advantage of optimizations related to efficiencies in working with powers of two. For example, it can be (and absolutely was several years back before we had dedicated GPUs and extremely clever optimizing compilers) faster to divide and multiply by powers of two. Working in powers of two also simplified operations within the pipeline, such as computation and usage of mipmaps (a number that is a power of two will always divide evenly in half, which means you don't have to deal with scenarios where you must round your mipmap dimensions up or down).

It's true you "waste" some space this way, but the extra space is usually worth it for the tradeoff in render performance. Additionally there are techniques, such as compression or packing multiple images into a single texture space that can alleviate some of the storage waste.
> 55 votes

# Answer
> Why are textures always square powers of two?

Textures are not *always* **square** nor are they *always* **powers of two**. The reason why they *tend to be* powers of two is usually to increase compatibility with older video cards that imposed that restriction. As for non-square textures, that's not usually a problem. To summarize:

* Textures typically don't need to be **square** \- although DirectX does have a `D3DPTEXTURECAPS_SQUAREONLY` capability but I've worked with non square textures even in older hardware with no problems.
* Textures should be **powers of two** because many older graphical cards still require it. The reason for that restriction was so that they could perform some optimizations to the texture mapping operations. Most modern graphic cards don't have this restriction either.
> 18 votes

# Answer
It relates to graphics card optimizations. They've been designed to process them in that way. Most cards these days *will* allow you to load textures with dimensions that are not powers of two, but it will likely have a negative impact on performance. There is a good chance that when it loads it is actually going to be converted costing you load time and not saving any memory. Non-square textures are generally OK, as long as both their dimensions are powers of two.

One way of dealing with odd size textures is using a Texture Atlas. Basically, you place multiple textures together into a single texture and use the texture coordinates of your vertices to reference the particular image you need. This comes with additional performance benefits as well, because it allows to avoid state changes. A common use of this is placing all of the elements of the interface into a single texture, meaning that if you have batched up your interfaces vertices into a single buffer object, you can draw the whole thing with a single call, rather than switching textures many times and making a separate draw call for each one.
> 9 votes

# Answer
Graphics hardware is optimized for matrix operations, fragment operations and vector operations. Simply put square matrices are easier to deal with, as calculations may be done in blocks( called fragments ), hardware is optimized for block operations, which is why there are things like file buffers, the RAM blit does not blit to disk until a block has been populated. The same is true of graphics memory.

The frame buffer is composed of fragments which are square. For example in a screen with a resolution 800x600 and an RGB color space (0-255) there are 800x600 points with 3 bytes each channel there are a grand total of 3x800x600 = 1,440,000 bytes to address in the frame buffer. That means there are 1,875 addressable fragments that are 256x256x3 bytes. Because the texture data is square it makes it significantly easier to map from the GRAM matrix to the screen buffer matrix using bicubic scaling, where as if it wasn't square the bias for the longer side would take more time to calculate when it needed to be scaled.

Many graphics APIs will accept non square texture data, because they accept UV mapping coordinates as floating point data, however once it is sent to the GPU, padding is added to the texture data, because the actual proportions of the image do not change the mapping appears unaffected, however padding is added to the texture data, because the GPU likes addressing it as a perfect square.

So if a 100x1024 image is used, and image that is 1024x1024 is used which means 946,176 bytes are wasted. Even more so if compositing is to be done, because an alpha channel will need to be added in order to indicate that the padding data should not effect the composited texture.
> 8 votes

# Answer
The problem is that some hardware has limited support for textures that don't have power of two dimensions.

For example, look at the bottom of http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876%28v=vs.85%29.aspx and read footnotes 3 and 4 there.

> 3 At feature levels 9\_1, 9\_2 and 9\_3, the display device supports the use of 2-D textures with dimensions that are not powers of two under two conditions. First, only one MIP-map level for each texture can be created, and second, no wrap sampler modes for textures are allowed (that is, the AddressU, AddressV, and AddressW members of D3D11\_SAMPLER\_DESC cannot be set to D3D11\_TEXTURE\_ADDRESS\_WRAP).
>
> 4 At feature levels 10\_0, 10\_1 and 11\_0, the display device unconditionally supports the use of 2-D textures with dimensions that are not powers of two.
> 7 votes

# Answer
Modern hardware can (finally) cope with enabling wrap modes on non-power of two based textures, however non-power of two textures still tend to waste GPU memory as they tend to get padded up *along the width* by some hardware specific amount (either to some tile size or rounded up to the next power of two size that contains the texture).

As this is hardware dependant and the vendors generally won't get into the specifics of these details, the safest thing to do is to continue to use power of two dimensions for textures, so as not to waste GPU ram.
> 0 votes

# Answer
Our digital world works with binary numeration then to multiplay or divide by 2 a value you can "move" a value to left or right i.e.

```
<<  Left shift      x = 5 << 1    0101 << 1     1010     10
>>  Right shift     x = 5 >> 1    0101 >> 1     0010      2

```

Work with values "power of two" is more easy for a CPU.
> 0 votes

---
Tags: textures
---


# Question
Title: Text blits to screen at wrong y-coordinate
I have a program that is meant to scroll numbers/letters down the screen, like in the movie "The Matrix". When one of the columns reaches a letter in the user's name (obtained using user input), it freezes and all of the other characters in that column fade away. The program opens correctly,but will only print characters at a zero y-coordinate. This is the function which blits the letters and numbers to the screen. When I insert a print statement to check if it is printing the letter at the right y coordinate, it says it is incrementing by 32 pixels, like it should.

```
for sym in lst:
    symbol = matrixfont.render(sym, True, (0, 255, 0))
    print("Printing %s" % sym)
    print("x coord is %s and y coord is %s" % (x_coord, i))
    screen.blit(symbol, (x_coord * 30, i))
    pygame.display.update()
    i -= spacing

```

It just prints all of the letters at y-coordinate 0, but at the correct x-coordinates. Maybe the full code will help:

```
import time
import random
import pygame
pygame.init()

#----------DEFINING VARIABLES

user_name = input("Type in your first name.")
spacing = 32
symbol_list = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
               "V", "w", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
background_color = 0, 0, 0
master_list = []
matrixfont = pygame.font.Font("C:/Python34/Programs/MatrixSpeller/OCRAEXT.TTF", spacing)
pressedkey = pygame.key.get_pressed()
windowwidth = len(user_name) * 30

#----------SETTING UP WINDOW

screen = pygame.display.set_mode((windowwidth, 300))
pygame.display.set_caption('Name Speller')
screen.fill(background_color)

#----------DEFINING FUNCTIONS

def update_list(x):
    print("update list %s" % x)
    s = random.choice(symbol_list)
    lststring = master_list[x]
    lststring = s + lststring[:9]
    master_list[x] = lststring

def print_list(lst, x_coord):
    global i
    i = 0
    for sym in lst:
        symbol = matrixfont.render(sym, True, (0, 255, 0))
        print("Printing %s" % sym)
        print("x coord is %s and y coord is %s" % (x_coord, i))
        screen.blit(symbol, (x_coord * 30, i))
        pygame.display.update()
        i -= spacing

#----------MAIN LOOP

for n in range(len(user_name)):
    master_list.append("@")
    print("master list is %s" % master_list)

while True:
    for n in range(len(user_name)):
        update_list(n)
        print_list(master_list[n], n)

```

# Answer
> 1 votes
It's probably because you're subtracting from the y-coordinate `i -= spacing`. In pygame, the upper left of the screen is (0,0) and the lower right is (width, height) so you should have:

```
i += spacing

```

---
Tags: python, pygame
---


# Question
Title: GL_DEPTH_COMPONENT vs GL_DEPTH_COMPONENT32
I googled like crazy and checked the OpenGL documentations but I couldn't find out how the precision of a depth buffer created using `GL_DEPTH_COMPONENT` is chosen.

As far as I know the precision is implementation dependent. But how will the precision be chosen? Will it always use the highest precision possible or rather the fastest one? Or is no general answer possible?

Shoud I always go with `GL_DEPTH_COMPONENT32` instead?

# Answer
For a basic, unsized internal format like `GL_DEPTH_COMPONENT`, the implementation chooses a resolution. The implementation may only used the `format` and `type` parameters to choose an internal format, but otherwise the format is up for the implementation to choose.

`GL_DEPTH_COMPONENT32` is probably overkill, and as of 4.5, isn't a required format for OpenGL implementations to support (though 16 and 24 bit ones are). Consider that higher resolution depth buffers may not be as performant.

The exact requirements are documented in the OpenGL specification. On the 4.5 Compatibility spec, it is documented on section 8.5, page 230.
> 2 votes

---
Tags: opengl
---


# Question
Title: Why doesn't Array.Copy to mesh.verticies work in Unity?
I am rebuilding a mesh but something seems odd that I have to create a temp array just to hold the verticies rather than copy an array.

I'm not using list because this is used frequently and I do not want to resize list and instead just use height index boundary to prevent additional garbage collection from resizing lists.

**Doesn't work and results in no mesh showing:**

```
Mesh mesh = new Mesh();
//copy myVerticiesArray to mesh.verticies. myVerticiesArray
//length has null values above verticiesIndexHeight but array copy height set in Array.Copy()
Array.Copy(myVerticiesArray, mesh.vertices, verticiesIndexHeight);
[...] code to set UVs etc omitted
mesh.Optimize();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
this.GetComponent<MeshFilter>().mesh = mesh;

```

**Also doesn't work and results in no mesh showing:**

```
Mesh mesh = new Mesh();
//loop through built verticies array to mesh.verticies of correct size because myVerticiesArray
//length has null values above verticiesIndexHeight
mesh.verticies = new Vector3[verticiesIndexHeight];
for(int i = 0; i < verticiesIndexHeight; i++)
{
    mesh.verticies[i] = myVerticiesArray[i];
}
[...] code to set UVs etc omitted
mesh.Optimize();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
this.GetComponent<MeshFilter>().mesh = mesh;

```

**Works and renders mesh:**

```
Mesh mesh = new Mesh();
Vector3[] tempVerticiesArray = new Vector3[verticiesIndexHeight];
//copy built verticies array to temp array of correct size because myVerticiesArray
//length has null values above verticiesIndexHeight
Array.Copy(myVerticiesArray, tempVerticiesArray, verticiesIndexHeight);
mesh.verticies= tempVerticiesArray;
[...] code to set UVs etc omitted
mesh.Optimize();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
this.GetComponent<MeshFilter>().mesh = mesh;

```

# Answer
> 2 votes
Mesh.vertices is a property, not a variable. According to docs, it:

> Returns a copy of the vertex positions or assigns a new vertex positions array.

Which means, when you call mesh.vertices, you don't get the actual vertices, you get a copy of actual vertices. So when you copy something to this array, you actual modify the clone, not the actual data, hence it will have no effect. The third way is the correct way to modify mesh.

There is a reason it is done this way: the actual mesh data may be in GPU memory, so modifying it may be an expensive operation. You should first build you mesh locally, then update the actual data.

---
Tags: unity, c#, vertex, mesh
---


title: Libgdx actor bounds are wrong

text:
# Question
Title: Libgdx actor bounds are wrong
The Actor's boundaries are not centered at the ButtonText but I used the setBounds() method. The higher the Y position is, the less centered is the boundary. The weird thing is that i only created and added to the Stage one button but the screen shows two. When i click the top button, the bottom one is the one highlighted.

How can i fix that?

```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;

public class MyGame extends Game {
    Stage stage;
    @Override
    public void create() {
        stage=new Stage();
        FileHandle skinFile = new FileHandle("data/resources/uiskin/uiskin.json");
        Skin skin = new Skin(skinFile);
        TextButton sas=new TextButton("dd",skin);
        sas.setBounds(0, 500, 100, 100);
        stage.addActor(sas);
        Gdx.input.setInputProcessor(stage);
    }

@Override
public void dispose() {
    super.dispose();
}

@Override
public void render() {
    super.render();
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

@Override
public void resize(int width, int height) {
    super.resize(width, height);
}

@Override
public void pause() {
    super.pause();
}

@Override
public void resume() {
    super.resume();
}

```

}

# Answer
Your viewport dimensions are probably wrong, as stated in this post on the LibGDX forums. You should make sure that you are handling the `resize(width,height)` callback and setting up your stage's camera appropriately. A simple test would be to just set it to the same width and height as the argument values in the `resize()` function.

For instance:

```
@Override
public void resize(int width, int height) {
    camera.setToOrtho(false, width, height);
    camera.update();
    stage.getViewport().setScreenSize(width, height); // update the size of ViewPort
}

```
> 1 votes

# Answer
I think that the reason your buttons are drawing double is because as the window is loading, its sizes change. The first time it draws the button in one location and then draws it again in a new location after resizing.

To get past this drawing issue, you have to clear the background. OpenGl does not do this for you every frame. In your render method, the first call should be

```
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

```

Can't stress enough how important it is to update your viewport in the resize call. Otherwise, your clicks won't be translated from screen coordinates to stage coordinates correctly which is probably why your clicks work outside the button.

```
@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height);
}

```

If you still doubt that it's a viewport issue, try setting a ScreenViewport on your stage and see if that makes the button click in the correct area. ScreenViewports make your screen coordinates equal to stage coordinates. It is a horrible choice in most cases for a viewport in a game, but it may help you figure out if your issue is viewport related.
> 0 votes

---
Tags: libgdx, gui
---


# Question
Title: Mixing Perspective and Orthographic Projections?
*I'm going to start with some background, so jump to my question at the bottom for the TLDR version.*

**Problem:**

In a Japanese 4gamer article (english translation via Chev on Polycount) explaining some of the technology and design behind Guilty Gear Xrd (a highly-stylized, 2.5D, toon-shaded fighting game) they detail some of the challenges concerning the game's development. One of the challenges had to do with the use of an orthographic 2D collision detection system on top of 3D character models that were rendered in perspective. In short, rendering character models through a perspective projection would naturally result in the characters looking wider towards the edges of the camera. As such, at various points on the screen the visual representation of the characters would fail to accurately represent their 'hitboxes' and 'hurtboxes'.

**Example 1: Models using perspective projection.**

*The character model for Player 2 (orange) more closely matches his collision data because of his location towards the center of the screen.*

**Example 2: Models using orthographic projection.**

*Using an orthographic projection, characters are accurately aligned with their collision data regardless of position. However, the desired visual effects of perspective are lost.*

**Their Solution:**

The developers at Arc System Works solved this issues by creating a 'partial perspective' projection - a non-uniform mixture of perspective and orthographic (maybe parallel is more accurate) projections. On the horizontal axis, the camera's projection is said to be a '70% orthographic and 30% perspective' hybrid. On the vertical axis, the projection remains 100% perspective.

**Example 3: Models using 'hybrid' projection.**

*Mixing perspective and orthographic horizontally allowed them to preserve collision alignment and visual spacing (an important aspect in competitive fighting games). At the same time, the 'fully perspective' projection on the vertical axis allowed them to achieve extra visual depth when the characters jump.*

**My Question:**

**How would one go about achieving this kind of non-uniform, semi-perspective, semi-parallel camera projection?**

When I think about this, I can imagine a camera frustum with a *wide vertical FoV* and a somewhat more *narrow (but not necessarily parallel) horizontal FoV*. Is this the correct interpretation of what they're describing, or am I visualizing it incorrectly?

Typically how would you generate a projection/modelview matrix like this? Is there a way to ask libraries like OpenGL and Direct3D for non-uniform matrices like these, or is there some way to combine an orthographic matrix and a perspective matrix in a non-uniform way through matrix math?

# Answer
I suspect the method actually used doesn't actually rely on parallel projection and it only seems so through the approximation of the article writer and subsequent translation. The problem with bringing a parallel projection into this is you'll attenuate perspective, which is not what you may want. At any rate the method I describe here achieves the same desired effect, a consistent silhouette size no matter the on-screen position, to an extent that can be directed per object.

From top to bottom:

**Standard perspective projection:** All cubes have their vanishing point at the center of the screen

**The manipulated perspective:** Each cube has its vanishing point in the same place relative to the cube itself and each presents the same silhouette. The size change due to distance is unaffected.

**more manipulation:** All the cubes behave as if they were on the left.

It's done by shearing each object in relation to the camera, as seen in the following pic, so that each object "faces" the camera. The shear value to use to bring the vanishing point in the center of the object is the slope of the camera-object vector over the camera eye direction.

What follows assumes a camera looking horizontally and the perspective manipulation being in the horizontal plane but more general cases should work.

Consider three points on the horizontal plane (assuming a strictly horizontal correction), the character position, the camera position, and P being the projection of the character position on the camera eye vector (in the case of a fighting game, usually orthogonal to the gameplay plane).

The shear value is *(length of P to Character) / (length of Camera to P)*. The sign should be adjusted depending on which side of the camera the object is. The shear matrix is constructed by taking an identity matrix and changing the third row's first column value to the shear value. Then you just use *shearMatrix* * *worldMatrix* to position the object in the world rather than just *worldMatrix*.

The whole process can be applied independently for the vertical axis.

Note that you can weigh that shear value to attenuate how much it brings the vanishing point towards the object's center, and add an offset to it (like in the third cubes picture).
> 4 votes

# Answer
What you want is a curvilinear perspective projection matrix to correct for the perspective projection distortion.

aka barrel or pincushion projection: http://en.wikipedia.org/wiki/Curvilinear\_perspective

Basically, you distort the image with a projection that is the opposite of the distortion you *don't* want so it all comes out straight in the end. Mathematically, you can set the distortion on each axis independently for different effects.

This is common in real-world compound optics. Think telescope.

Unfortunately, I do not know of a way to make OpenGL calculate these for you, although you can use the math in the Wikipedia article to generate your own projection matrix.

I don't believe you will be able to concatenate these matrices, so you'll need to render dual-pass. Render your standard perspective view to an off-screen texture the way you normally would. Then re-render your offscreen texture mapped to a quad to the viewport using the curvilinear perspective projection to correct for the edge-of-the-screen curvature. That should get you the effect you want.

**Grid projected with barrel distortion:**
> 3 votes

---
Tags: mathematics, graphics, graphics-programming, projection, linear-algebra
---


title: Data oriented design in physics engine

text:
# Question
Title: Data oriented design in physics engine
I am new to data oriented design and I am currently developing a physics engine as a hobby project. I am really interested in data orinted design but I am not sure how to apply data oriented design to my physics engine. I am using Box2D as a reference and when I look at the source code, erin catto use linked list as a container for rigid bodies. The reason why he use linked list over array is stated here. This is what he stated at the forum

> I could use an array of body pointers. That would have worse cache performance. First you have to get the array element, then the element data. I would also need some extra logic to ensure the array is big enough.
>
> I'm not sure how I would use an array of bodies. If I resize the array, the pointers become invalid. I could return an index when you create a body, but then the array would have holes as bodies are freed. Traversing the body array would then involve extra logic to see if the body is allocated or destroyed. Also, it may be cumbersome for users to have to use an index rather than the object itself. If I return the current body pointer from the index, there will likely be many bugs where users hold onto that pointer and it becomes invalid.
>
> Finally, when islands are created the set of bodies is likely no to be contiguous in memory.

I will add that when the physics engine do a broadphase collision detection, It will return a list of collider pairs that will most likely located randomly at memory. From what I understand, you need something like handle so the data can be moved around in memory. With handle, you only need to move the last object to the slot that holds the deleted object. Using handle over pointer will add an extra level of indirection which results in more cache misses. So is it really beneficial to store a set of rigid bodies or their components as array?

Edit: I believe there are parts of physics engine that benefit from storing rigid body using array. For example the integration phase. But I am not sure if the benefits outweight the disadvantages.

# Answer
What you should optimize for is probably best shown in and around slide 40 of this presentation: http://www.slideshare.net/cellperformance/gdc15-code-clinic

The idea is to prevent the code from doing wasteful things with the CPU. Loading memory and then throwing it away is rather wasteful. So, naturally, you can reorder data to make better use of it. If you see a commonly used function that uses a certain set of variables, you'll want to make sure that they can be loaded on as little cache lines as possible by putting them close together and aligning them properly in memory.

With sufficiently complicated physics engines (ignoring fixed size particle system solvers), given that bodies contain lots of data and are rarely accessed sequentially, there aren't too many other optimizations to perform.

> So is it really beneficial to store a set of rigid bodies or their components as array?

One extra allocation (when compared to intrusive linked lists), addition time is almost always O(1) (certain additions will trigger a resize of the array memory, but only in the beginning and can be largely avoided), removal is O(1) (when using the swap-with-last trick, since order doesn't matter), iteration requires indirection, but it doesn't happen frequently. Intrusive linked lists - O(1) addition, O(1) removal, no extra allocations, no indirection on iteration.

Intrusive linked lists look better than arrays but arrays are not far behind for this use case. Expect the performance for both to be fairly similar. The Bullet physics engine uses arrays, by the way.

P.S. Plain linked lists (like std::list) would require one more allocation for each node (since it only accepts copies of values to store, and that's not an option with physics bodies, so pointers would have to be used) and require extra indirection, so I'd recommend avoiding those.
> 3 votes

---
Tags: physics, box2d, physics-engine, data-oriented
---


# Question
Title: Prevent button layout changing after one is removed?
I have a layout with four buttons in it. I end up removing one of the buttons using:

```
View v = (View) findViewById(R.id.ViewId);
                    ((ViewManager) v.getParent()).removeView(v);

```

The problem is, whenever I remove one button (which works fine), the other three buttons move out of place.

For example, I have a top right button, a top left button, a bottom right button, and a bottom left button. I choose to remove the top right button using the code I gave earlier. This causes **all the other three buttons** to move out of place.

I think this may be because of the xml, where it states things like:

```
android:layout_toRightOf

```

And I think that when I move one button, that statement in the xml has nothing to be to the right of, and so it goes of to a random position. Is there a way I can remove these statements without having to change the position of my buttons?

**Can I keep the buttons independent of each-other?**

# Answer
I think this is what you want. It makes the button invisible while still being used for layout. That way it will still take out the same space and not change your layout.

```
View b = findViewById(R.id.your_button);
b.setVisibility(View.INVISIBLE);

```
> 1 votes

---
Tags: java, android, gui
---


title: FPS camera up and down control

text:
# Question
Title: FPS camera up and down control
I am new to Unity. Now I am working with FPS camera. While pressing a key down arrow I want my camera to go down and again it come back to normal position. I am not getting any idea how to do it. Anyone, please help.

# Answer
> 1 votes
With "go down" do you mean "tilt down" (as in "you lower your head") or "move down" (as in "you go down on your knees")?

Anyway, both are done by manipulating the `Transform`-component of your camera.

`Camera.main.transform.Rotate(vector3);` rotates the currently active camera and setting `Camera.main.transform.position = vector3;` moves the camera to a different position. When you already have a script in your scene which controls the camera, you need to make sure that the scripts don't interfere with each other. We can not see your scene setup, so we can not help you with that.

To find out if a user is currently holding the down key, use `if (Input.GetKey("down")) {`

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


title: Swap buttons in layout

text:
# Question
Title: Swap buttons in layout
Say I have 4 buttons. I want to have button 2 always swap out with another button, randomly. So, when the user taps button 2, it should swap with another button (randomly).

Now, `button 2` is at the bottom right corner. So if the user taps button 2 again, it has the option to swap with the other three buttons. How can I achieve this?

I have already tried to make an array of the four values:

```
top_right, top_left, bottom_right, bottom_left

```

And have successfully had them swap, but it was very memory inefficient, and took a while.

# Answer
> 1 votes
I created a working demo using android's built-in buttons.

This is the main Activity class. Each button have the same onClick method buttonClicked().

```
List<View> buttons = new ArrayList<View>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Store the button to the buttons array for later.
    buttons.add(findViewById(R.id.button));
    buttons.add(findViewById(R.id.button2));
    buttons.add(findViewById(R.id.button3));
    buttons.add(findViewById(R.id.button4));
}

public void buttonClicked(View v) {
    // Remove the clicked button from it's frame layout parent.
    ViewManager p = (ViewManager) v.getParent();
    p.removeView(v);

    // Find another button randomly.
    Random rng = new Random();
    View v2;
    do {
        int i = rng.nextInt(4);
        v2 = buttons.get(i);
    } while (v2 == v); // Loop until you get a different button to swap with.

    // Remove the other button from it's frame layout parent.
    ViewManager p2 = (ViewManager) v2.getParent();
    p2.removeView(v2);

    // Now simply insert each button into the other buttons frame layout.
    p.addView(v2, v2.getLayoutParams());
    p2.addView(v, v.getLayoutParams());
}

```

This is how the layout looks like. I have each button in a separate frame layout which stay where they are with the buttons inside swapping which frame container they are inside.

If anything is unclear just ask.

# Answer
> 0 votes
If you want to use the solution you describe in your question, you can achieve it pretty easily with an `ArrayList`. This is assuming you have some sort of class for your buttons. If not, it might be a bit more cumbersome. The logic's the same though.

Create the initial list at the start of your class with the buttons:

```
ArrayList<Button> buttons = new ArrayList<Button>();
buttons.add(new Button("button1", xPos, yPos));
buttons.add(new Button("button2", xPos, yPos));
buttons.add(new Button("button3", xPos, yPos));
buttons.add(new Button("button4", xPos, yPos));

```

Then whenever the user clicks on one of them, run this:

```
// Make this equal the button the user clicks!
Button userSelection = GetClickedButton();

// Remove that button from the array.
buttons.remove(userSelection);

// Select a random button from the remaining ones.
Button toSwap = buttons.get(new Random().nextInt(buttons.size())));

// Now swap. Just swap the positions of the chosen buttons.
SwapButtonPositions(userSelection, toSwap);

// Add the removed button back to the list.
buttons.add(userSelection);

```

EDIT: I misread your question. I thought you wanted any button to be swappable, not just one of them. The logic for doing that is the same as above. Just have some way to tag the swappable button (like giving it a name) and run the code whenever it's clicked, rather than when any button's clicked.

---
Tags: java, 2d, android, graphics, software-engineering
---


# Question
Title: How can I optimize block rendering in an OpenGL game?
I am working on a game with blocky graphics -- similar to Minecraft. My world generation algorithm is similar to the Diamond-Square algorithm. The terrain was initially too rough and uneven, so I created a smoothing algorithm and allowed for the generation of hills.

Before the smoothing algorithm does its job, there are about 900 (+/- 100) cubes. After the smoothing algorithm finishes its task, there are about 1200 cubes. The resulting terrain is satisfyingly smooth and even, but the FPS decreases.

At first I couldn't create a 10x10 world without crashing. I figured it was because I kept binding and unbinding the same VAO for every block, so I changed that because every block uses the same VAO. It continued to lag and eventually crashed, so I tried to see if it was a problem with the terrain generation.

I found out that there was an infinite loop in the generation process, so I fixed that. It worked, but not well enough. It generated a 10x10 world and doesn't crash, but it runs at only 5 FPS, sometimes less. I then enabled back-face culling. The FPS improved a little, but only by 1-2 FPS. I still haven't implemented frustum/occlusion culling.

Is there an amazingly helpful culling/optimization technique I should know about?

# Answer
> 5 votes
You can check every block if it is exposed to air (=no other block) on any side or completely enclosed. Those which are completely enclosed shouldn't be rendered as they are not visible anyways. This shouldn't be done during every render call, you should only perform such checks if they are necessery. A possibility is that every surrounding block is checked if a specific block gets changed in any form (in Minecraft this is referred to as block updates). If you perform frustum culling at any time, I would advise you to only check for chunks and not every single block, since it would probably be overkill and only result in a performance loss compaired to rendering a few blocks that might be outside of the view frustum but inside a chunk that touches the view frustum.

Also it is really bad performance-wise to render every block with a seperate draw call. There are various different methods depending on your target OpenGL version. There are other resources though that cover this, take a look at this.

---
Tags: opengl, java, 3d, lwjgl
---


title: FSM AI design with no accept states

text:
# Question
Title: FSM AI design with no accept states
I'm new to game development and design, I've been looking forward to doing FSM AI design as it seems interesting to me, but I have a question that I see no answer for in the internet.

I've seen FSM diagrams from, for example, Pac-Man, and I noticed that the FSM has no accept states, it makes sense because the enemies are always active and in their different states (Wandering, chasing Pac-Man, running from Pac-Man, recovering in their house) What obviously stops the FSM of the enemies in Pac-Man is either Pac-Man dying or the level ending, but that seems more like brute force than a design decision.

I can imagine some FSM where the enemy just "dies" and that would be an acceptation state as it ended it's process, but again, in many sources I see that some designs just have no accept states. Could someone explain why is this?

Also, what would you do to prevent no-accept states FSM?

# Answer
When designing AI, you usually have behaviour for every possible situation while the character is alive. Even when they are just standing around, you usually want them to play some kind of animation, and of course wait for triggers to transition to another state.

In many cases, the final (accepting) state defines the logic of the character dying (or the vehicle exploding, or whatever you have). In more complex setups, you would then play an animation, maybe notify other objects, and then delete the object. In simpler games, like Pac-Man, you might not have an animation, but instead just call the object's destructor.

This means that often you do not have that accepting state as an actual object, and therefore it does not appear in a UML or FSM diagram, because it is merely an imaginary state. The transition to that state is deleting the object, where physically it does not have a state anymore. Theoretically, it is then in a state of non-existance.
> 1 votes

---
Tags: architecture, ai, fsm
---


title: Texture object and texture unit in GL

text:
# Question
Title: Texture object and texture unit in GL
As I understand texture usage consist of two parts

1. How to store this discrete data about texture internally. How much dimensions, channels, etc.
2. How to fetch/sample/filter

**The question relative to OpenGL are:**

q1: What parameters are stored in texture object (*glGenTexture*) and what parameters are store in texture unit (*glActiveTexture*) ?

q2: Does glTexParameter perform setup per texture object or per texture unit?

# Answer
> 4 votes
Q1. You would call glGenTexture() like so`glGenTextures(1, &handle)`. `handle` would now be an object containing an empty `GL_TEXTURE_1D, GL_TEXTURE_2D, etc..` that you can fill with a texture by using e.g. `glBindTexture(GL_TEXTURE_2D, handle)` followed by `glTexImage2D(GL_TEXTURE_2D, ...)`. I don't think there is a real limit to have many texture objects you could have.

There is a limit to how many you can use at the time however. You might have multiple textures per model in your scene, diffuse-map, normal-map, etc... so you would link each of your texture handles to their own texture slot so you can sample all of them at the same time.

Imagine each time your render something you can only use 8 colors at the time. You may create as many colors as you like and store that in GPU memory. But when it comes to rendering you can only select 8 color slots to render with and no more.

Example:

```
// Generate the textures
glGenTexture(1, &handle1)
glGenTexture(1, &handle2)

// Set the active texture slot to 0, bind handle1 to it and fill it with a texture.
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, handle1);
glTexImage2D(GL_TEXTURE_2D, ...)

// Set the active texture slot to 1, bind handle2 to it and fill it with a texture.
glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, handle2);
glTexImage2D(GL_TEXTURE_2D, ...)

// Get the uniform samplers from the shader program.
GLint sampler1 = glGetUniformLocation(program_handle, "sampler1");
GLint sampler2 = glGetUniformLocation(program_handle, "sampler2");

// Set sampler1 to sampler from texture slot 0 and sampler2 will sample from texture
// slot 1.
glUniform1i(sampler1, 0);
glUniform1i(sampler2, 1);

```

Q2. Let me quote this page: https://www.opengl.org/sdk/docs/man/html/glTexParameter.xhtml

> glTexParameter specifies the texture parameters for the active texture unit, specified by calling glActiveTexture. glTextureParameter specifies the texture parameters for the texture object with ID texture.

To clarify, `glTexParameteri(GL_TEXTURE_2D, ...)` should affect the texture associated with the handle abound to `GL_TEXTURE_2D`. So if you called `glBindTexture(GL_TEXTURE_2D, handle1)` then all `glTexParameteri(GL_TEXTURE_2D, ...)` should be associated with `handle1`. This assumes you didn't change active texture unit as that would have a different `GL_TEXTURE_2D` bound to it. `glTextureParameter()` is new in OpenGL 4.5 and can be used to avoid all that binding by passing the handle directly.

---
Tags: opengl
---


# Question
Title: Vertex position problem for connected lines
I’m trying to generate a mesh to display connected segments representing street lines in a mini map. I have problem with vertex orientation that my math knowledge has hard time to resolve.

Let’s consider 3 points p0, p1 and p2.

I use this code to create the vertices from the segment between p0 and p1 (the same code is then used for the segment from p1 to p2):

```
height = 2.0f; // desired line thickness
vertices[0] = new Vector3(p0.position.x, p0.position.y - height / 2.0f, 0);
vertices[1] = new Vector3(p1.position.x, p1.position.y - height / 2.0f, 0);
vertices[2] = new Vector3(p0.position.x, p0.position.y + height / 2.0f, 0);
vertices[3] = new Vector3(p1.position.x, p1.position.y + height / 2.0f, 0);

```

The result looks like this:

Not that bad, except that the "thickness" of the line is not constant. If you look closely to the segment left and right borders, they are aligned (going from bottom to top). The problem comes from the “height” variable that is added or subtracted too naively to the positions.

What I’d like to have is something like this, with oriented borders / vertex.

However I don’t know how to proceed.

Any help or comment would be appreciated. Thanks for your time.

\**** EDIT \**** Thanks to @wondra's solution I managed to do what I needed to. Here is how:

```
    // Returns point of intersection
    // TODO: check if lines are parallel
    public Vector3 LineIntersection(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
    {
        float ma = (p2.y - p1.y) / (p2.x - p1.x);
        float mb = (p4.y - p3.y) / (p4.x - p3.x);

        float ba = p1.y - (p1.x * ma);
        float bb = p3.y - (p3.x * mb);

        float x = -(ba - bb) / (ma - mb);
        float y = ma * x + ba;

        return new Vector3(x, y);
    }

/// --- LOOPING THROUGH POINTS ---

    // @wondra's solution
    Vector2 dir = (sec_node.position - prim_node.position).normalized;
    Vector2 perp = new Vector2(dir.y, -dir.x);

    vertices[vert_idx]      = prim_node.position + (perp * -height / 2.0f);
    vertices[vert_idx + 1]  = sec_node.position + (perp * -height / 2.0f);
    vertices[vert_idx + 2]  = prim_node.position + (perp * height / 2.0f);
    vertices[vert_idx + 3]  = sec_node.position + (perp * height / 2.0f);

    if ( vert_idx > 4 )
    {
        int vert_idx_bis = vert_idx - 4;
        vertices[vert_idx] = LineIntersection(vertices[vert_idx], vertices[vert_idx + 1], vertices[vert_idx_bis + 1], vertices[vert_idx_bis]);
        vertices[vert_idx_bis + 1] = vertices[vert_idx];

        vertices[vert_idx + 2] = LineIntersection(vertices[vert_idx + 2], vertices[vert_idx + 3], vertices[vert_idx_bis + 3], vertices[vert_idx_bis + 2]);
        vertices[vert_idx_bis + 3] = vertices[vert_idx + 2];
    }
/// --- END LOOP

```

# Answer
Lets start with the easiest, the segment from p0 to p1. First of all you need the perpendicular direction to this segment. To do this get the "normal" direction first simply subtract one point from the other, then use the well-known trick to get perpendicular vector (swap coords and negate one):

```
Vec3 seg01_dir = (p1 - p0).Normalize();
Vec3 seg01_perp = new Vec3(seg01_dir.y, -seg01_dir.x, 0); //I assume 2d data(!)

```

Now you have all you need to get all 4 points of the segment rectangle, just offset endpoints by half of the desired width in perpendicular direction:

```
height = 2.0f; // desired line thickness
vertices[0] = p0 + (seg01_perp * (-height / 2.0f));
vertices[1] = p1 + (seg01_perp * (-height / 2.0f));
vertices[2] = p0 + (seg01_perp * (height / 2.0f));
vertices[3] = p1 + (seg01_perp * (height / 2.0f));

```

...this would cower your example but be aware: The corners of the line strip would be broken if you did something that simple - the *actual* positions of `vertices[1]` and `vertices[3]` depends on next segment!
To be more precise you need to find(same as above) all 4 corners for next segment first and then correct the adjacent vertices (for p0-\>p1 and p1-\>p2 those are vertices 1,3,4 and 6). In order to correct the coordinates you need to find the intersection between lines given by vertices 0 to 1 and 4 to 5 giving you correct position for vertices 1 and 4 (the "lower"/right joint next to p1"). Similarly the intersection of lines given by 2 to 3 and 6 to 7 gives correct position for vertices 3 and 6 (the "upper"/left joint next to p1"). Repeat for all joints.
*note: I dont go into implementation details of the line intersection - there are plenty of good implementations around here*
> 1 votes

---
Tags: unity, procedural-generation, vertex, mesh
---


# Question
Title: 2D and 3D Perlin Noise Terrain Generation
I'm using 2d perlin noise to generate a heightmap and then adding 3d perlin noise to the heightmap to create overhangs and ridges. But it's not turning out like I would like it to. There are too many hills that don't look good and lots of different places where it's flat. This is the perlin noise function I'm using for both the 2d and 3d (in LUA):

```
function noise(x, y, z)
  local X = math.floor(x % 255)
  local Y = math.floor(y % 255)
  local Z = math.floor(z % 255)
  x = x - math.floor(x)
  y = y - math.floor(y)
  z = z - math.floor(z)
  local u = fade(x)
  local v = fade(y)
  local w = fade(z)

  A   = p[X  ]+Y
  AA  = p[A]+Z
  AB  = p[A+1]+Z
  B   = p[X+1]+Y
  BA  = p[B]+Z
  BB  = p[B+1]+Z

  return lerp(w, lerp(v, lerp(u, grad(p[AA  ], x  , y  , z   ),
                                 grad(p[BA  ], x-1, y  , z   )),
                         lerp(u, grad(p[AB  ], x  , y-1, z   ),
                                 grad(p[BB  ], x-1, y-1, z   ))),
                 lerp(v, lerp(u, grad(p[AA+1], x  , y  , z-1 ),
                                 grad(p[BA+1], x-1, y  , z-1 )),
                         lerp(u, grad(p[AB+1], x  , y-1, z-1 ),
                                 grad(p[BB+1], x-1, y-1, z-1 )))
  )
end

function fade(t)
  return t * t * t * (t * (t * 6 - 15) + 10)
end

function lerp(t,a,b)
  return a + t * (b - a)
end

function grad(hash,x,y,z)
  local h = hash % 16
  local u
  local v

  if (h<8) then u = x else u = y end
  if (h<4) then v = y elseif (h==12 or h==14) then v=x else v=z end
  local r

  if ((h%2) == 0) then r=u else r=-u end
  if ((h%4) == 0) then r=r+v else r=r-v end
  return r
end

p = {}
local permutation = {151,160,137,91,90,15,
  131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
  190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
  88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
  77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
  102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
  135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
  5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
  223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
  129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
  251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
  49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
  138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
}

for i=0,255 do
  p[i] = permutation[i+1]
  p[256+i] = permutation[i+1]
end

```

You can also find the implementation, written by Perlin himself, here: http://mrl.nyu.edu/~perlin/noise/

And this is how my loop looks like:

```
local smoothness = math.random(20, 30)
    for x = 1, mapScale do
        wait()
        for z = 1, mapScale do
            local height = noise(x/smoothness, z/smoothness, 0) --Find out the height
            for y = 1, (height*mapHeight)+10 do
                local density = noise(x/smoothness, y/smoothness, z/smoothness) --Find out the density
                if y > waterLvl then
                    if density*10 > 0 then
                        t:setCell(x, y, z, 1, 0, 0) --Sets cell at position x, y, z
                    end
                else
                    t:setCell(x, y, z, 1, 0, 0)
            end
        end
    end
end

```

This is how it turns out to be:

How would I change the frequency, number of octaves, and persistence with this function since it doesn't take any parameters for them?

# Answer
You are ONLY generating Perlin noise. This is actually the same as using only one octave, at any frequency. You can base yourself to implent FBM (Fractional Brownian Motion), It is actually what all engines use to make Perlin noise more fractal looking.

Bringing it down to code, you can use it like this:

```
//pseudo code
function fBm(float x, float y, float z, int octaves = 8, float lacunarity = 2.0, float gain = 0.5)
{
    float amplitude = 1.0;
    float frequency = 1.0;
    float sum = 0.0;
    for(int i = 0; i < octaves; ++i)
    {
        sum += amplitude * noise(x * frequency, y * frequency, z * frequency);
        amplitude *= gain;
        frequency *= lacunarity;
    }
    return sum;
}

```

You can change this line

```
sum += amplitude * noise(x * frequency, y * frequency, z * frequency);

```

with some other noise functions to generate some cool effects, for example:

```
sum += amplitude * (1-abs(noise(x * frequency, y * frequency, z * frequency)));

```

and you'll have a cool eroded terrain, with lots of straight mountains. Having a nice terrain is a game of playing with parameters, don't expect an already made "recipe", try to make your own!
> 13 votes

# Answer
I have an idea that, since you can use different octaves, you can make harmonics using multiple resolutions of perlin noise.

8, 4, 2, 1 as octaves would superposition itself nicely, I think.

The only problem with this is that it might not be 100% "random" in that you use the same seed for each octave.

The key here is the word "superposition"
> 0 votes

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


# Question
Title: High poly vs Low Poly when creating model
I am new in game development, but I have some knowledge in Maya and 3ds Max, I want to create pirate ship for game. So I spoke with many 3d artists and there are different opinions about low polygons and high polygons modelling. I am an iOS developer too so I know that it's hard for computer to process many polygons, so we should reduce amount of faces as much as we can. But my question is much more connected to 3D.

Do I need to create low polygons model at start and then smooth it to increase amount of faces or do I need to create high polygons model and then reduce amount of edges, faces and etc?

# Answer
I think your question is about modelling assets for your game and whether you should start with a low or high poly prototype.

To me it makes sense to prototype quickly and therefore choose whichever takes you the least amount of time...

That doesn't always mean low-poly (though in general it is usually quicker to build a prototype model out of simple primitives than it would be to model something accurately). If for example you found a high-poly asset available to you online or somewhere else, then you shouldn't be worrying about number of polygons at such an early stage and should feel free to use that model accordingly.

I have always modelled starting from primitives, adding complexity until I'm satisfied that the output **stylistically** matches what I had in mind.
> 2 votes

# Answer
Okay you'll never use high poly models in the actual game itself.

The purpose of a high-poly model is to provide your low-poly silhouette model "DETAIL" information for baking.

Two different methods for creating models.

1) Low to High

2) High to Low

Low to High is for modelers that are more methodical. Like Maya Artist to Zbrush

High to Low is more for sculpture type artist. Like Zbrush to Maya

no approach is better it's based on the ARTIST

Learn more about UVING, RETOPOLOGIZING, and baking maps for games. This knowledge will help you
> 1 votes

---
Tags: unity, models, methodology, 3d-modeling
---


# Question
Title: When making 3D model for building, is it better to split it or combine it?
As the title say, when making 3d model for building (example: school, office, etc). Used for FPS game so it must have detail and texture must be vary so it won't look like repeating/reused. Is it better to make the whole building as one model with multiple materials and UV map, or split it to sub model such as a wall, pillar, floor, etc. I want to know which is more practical or better for a game. I want to know why is it better, advantage and disadvantage of both, or if there's a better technique I can use.

# Answer
> 0 votes
It makes sense to break assets into pieces as small possible until the workflow overhead gets too much, or the in-game visual repetition breaks immersion.

For example, if you have a model representing some leaves, you could create various different types of vegetation by placing it in different places with slight scale and hue adjustments:

* This **saves disk space**: you only have to store that model once.
* It can also **reduce repetitive work**: if you think of a better model for those leaves, you can make the change to one model and all your in-game vegetation that uses that model will inherit the changes without further changes.

However, this has the mentioned disadvantages:

* Excessive **repetition can break immersion**; if players begin to notice pieces of the environment are used repeatedly, the world feels more fake.
* At some point, **asset management becomes hard**. For a large game, if level designers have to move a lot of objects around to construct something simple, that'll kill their productivity (unless your tools can handle it e.g. by allowing assets to be grouped and such groups duplicated and distributed).

The right value along this gradient comes down to your game:

Cinematic, environment-centric games like *L.A. Noire* or *The Wolf Among Us* have to be most careful about making their environments unique and interesting (so are likely to use more and more detailed assets, and larger models).

On the other hand, *The Elder Scrolls: Skyrim* or *DOOM* can in some segments of the game get away with extremely heavy asset reuse, because the player's attention is elsewhere.

Some games also heavily utilise procedural generation, which can help get the required variety out of less and smaller assets with less human effort (e.g. *Minecraft*), or even *almost no static assets at all* (e.g. the upcoming *Nowhere*).

---
Tags: 3d, 3d-modeling
---


title: Website within Skyrim

text:
# Question
Title: Website within Skyrim
I'm new to the Skyrim Creation kit but I've been through a few tutorials and looked through the documentation but I couldn't see a way to do this. Is it possible to display an HTML page within the game itself? Like a popup screen in-game that displays Google or other site? I've looked for a couple of days but feel I might be chasing something that's not possible.

Thanks

# Answer
> 0 votes
I came across this same problem. When I saw that books in the creation kit are created in html coding, I decided to experiment by adding a `<a href=`. When I opened the game, the entire hyperlink text was not displayed. As far as I'm concerned, the only way to do what you wanted would be to open the in-game steam browser, but I don't think that there would be a way to make it appear without the player pressing shift-tab.

Answer: No. It is highly unlikely that you would be able to browse the internet from within Skyrim, with or without mods.

---
Tags: modding, web, html, skyrim-modding
---


# Question
Title: Collision method only using one item from list
I've made a temporarily method for collision with all the blocks on the screen. (I used almost the same method in the past, but only for one block at the time.)

So I start in the `Sprite` class. I use a list named `tileCollision` and I make a new list in the constructor for the tiles:

```
public List<Rectangle> tileCollision { get; set; }

public Sprite(GraphicsDevice gd,Texture2D collisionImage, Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
{
    this.collisionImage = collisionImage;
    this.textureImage = textureImage;
    this.position = position;
    this.frameSize = frameSize;
    this.currentFrame = currentFrame;
    depth = 0;
    // the Rectangle list
    tileCollision = new List<Rectangle>();
}

```

This is the collision method for the `Sprite` class (NOTE: this class is abstract):

```
public virtual void Collision (Rectangle collisionRect, List<Rectangle> tileCollision)
{
}

```

So now we can have a look at the `PlayerMovement` class, derived from the `Sprite` class. This is the `Collision` method (NOTE: the `TileSprite` class (class for my tiles) also contains a collision rectangle):

```
public override void Collision(Rectangle collisionRect, List<Rectangle> tileCollision)
{
    foreach (Rectangle rect in tileCollision)
    {
        if (collisionRect.Intersects(rect))
        {

            stopping = true;
            walking = false;

            if (collisionRect.X < rect.X)
            {

                fallingTest = false;
                stopping = true;

                if (left)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (collisionRect.X > rect.X)
            {

                fallingTest = false;
                stopping = true;

                if (!left)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (collisionRect.Y <= rect.Y - 50)
            {
                ground = true;
                fallingTest = true;
                stopping = false;

                if (moving)
                {
                    walking = true;
                }
            }

            if (collisionRect.Y >= rect.Y + rect.Height)
            {

                stopping = true;

                if (moving)
                {
                    walking = true;
                }
            }
        }
        if (!collisionRect.Intersects(rect))
        {
            fallingTest = false;
            stopping = false;

            ground = false;

            if (moving)
            {
                walking = true;
            }
        }
    }
}

```

And finally, this is my `SpriteManagerGeneral` class (the class where I "connect" everything for sprite handling). The dirt tiles are added to the `tileCollision` list (NOTE: just for testing):

```
// childTiles list is not used for collision
tileBase.childTiles.Add(dirt);
tileBase.tileCollision.Add(dirt4.bCollisionRect);
tileBase.childTiles.Add(dirt2);
tileBase.tileCollision.Add(dirt3.bCollisionRect);
tileBase.childTiles.Add(dirt3);
tileBase.tileCollision.Add(dirt2.bCollisionRect);
tileBase.childTiles.Add(dirt4);
tileBase.tileCollision.Add(dirt.bCollisionRect);

```

My update method for the collision looks like this:

```
playerBase.children.ForEach(c => c.Collision(player.collisionRect, tileBase.tileCollision));

```

(playerBase is the base of the player that contains a list (`children`) with all the body parts in it)

So now my problem: my problem is that my game only uses the collision logic on the LAST item (Rectangle) added to the `tileCollision`.

You see here that `dirt` is added as the last item, so the collision will work on this block, but not on the others.

I want it so that the method loops through every item instead of the last item.

# Answer
> 1 votes
I used `if (!collisionRect.Intersects(rect))` in my collision method but that means that IF one tile doesn't collide with the player, then it will call this if statement.

So I changed this to `if (!(tileCollision.Any(c => collisionRect.Intersects(c))))` and it works now.

This code translated to English:

If none of the collisionboxes from the tile collide with the player, then call this statement.

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


# Question
Title: How do I save a procedurally-generated map as binary level-data in C++?
For example, I'd like to do something as simple as a generating an array matrix using Conway's Game of Life and then filling each cell with particular data to be saved to a binary file.

Additionally, how do I load the binary level-data? :)

# Answer
> 4 votes
If the data's small, just use a text format like XML, JSON, CSV, or your own flavour. If OTOH the data is massive and/or private and/or size / parse speed important, then binary's probably best.

You will need to create a binary data format / layout to be used. This would denote a byte array of a certain size and which bits therein are used for what, e.g you might have a `struct` of 64 bits where 4 bits act as one field and the other 60 as another field. This is a very simple example; you will more likely have several, nested struct types representing the full body of data for a more complex game. Now use an output `stream` to save this to disk or send it over the network, or alternatively use your own custom in-game protocol to do same.

As for restoring from that save, you'd likely parse back into the same `struct` type after retrieving the `stream` (byte array) from disk or network: get the `stream` contents with the correct endianness, and then static-cast its data to the `struct` type in question (this doesn't take into account `struct` padding bytes which may / may not be stripped on initial conversion to a stream).

# Answer
> 2 votes
If the data is a simple array and it's just for a personal project you could do something as straight-forward as read and write each array element to/from a file. Flatten the matrix into a 1-D array, and just make sure that you read the elements from the file in the same order that you wrote them. If, on the other hand, you want to serialise something more complicated than an array of primitives then you could look into using something like Protobuf.

For an example of the first approach:

```
#include <assert.h>
#include <algorithm>
#include <fstream>
#include <stdio.h>
#include <vector>

int main(int argc, char const *argv[]) {
    // initalise a collection with data for writing, here
    // we are just using integers for simplicity.
    int array[] = {1, 0, 1, 1, 0, 1, 1, 1, 0};
    // if using C++11 you could use an initializer list
    // to construct the vector, e.g:
    //  std::vector<int> outVector = {1, 0, 1, 1, ...}
    std::vector<int> out_vector(array, array + sizeof(array) / sizeof(*array));

    // define the input/output filename. if you need to manipulate
    // the filename at all, use a std::string instead of char*.
    char *file_name = "example";

    // declare a file stream to read/write data to the file
    std::fstream f;
    // open the file for writing, and proceed to write
    // each integer to the file.
    f.open(file_name, std::fstream::out);
    for (size_t i; i < out_vector.size(); i++) {
        f << out_vector[i];
    }
    f.close();

    // initialise a collection for reading the data back in
    std::vector<int> in_vector;
    // open the file for reading, and proceed to read
    // each character of the file into the new collection.
    f.open(file_name, std::fstream::in);

    char in_char;
    while (f >> in_char) {
        int in_int = in_char - '0'; // convert char -> int
        in_vector.push_back(in_int);
    }
    f.close();

    // the collections should contain the same data
    assert(in_vector == out_vector);
}

```

---
Tags: c++, procedural-generation, savegame
---


# Question
Title: Device model detection and comparation doesn't work
I need to detect device model, and if it is Galaxy Ace GT-S5830i, print it out. But it never print's it (it doesn't get through condition).

My code:

```
public String mDeviceModel = android.os.Build.MODEL;

System.out.println(mDeviceModel); //this prints my GT-S5830i

if (mDeviceModel == "GT-S5830i") //compiler don't get thru this cond.
    System.out.println("GALAXY ACE S5830i"); //never printed

```

I can't get what's wrong here.

# Answer
> 3 votes
It's just a classic string comparison bug. In java "==" compares the object references to each other to see if they are the same object. In this case the string you just created for the comparison and the string `android.os.Build.MODEL` are two completely different string/objects even though their content may be the same. To compare the content of two strings, use the strings `equals()` method.

```
if (mDeviceModel == "GT-S5830i")
    System.out.println("GALAXY ACE S5830i");

```

Should read

```
if (mDeviceModel.equals("GT-S5830i"))
    System.out.println("GALAXY ACE S5830i"); // Should now print.

```

---
Tags: java, android
---


# Question
Title: My Simple Score System Isn't working please help
```
using UnityEngine;

/// Handle hitpoints and damages
public class HealthScript : MonoBehaviour
{
    /// Total hitpoints
    public int hp = 2;
    /// Score System
    public int score;

    /// Enemy or player?
    public bool isEnemy = true;

    void Start()
    {

    }

    void Update()
    {

    }

    /// Inflicts damage and check if the object should be destroyed
    public void Damage(int damageCount)
    {
        hp -= damageCount;
        SoundEffectsHelper.Instance.MakeplayerHitSound();

        if (hp <= 0)
        {
            SpecialEffectsHelper.Instance.Explosion(transform.position);
            SoundEffectsHelper.Instance.MakeExplosionSound();
            // Dead!

            if (isEnemy == false)
            {
                Application.LoadLevel(Application.loadedLevel);
            }
            if (isEnemy ==true)
            {
                ///when health reaches 0 object is destroyed and awards the player 100 points.
                Destroy(gameObject);
                score += 100;
            }
        }
    }

    void OnGUI()
    {

        if (isEnemy == false)
        {
            GUILayout.Label("score:  " + score.ToString());
            GUI.BeginGroup(new Rect(Screen.width / 2 - 350, Screen.height / 2 - 250, 100, 100));
            GUI.color = Color.red;
            GUI.Box(new Rect (10, 40, 80, 30),"Health: " + hp.ToString());
        }
    }

    void OnTriggerEnter2D(Collider2D otherCollider)
    {
        // Is this a shot?
        ShotScript shot = otherCollider.gameObject.GetComponent<ShotScript>();
        if (shot != null)
        {
            // Avoid friendly fire
            if (shot.isEnemyShot != isEnemy)
            {
                Damage(shot.damage);

                // Destroy the shot
                Destroy(shot.gameObject); // Remember to always target the game object, otherwise you will just remove the script
            }
        }
    }
}

```

**The score displays but doesn't attribute points when the enemy dies what am I doing wrong?**

# Answer
When you assign this script to every enemy and player, then every enemy and player has their own `score`. When an object dies, it adds 100 to *its own* score, not the score of the player which killed it.

Possible options to fix this are:

* change `int score` to `static int score`, which means that the value is shared between all instances of the behavior. This is the most simple solution, but will only work for singleplayer.
* When you want to support multiplayer where each player has an own score, remove the score counting from this class and move it into a different script which only exists once per player. You should add a reference to that script to your `ShotScript` behavior. That way you can keep track of which player fired a shot and use that reference to award the score to the right player.
> 2 votes

# Answer
I got the script working with a little help thanks for all your input. by putting the score in a separate script and defining the player object in this script it works perfectly.

```
using UnityEngine;

/// <summary>
/// Handle hitpoints and damages
/// </summary>
public class HealthScript : MonoBehaviour
{
    /// <summary>
    /// Total hitpoints
    /// </summary>
    public int hp = 2;
    /// <summary>
    /// Score System
    /// </summary>
    public int score;
    GameObject player;
    /// <summary>
    /// Enemy or player?
    /// </summary>
    public bool isEnemy = true;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag ("Player");

    }

    void Update()
    {

    }

    /// <summary>
    /// Inflicts damage and check if the object should be destroyed
    /// </summary>
    /// <param name="damageCount"></param>
    public void Damage(int damageCount)
    {
        hp -= damageCount;
        SoundEffectsHelper.Instance.MakeplayerHitSound();

        if (hp <= 0)
        {

            SpecialEffectsHelper.Instance.Explosion(transform.position);
            SoundEffectsHelper.Instance.MakeExplosionSound();
            // Dead!

            if (isEnemy == false)
            {
                transform.parent.gameObject.AddComponent<GameOverScript>();
                Destroy(gameObject);
            }
            if (isEnemy ==true)
            {
                ///when health reaches 0 object is destroyed and awards the player 100 points.
                player.GetComponent<ScoreScript>().score+=100;
                Destroy(gameObject);

            }

        }
    }
    void OnGUI()
    {
        //display player information
        if (isEnemy == false)
        {
            GUI.color = Color.red;
            GUI.Box(new Rect(Screen.width / 2, Screen.height - Screen.height, 248, 46), ("Health: " + hp.ToString()));

        }
    }

    void OnTriggerEnter2D(Collider2D otherCollider)
    {
        // Is this a shot?
        ShotScript shot = otherCollider.gameObject.GetComponent<ShotScript>();
        if (shot != null)
        {

            // Avoid friendly fire
            if (shot.isEnemyShot != isEnemy)
            {
                Damage(shot.damage);

                // Destroy the shot
                Destroy(shot.gameObject); // Remember to always target the game object, otherwise you will just remove the script

            }

        }

    }

}

```
> 0 votes

---
Tags: unity, c#, game-design
---


# Question
Title: How can I minimise data sent through a network in a modern FPS?
I am aware of snapshot interpolation with the use of delta compression as being a technique used to minimise the amount of data sent in a modern FPS game like Quake 3, but what other techniques are there?

# Answer
> 6 votes
When we implemented our networking engine we exploited a number of compression techniques:

1. First we write all of our snapshot bit-wise: bools are only 1 bit instead of 1 byte (or more depending on compiler). We wrote a bitstream class that reads and writes data to a stream. This saves a fair bit of data all alone when packing flags down. For an example of a decent C++ BitStream class have a look at the RakNet source recently made available by Occulus here: https://github.com/OculusVR/RakNet
2. We found the smallest way to represent data, bitwise - if an integer can only be in the range of 0 to 15, for example, we only store it in the snapshot as 4 bits. We perform this range packing on signed and unsigned integers, minimizing the amount of data being sent at the cost of having to write the data to our snapshot stream bit-wise. There is CPU cost here, but the data bandwidth is greatly reduced. We do this for enumerations as well - if there are only two states, it only takes one bit, for example. We exploit templates here to make this easy to write in code.
3. We establish some data types that can be quantized - data that we are satisfied to lose some decimal precision to reduce the over-the-wire bandwidth. Combined with the range packing we can compress floating point numbers down from 32 bits to a smaller, range and precision specific level. Again we exploit templates here to make this easy to write in code.
4. Delta compression - you have identified this already, but it makes a significant impact.
5. We group blocks of data where the delta compression allows us to group a number of related, unchanging fields under a single dirty bit to indicate if they have changed or not. This reduces the cost of sending a bit for each field indicating it has NOT changed. There is less of a win here, and one has to be careful about how you group them, but infrequently changing fields that generally change in tandem are good candidates.
6. We take the entire packet and compress it using a quick compression engine - lz4, for example. This reduces the data even more - every thing helps.
7. We don't send ANY data for objects that are too far away to be part of the local player's simulation and bulk-synchronize those objects when the player enters proximity. Some objects are excluded from this system such as mission objects, keys and locks, for example.
8. We don't send ANY data that can be reliably reproduced on the client. For example, we send animation state and time instead of the position of each bone - the client can reliably pose the character with that information, saving us the bandwidth of sending the transform of every bone (and anything attached to those bones - hit boxes, effects, etc). We extend this out as far as we can. As one comment pointed out, "the best compression is not sending it at all".

I'm sure there are others, but these ideas should help.

---
Tags: networking, first-person-shooter, data, compression
---