# Question
Title: OpenGL ES draw pre-rendered background onto depth buffer
I want to create a scene with 2D pre-rendered background and 3D models for characters (like those classic Final fantasy games).
For the background, I have 2 textures:

* one to be displayed, with colors, details...
* one to be used as depth buffer (depth value presented as grayscale value maybe)

I want to write a shader program to help me discard all the pixels(frags) which have the depth smaller than current depth.
But then, do the background and the models have to use the same shader?
What value to compare with the depth value?
Is this approach even possible?

# Answer
"Is this approach even possible?"

What you could do is make a fine resolution full screen "quad" that has it's verticies displaced in the vertex shader according to a lookup into your "depth buffer" texture. That way, the perceived depth of your grayscale image will be written into the currently bound framebuffers depth buffer.

"I want to write a shader program to help me discard all the pixels(frags) which have the depth smaller than current depth."

You don't need to do this, just use OpenGL's depth test.

"What value to compare with the depth value?" OpenGL does this for you, provided you enabled depth testing.

Edit: And of course, the displacement in the vertex shader should approach the camera.

I think the vertex shader should look a bit like this:

```
attribute vec3 vert;
attribute vec2 uv;
uniform sampler2D depthTexture;
uniform float mapRange; //you will probably need to change this value for every scene

void main() {
  float displacement = texture2D(depthTexture, uv).w*mapRange; //preferably, for the texture you want single channel 32 bits, dunno if ES supports that though
  gl_Position = vec4(vert, 1)+vec4(0, 0, -displacement , 0); // the displacement moves along the negative z axis, which afaik is towards the camera.
}

```

Fragment shader:

```
void main() {
  gl_fragColor = vec4(1);
}

```
> 2 votes

---
Tags: opengl, opengl-es2, depth-buffer
---


# Question
Title: Control animation using animator control class
I did a sample existing code to control animation using animation.I dragged and dropped a character into the scene then I added a Animator to it and added the animator controller.Below I have given the screen short of the animation

Then I have attached the following code to it

```
Animator animator;

int eatHash=Animator.StringToHash("ideal");

int stateHash=Animator.StringToHash("Base Layer.pickbothfork");

void Start () {
    animator = GetComponent<Animator>();
}

// Update is called once per frame
void Update () {
    //animator.SetBool ("isEat", true);
    float move = Input.GetAxis ("Vertical");
    animator.SetFloat ("Speed",move);

    AnimatorStateInfo stateinfo = animator.GetCurrentAnimatorStateInfo (0);
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Debug.Log ("clicked spacebar");
        animator.SetTrigger(eatHash);
    }
}

```

The problem here is the above code is working,when I run the project the animation is getting played one after the another according to the state diagram.But when I click on the space bar the trigger function(jump animation ) is not working

```
if (Input.GetKeyDown(KeyCode.Space))
{
    Debug.Log ("clicked spacebar");
    animator.SetTrigger(eatHash);
}

```

Can anybody please help me finding solution for it

# Answer
> 1 votes
If you want to go from walk or run animation to the jump animation you have to create a specific transition for each of those. You can edit the transitions by right-clicking them and selecting edit.

# Answer
> 1 votes
You don't have any transitions from run/walk back to jump. Look at the arrows; you only have a transition from jump to run, not back from run to jump.

In other words, transitions are not bi-directional; they're only one way. If you want a transition that goes back to a previous state, then you need another arrow.

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


# Question
Title: How can I change the sprites in the NES Double Dragon ROM?
I have played a few NES ROMs where people have gone into them and changed the sprites. How did they do this?

I'd like to do this for the Double Dragon ROM. How can I accomplish that?

# Answer
Just to extract an answer from the comments:

Zophars Domain shows you a list of tools that you can use for NES ROMs including Graphics Extractor and Inserter which allows you to extract and insert tile graphics from the ROM.

To use this you need the Extractor executable and the Inserter. Use the extractor to get the tiles first, edit them in your editor of choice (MS Paint ftw) and then use the inserter to pop them back into the ROM. Make sure you create a backup in-case it corrupts the ROM image.
> 2 votes

---
Tags: modding, roms
---


# Question
Title: Can you offset the horizontal flip in SpriteEffects XNA?
As the title suggests I need to know if there is a way to offset the `SpriteEffects.FlipHorizontally` component in the XNA draw method. My reason for this is the sprite I am attempting to flip is not centered, the result is that the sprite does not rotate as expected and causes unexpected collisions when flipping. I have the alternative of redoing all the textures in the sprite sheet to centre them up however I'm wondering if there is also a quick solution that can be added into the code?

My tests so far have shown that the origin of the texture seems to have no effect on where it is flipped otherwise I would just offset my origin and gone with that.

# Answer
You will need to mirror the origin of your sprite.

Simply subtract the original origin from the width of the sprite.

Something like:

```
Vector2 origin = new Vector2(20, 10);
int spriteWidth = 100; // from sourceRectangle or texture width
SpriteEffects spriteEffects = SpriteEffects.None;

if (flipSpriteHorizontallyAroundOrigin)
{
    origin.X = (float)spriteWidth - origin.X;
    spriteEffects |= SpriteEffects.FlipHorizontally;
}

```
> 1 votes

# Answer
Flipping a sprite around a given offset from its center is equivalent to first flipping the sprite normally (around its center), then offsetting the result.

I haven't used XNA in a while, but you can do this by adding a translation to your drawing matrix.

A somewhat hackier way to do this is to call `SpriteBatch.draw` with an origin and pass a `scale` parameter with the relevant component set to `-1`. Since the scaling transform honours the origin and scaling by negative one flips, this should flip the sprite about that origin.
> 0 votes

# Answer
I recommend you use an offset with your mirroring. this way, you can control where the symetry happens. Back when I was using XNA, I used to always consider the position of an object in the center and that certainly helped with all the flipping I needed.

I used to take the 6th overload to the spriteBatch.Draw(...) method if you're interested.
> 0 votes

---
Tags: xna, c#, textures
---


title: Why use compression such as zlib?

text:
# Question
Title: Why use compression such as zlib?
Compression and encryption are different things AFAIK, so why even use compression if you have to still decompress anyway, is this just to reduce distribution size or is there some other reason?

# Answer
Mainly compression is used to reduce the size of the distributive and game resource package. You should distinguish compression of the distributive and the resource package of the installed game. The distributive usually is compressed by high compression ratio algorithms, while the package of installed game can be compressed by algorithms with fast decompression speed to be able to decompress it on fly. For the distribution there is only one benefit - reduction of its size. However, for the package of installed game the benefit is not only a reduction of its size, but also possible a light speed up of file read operations. The resource package of the installed game might not be compressed, it is not always necessary.

The speed up of read operations could be achieved in case of slow disk read operations (mobile devices for example) and using algorithms with very fast decompression speed, such as LZ4

On mobile devises, I have noticed the following thing. The ratio of read time of compressed data to decompression time with LZ4 can be up to ten times. So depending on compression ratio, you can chose what types of files should be compressed and what not.

You should be aware of the following disadvantages of on fly decompression:

* It is hard to implement streaming of compressed data and there could be serious loss of performance.
* Memory consumption would be increased due to the need of allocating buffers for decompression.
> 6 votes

# Answer
Mainly compression is in fact used to reduce distribution size.

If you think about it with digital music, you could download a CD as .wav and it's 650 MB, or as 256 KBPS AAC files and it's 1/5 the size with the same sound quality\*.

It just makes sense to compress anything you can. You're taking the compression time on your side once to save time downloading or reduce storage media size for everyone who uses the product.

As a side note, yes encryption is different from compression. Encryption makes it hard to read the data if you're not the intended recipient. When making an iOS game, we send a compressed archive to Apple, then they encrypt it, which makes the package *bigger*.

* I have done blinded testing on this. There's no discernable difference between uncompressed audio and 256 KBPS AAC audio.
> 3 votes

# Answer
A big reason to compress game assets is to decrease loading times.

Example scenarios:

1. Read uncompressed asset of 20MB size, or
2. Read compressed asset of 10MB size and decompress.

In scenario 2 less data needs to be read from the hard disk which will save some time. If the CPU is faster at decompressing the read 10MB to the original 20MB than the hard disk in scenario 1 is capable of reading the remaining 10MB, compression will improve the loading time. Note that hard disks are generally much slower than CPUs. Many algorithms (you mentioned zlib's) even allow decompression on the CPU while the hard disk is reading in parallel.

You should pick an algorithm that

1. compresses well (to reduce the time spent reading from the hard disk) and
2. decompresses quickly (to reduce the time decompressing using the CPU).

Algorithms that would increase loading times are used when compressed size on disk is more important than decompression time, for example during installation of the game assets.
> 3 votes

# Answer
The answer is time

```
Use Compression?
    if uncompressed (down)load time > compressed (down)load time+decompress time then
        Win! use compression
    else
        Lose! don't bother

```
> 0 votes

---
Tags: c++, compression, encryption
---


title: Road parallax background

text:
# Question
Title: Road parallax background
I am a beginner in game development. I want to create a parallax background that merges at the front and expands at the bottom. I'm sure there is a way to do this, but I'm missing something. My parallax background is working fine but didn't merge from start to bottom.

Any guidance? Thanks!

Code for my parallax:

```
private BitmapTextureAtlas mAutoParallaxBackgroundTexture;
private TextureRegion mParallaxLayerMid;

this.mParallaxLayerMid=BitmapTextureAtlasTextureRegionFactory.
createFromAsset(this.mAutoParallaxBackgroundTexture, this,"road.png", 0, 0);

back_ground = new Sprite(0,0,CAMERA_WIDTH,CAMERA_HEIGHT,this.mParallaxLayerMid);

autoParallaxBackground = new AutoParallaxBackground(20, 30, 40, 50);
autoParallaxBackground.attachParallaxEntity(newParallaxEntity(15.0f,back_ground));
scene.setBackground(autoParallaxBackground);

```

I'm trying to make parallax background like in these screen shots.

# Answer
Your question is a bit rough but if I'm following correctly, you want to make it so the background is stretched horizontally as it moves towards the bottom of the screen, giving it a somewhat isometric view and a more angled perspective.

Just as a warning, I've no direct android development experience myself so this is going to be largely theoretical. Others may be able to tell you what parts of this are feasible or better methods to do so.

## Camera Method

Easy way to do this off the top of my head is to tilt an overhead camera pointed at a top down surface.

That would allow you to do all your game logic without regards to the perspective drift (something moving forward along the road would naturally shrink as it moved away). Of course this means that there will be parts of your surface that are clipped by the bounds of the screen, but depending on how you handle your gameplay this may or may not be an issue.

## Shader Method

Another way to handle it would be to implement some form of shader that sampled the surface differently based on Y position on screen. Again, I'd likely render my scene as a rectangle (straight top-down, no perspective) and use that as what gets sampled so all the assets get the effect and not just the background. Using a system like that you could specify a percent amount to sample from at the bottom of the screen and the top and adjust them to taste.

An example of using that method. Say you had a surface and you wanted 50% at the bottom and 100% at the top:

When you go to draw to your screen, what is actually displayed is entirely within the red. At the bottom of the screen, the left most pixel samples from the 25% mark and the right most pixel samples from the 75%. This does mean you'll have to deal with stretching up close/loss of detail at distance, but things like image resolution and how dramatic you make the difference between "near" and "far" will allow you to adjust it until it feels right.

## Cheating!

If both of those have issue, or if it just sounds like too much of a pain, then I'd recommend cheating. Make your background relatively static with the proper tilt to it and only move non-static elements along it.

Using the road example, the lines down the middle and the things along the sides of the road. You'll have to scale them up slightly as you move them down the screen, but you can get a fairly decent illusion of perspective/depth with very little cost this way provided you either don't turn or come up with a decent way of handling them. This is something very similar to what a number of old resource limited games would do in this situation.

Hope one of these is something close to what you were looking for.
> 5 votes

# Answer
I use that for full screen

```
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, 0, camera.getWidth() ,camera.getHeight() ,this.mParallaxLayerBack, vertexBufferObjectManager)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 80, this.mParallaxLayerMid, vertexBufferObjectManager)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, cameraHeight - this.mParallaxLayerFront.getHeight(), this.mParallaxLayerFront, vertexBufferObjectManager)));
scene.setBackground(autoParallaxBackground);

```

camera is a globar var, i hope that help you! it works for me
> 0 votes

---
Tags: android, andengine, parallax-scrolling
---


# Question
Title: Quadtree vs multiple resolution grids for terrain rendering
I have been thinking about quad trees with regards to terrain rendering.

From my understanding the basic functionality of quadtree terrain rendering is to frustum cull the terrain in such a manner:

```
function render() {
    lod_threshold++;
    if(lod_threshold_reached || !has_children()) {
        draw_terrain_mesh();
        return;
    }
    for(child in children) {
        if(child.bounds.intersect(viewing_frustum)) {
            child.render();
        }
    }
}

```

where node.bounds is a 3d bounds calculated as containing the maximum heightmap value of the contained terrain

My questions are the following

1. If we are in fact testing a 2d portion of terrain with it's bounds calculated to include the maximum heightmap value against the 3d frustum, what is the preferred bounds calculation for generating the node.bounds in the quadtree?
2. That a tree is necessary because that one has to iterate every portion of a 3d scene to calculate frustum occlusion in a general way. Eg, there is no shortcut algorithm to calculate the set of 3d cells generated from a 2d grid that intersect the viewing frustum. As a more general question and to question the obvious, is there a way to calculate cells in a viewing frustum without having to iterate every cell in a scene? Presumably not otherwise you wouldn't need trees for culling

With regards to an alternative grid implementation:

Has this implementation been contemplated for general purpose terrain culling? I am presuming that some form of grid base terrain culling is certainly preferred in certain games, namely top down games where the possibility of terrain in the distance of being on camera is non-existent.

```
function calc_cells_in_quadrilateral(frustum_projection_onto_2d_terrain_grid) {
    //calculate cells in the resulting quadrilateral projection of the frustum onto the grid without having to bounds test every cell
    //at some point based on distance from camera, assign lod
}
retrieve lod for each cell in the calculated set from lod grids
have multiple (array2 or intmap) containing the terrain data at every lod for O(1) retrieval

```
1. Is there is a way to calculate cells in a quadrilateral without having iterate every cell in a grid? eg, from shaving off cells from slopes or something?
2. If there is, in what fashion should one assign the lod cell based on distance? I haven't contemplated this in detail because #1 may be impossible
3. The terrain would not be optimally culled in this 2d culling algorithm against the quadrilateral frustum projection onto the heightmap, because the height value at the edges may be outside the screen, correct?
4. http://www.olhovsky.com/2011/03/terrain-started/ In this post, he describes assigning lod from a grid and from a quad tree. The illustrations are confusing with regards to whether question #1 is correct and terrain rendering with quad trees serves to draw the terrain mesh against the frustum as opposed to just as a function of distance 360 around the camera as at appears to do with his grid implementation. Please specify whether it appears that he is infact not frustum culling in the grid implementation but is frustum culling the quadtree.

# Answer
For performance reasons I never frustum cull on the CPU -- I just distance cull as part of the LOD determination so I'm rendering everything in front of and behind the camera (let the GPU do the culling for the frustum) so that when the player turns there is no potential lag while new terrain chunks are activated or (even worse) sent to the gpu. I also don't worry much about terrain occlusion.. if the player is within viewing range of a chunk the data needs to be there in case he walks over the ridge.. again a case where having the data on the GPU and letting the GPU depth buffering handle the occlusion is worth the trouble.

LOD for distance needs to be based on the distance between the corners of a chunk in pixels at a given viewing distance and camera field of view. There just isn't much point to rendering a distant chunk at such high LOD that the chunk is only a few pixels of screen area, so you step up the quad tree or don't drill down so far that you are processing a lot of vertex and texture data for a very small number of pixels. Finding a good balance here can be a royal pain :) Especially note that the pixel size of an edge viewed edge on can be calculated using nothing more than the distance and field of view numbers without performing any matrix math using the view/projection transform, and typically that pixel width of an edge is more than sufficient to determine what LOD needs to be used for a specific branch of the quad tree.

You do need the quad tree to manage the LOD data and to contain references to the GPU objects that represent your terrain, and to manage loading and unloading that GPU data as needed while the player is moving around. Just pay attention to what the GPU can do FOR you that reduces CPU load for deciding what needs to be active on the GPU because it is potentially viewable now or in the near future :)
> 1 votes

---
Tags: terrain, terrain-rendering, quadtree
---


# Question
Title: How to resize my 2d game to fit the screen?
I am currently making a 2D game using Java (Java 2D). I want to make my game resizable. If you play any game on an emulator (e.g. legend of Zelda in fceux emulator) in full screen mode, you'll see that the 8-bit or 16-bit game re-sizes to fit the screen size. How can I implement the same thing in my game programatically?

# Answer
> 3 votes
I'm assuming you're using the standard Java 2D API, not OpenGL.

In that case, you render your graphics to a buffer image first. Then, to render that image to the screen, you can either use a Graphics.drawImage call that allows resizing your buffered image:

```
public abstract boolean drawImage(Image img,        // the buffer image
                int dx1, int dy1, int dx2, int dy2, // 0, 0, screen.w, screen.h
                int sx1, int sy1, int sx2, int sy2, // 0, 0, image.w, image.h
                ImageObserver observer)             // null is fine

```

or, if you want to have more control over the scaling algorithm, you can first convert the image to a second buffered image using the following method of the `Image` class:

```
public Image getScaledInstance(int width, int height, int hints)

```

Here, the parameter `hints` is one of

```
Image.SCALE_DEFAULT
Image.SCALE_FAST
Image.SCALE_SMOOTH
Image.SCALE_REPLICATE
Image.SCALE_AREA_AVERAGING

```

See the API doc for details. For bigger games, you might want to keep an eye on performance doing these rescales, but for typical 8-bit resolutions you should probably be fine.

---
Tags: java, graphics, resolution
---


# Question
Title: Architecture to draw many different objects in OpenGL
I have some objects that I want to draw. I am not sure how I can create my architecture in a way where I can draw everything as fast as possible.

As example:

```
class MyObject
{
  float[] vertices;
  float[] colors;
  float[] textures;

  public MyObject()
  {
    //fill every buffer with data
  }

  public void Draw()
  {
    //set shader
    //set shader uniforms etc.

    //foreach buffer
    BindBuffer();
    VertexAttribPointer();

    DrawArrays();
  }
}

```

In this way, I can draw every object like `myObject.Draw` after it is constructed. The problem would be, that if I have 5000 objects, I have 5000 draw calls. I need to set the shader every time even if I loop over the 5000 objects because I don't know if they use the same shaders.

Another way:

```
class MyObject
{
  bool needsToBeChanged;

  public MyObject()
  {
    //set my edge points
    needsToBeChanged = true;
  }

  void ChangeMyObject() //e.g. I changed the height of my object
  {
    needsToBeChanged = true;
  }
}

class GLWindow
{
  float[] vertices;
  float[] colors;
  float[] textures;

  GameLoop()
  {
    foreach(MyObject myObj in allMyObjects)
    {
      if(myObj.needsToBeChanged)
      {
        //get objects points for drawing it and set the global buffers up

        myObj.needsToBeChanged = false;
      }
    }

    DrawArrays(); //draw only once (because every data is in the buffer)
  }
}

```

Only 1 draw call for everything. I guess this will be faster than first method. The problem on this code is the big buffer that contains everything. Let's imagine we have inherited from MyObject and want to draw objects in different shapes. Now the Loop gets more complicated. You may have to split it because you need another shader for example for text. Now you have 2 arrays... And with other changes the Loop becomes more and more complicated and harder to maintain.

What solutions (beside the both) are available for this kind of problem? Can I use the first way or is there a better way where I can reduce the draw calls? How is it solved in other applications?

# Answer
> 6 votes
Generally speaking, you will need a separate draw call for each set of objects that have a different material (by material I mean a different shader, texture or other shading parameters).

So the obvious approach is to group objects that have the same material, so that they can be rendered together, avoiding the expensive state changes. This is normally done by batching objects that share the same material. A data structure that helps achieving this is the scene graph.

Once you have batched objects with the same material you eliminate redundant state changes. The shader program and textures are now set outside and a batch is rendered. Conceptually, this would look like this:

> ```
> for each batch in batches
>     set common material properties
>     for each object in batch
>         draw object
>     end for
> end for
>
> ```

But you still have multiple draw calls within each batch. This could be resolved if all objects resided inside the same Vertex Buffer. Packing everything in the same VB is feasible and might be the best option in some cases. Modern OpenGL, however, provides instanced rendering (see a tutorial here), which is a very good solution to reducing the number of draw calls.

Overall, some parts of your rendering will probably be better optimized with simple batching or a scene graph, while other will be more efficient if implemented using instancing. You should profile and test to discover the ideal approach. But bare in mind that this is an *optimization step*, therefore, you should first worry about making the game/software work, then you optimize it.

---
Tags: opengl, oop
---


title: Is this possible in cocos2dx 3.0?

text:
# Question
Title: Is this possible in cocos2dx 3.0?
I have a number of five images (`sprite1.png, sprite2.png, sprite3.png, sprite4.png, sprite5.png`), these all I want to add as a sprite...

```
int rndSprtNum = (arc4random() % 5) + 1;
for(int i = 0; i < 5; i++)
{
    int rndSprtNum = (arc4random() % 5) + 1;
    CCSprite *first = CCSprite::create("sprite%d.png",rndSprtNum);

    rndSize = rndSize+(arc4random() % 20) + 15;
    int  width = rndSize + 125*(size.width/768);
    rndSize = rndSize + 90;
    first->setPosition(ccp(width,512 * (size.height/1024)));

    this->addChild(first,0);
}

```

Is this possible in cocos2dx v3.0?

# Answer
How did you get the idea that you could use CCSprite::create like that? the correct syntax would be:

```
CCSprite::create(CCString::createWithFormat("sprite%d.png", rndSprtNum)->getCString());

```

Other than that your code seems to be fine, except I don't get what it's supposed to do, which is a little bit alerting.

Seriously, did you even try compiling that code? You should get a compile error...
> 1 votes

# Answer
The question refers to **cocos2d-x 3.0**. `CCSprite` has been deprecated in favor of `Sprite` and the `CCString` in favor of `std::string`. Actually, most methods in recent versions, accept only `std::string` and the prefix `CC` has been deprecated from most classes.

Therefore the following would be correct (and not deprecated):

```
std::ostringstream oss;
oss << "sprite" << rndSprtNum << ".png";
Sprite *first = Sprite::create(oss.str());

```
> 0 votes

# Answer
If you need to use CCString, it is now \__String in Cocos2d-x v3. This will have all the same functions, also a great way to find the new versions is typing in the deprecated version aka CCString thne right clicking it and pressing jump to definition.
> -1 votes

---
Tags: cocos2d-x
---


# Question
Title: What version of Marching Cubes bring "ambiguities"
I am reading Eric Lengel’s paper about the Transvoxel algorithm.

In an early part describing the classical Marching Cubes (3.1.1), he talks about ambiguous cases. From what I understand, these can result from grouping the cases into “equivalence classes”.

However, in the Marching Cubes paper I read (is this the one he is referring to ?), there does not seem to be any grouping done, and each of the 256 cases produces its own triangulation. For example, taking the case of Lengyel’s figure 3.2 (on page 12 of the first document), the left cube has index 189 (vertices 0 2 3 4 5 7) and the right cube index 24 (vertices 3 and 4), which gives non “equivalent” triangulations: 4 triangles for the left cube, and 2 for the right cube.

To phrase this as a question: are there different versions of Marching Cubes, and could Lengyel be referring to a different one than Paul Bourke's ?

# Answer
The original 1987 paper on marching cubes reduced the 256 cases to 15 using symmetries and 'complementary cases'.

The Eric Lengyel paper you link describes what an ambiguous face is and how if two adjacent cubes sharing such a face disagree on its interpretation there will be a hole in the triangle mesh at that face. (Section 3.1.2).

The original paper had exactly such a disagreement wherever a complementary case cube shared an ambiguous face with a non-complementary case cube: Neither the triangle edges nor the inside/outside interpretation would match up at such a face and so there would be a hole in the mesh. The discrepancy was picked up quite quickly (Dürst, 1988) so subsequent treatments of marching cubes are likely to handle these cases correctly or, failing that, at least consistently.
> 3 votes

---
Tags: marching-cubes
---


# Question
Title: Why are shadows not snapping to the objects?
I'm using a directional light in Unity to cast shadows. However, the shadows don't appear to be "snapped" to the objects creating them. The object appears to be floating in mid air while it actually isn't.

How do I "snap" the shadow to the objects so it looks like it's actually on the ground?

# Answer
Check out the Bias property on your light. From the documentation (specifically the "Shadow Mapping and the Bias Property" section):

> It is a mistake to set the bias too high, however, since areas of a shadow near to the object casting it can then sometimes be falsely illuminated. This effect is known as “Peter Panning” (i.e. **the disconnected shadow makes the object look as if it is flying above the ground**, like Peter Pan).

I suggest you lower the bias value. But don't lower it too much! If it's too low you'll get shadow acne.
> 2 votes

---
Tags: unity, shadows
---


# Question
Title: MonoGame SharpDX Error 'The Parameter is Incorrect' when using graphics.DrawUserPrimitives
Below is a small section of code that is meant to draw a multicolored triangle to the middle of the screen in a MonoGame game. This uses the basic function `DrawUserPrimitives` to draw the triangle. This works fine in XNA, but the moment i try to use it in a MonoGame DX game (Which compiles using SharpDX) it will crash with the following error:

*An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll*

*Additional information: HRESULT: \[0x80070057\], Module: \[General\], ApiCode: \[E\_INVALIDARG/Invalid Arguments\], Message: The parameter is incorrect.*

Below is the code that is causing the error.

```
private void SetUpVertices() {
        vertices = new VertexPositionColor[3];

        vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
        vertices[0].Color = Color.Red;
        vertices[1].Position = new Vector3(0, 0.5f, 0f);
        vertices[1].Color = Color.Green;
        vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
        vertices[2].Color = Color.Yellow;
    }

    public void Draw(GameTime gameTime) {
        gDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);
    }

```

Has anyone ever come across simillar errors using the DirectX version on MonoGame and SharpDX when dealing with primatives? And do you know of a way I can fix this issue?

# Answer
> -1 votes
I had this all the time when building my engine core code it means you passed something to directx that isn't correct.

At a glance it appears you are passing a vertex array to a draw call .. this doesn't seem right to me although I haven't used monogame in some time (my code is sitting on the raw SharpDX API) so they may have done some wizardry to allow this but my get feel is that you need to put your vertices in to a buffer first then call draw on the buffer.

That said ... This question seems to imply that its fine and that actually you are missing your effect ...

Drawing simple geometric figures with DrawUserPrimitives?

---
Tags: xna, monogame, sharpdx
---


title: Tilemap collision problem

text:
# Question
Title: Tilemap collision problem
I have a method here that returns true if a collision is detected between the player and tile.

```
            private bool CheckCollision()
    {
        foreach (CollisionTile tile in map.CollisionTiles)
        {
            if (tile.TileType == "stone" && player.rectangle.Intersects(tile.Rectangle))
            {
                return true;
            }

            if(tile.TileType == "water" && player.rectangle.Intersects(tile.Rectangle))
            {
                return true;
            }
        }
        return false;
    }

```

The collision detection works fine but when I try to move away from the tile I don't move at all. What could be my problem here?

```
              if (!CheckCollision())
        {
            player.Update();
        }

```

this is in my update method.

# Answer
Here is a way to do it:

Update your player's position by storing a vector of the input result, then check collisions with only the movement in y, if there's no collision, you can simply add the y movement to the player's position and do the same with the x movement. If there's a collision, check how far you can go with this x or y component, then add it and so the same for the second component.

It's kind of tricky to help with collisions if we don't know how you are moving, if you are using a momentum based movement or how your whole system is built.

Essentially, the way you are working right now seems to check collisions and only update the player if he can move. With the method I explained above, you are sure that your player will move. And only stop in one direction if it hits something. Hope this helps, otherwise please post some code!
> 1 votes

---
Tags: xna, c#
---


# Question
Title: Downloading 10 images and storing their data with WWW
I would like to download 10 images, and store their texture data into my list. I don't really know how to do that - I heard that for this you use the WWW class, so I went:

```
List<byte[]> StartDownload() {
    List<byte[]> result = new List<byte[]> ();
    for (int i = 0; i < 10; ++i) {
        WWW request = new WWW("http://www.example.com/" + i + ".png");
        result.Add(request.texture);
    }
    return result;
}

```

Which of course doesn't work, but I'm not sure why.

# Answer
You have to use the `yield` command so that unity will wait for the texture to download before subsequent code is executed.

For Example.

```
// Get the latest webcam shot from outside "Friday's" in Times Square
var url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
function Start () {
     // Start a download of the given URL
    var www : WWW = new WWW (url);
    // Wait for download to complete
    yield www;
    // assign texture
    renderer.material.mainTexture = www.texture;
}

```
> 1 votes

---
Tags: unity, textures, http
---


# Question
Title: most effective storage of logged information
I am currently implementing basic logging of information on my multiplayer game and I want to have the most effective method.

To log when a player connects and disconnects to a the server it currently saves the info in one of two global txt files, one for the entire servers connections one for disconnections (a new pair for each day).

Taking into consideration the file sizes, that they are to be written to and not read from, organisation and problems with a large amount of players, **would it be more effective to store the data:**

A. In daily files

B. In monthly files

C. In yearly files

**And should the files be:**

1.combined in a single txt file

2.seperate in two txt files

3.combined individually for each player

4.seperate but for each player

Or 5.Another alternative I haven't thought of.

**Which way should I use and why?**

(also I know the difference between one or another could be dependent on the exact use so the best overall performance/organisation)

P.s if you don't understand the way I've said or worded something ask and I'll try to explain it better.

# Answer
The overall problem by using any text-based solution is that they are highly unreliable and naive implementations are often prone to data integrity issues. This is where david's suggestion to use a database becomes important.

Databases offer you the ability to write entries to a table without worries about concurrent operations from other connections. Additionally, databases offer recovery mechanics where if the database crashes, it can attempt to recover and play back operations against the database that were in memory but not yet written to disk at the time of failure.

All this becomes critical, particularly in more transaction oriented operations such as trading items between players, sending in-game mail, and so forth. It's important things aren't capable of being duplicated by fooling the system and that the operation occurs atomicly without any side affects due to concurrency.

Logging in and of itself may not be a *critical* operation, but databases can also provide you a way to store information in a partitioned way to where information can be accessed in a much faster way than sequential searching through a text file. A single table can be split across multiple partitions to speed up queries that are against more recent activity versus that of older activity. Databases offer you indexing mechanics to where queries against specific column criteria can quickly find rows that fit your criteria.

If you're running a game server, chances are at some point you'll need a database to back a bit of your game's information. Might as well use it for this as well :P.
> 4 votes

# Answer
You might want to consider logging to a database, such as MySQL or one of the various "nosql" plain old tables.

(If your user base is "massive", there's paths to scaling with more servers or outside services like Amazon or Azure...)

In one table, you can have a row for each log entry, and a column with things like the time, the player, the action (log on, log off), or other events of interest.

This is convenient for aggregation of various metrics, it's exactly what databases are good at.

As for how often you switch to a fresh table, or delete your data, really depends on how full it's getting and if you have any privacy or data retention agreements with the players.

-- I was thinking of this a little more. For an easy an maybe good-enough approach, by all means just append to one file with log entries.

If there's threads involved, use a thread-safe queue of things to append, and then poll and append from just one place.

One file per day, and a folder for each year, as a wild guess to start, would probably be fine. Easy to think about, easy to label the folder & filenames appropriately, easy to grep.
> 2 votes

---
Tags: multiplayer, mmo, data, storage
---


title: OpenGL (ES 2.0) Function Dependencies

text:
# Question
Title: OpenGL (ES 2.0) Function Dependencies
In OpenGL (ES 2.0), there are many functions that can be called in any order, and still others that must be called after other functions had been called and not before.
For example, attaching a shader to a program requires a valid program so `glAttachShader` must be called after a call to `glCreateProgram()`. `glCreateProgram()` must be called after GL initialization etc.
Any functions that assume a certain "current" state, depend on the functions that set this state previously (defaults notwithstanding).
Such a dependencies necessary conditions for correct functioning (but not necessarily sufficient).

Is there a document or diagram somewhere that explicitly shows these dependencies and independencies? All I found were the occasional implicit mention in the texts.

This would be very helpful for debugging, learning and understanding the framework structure and also for developing higher-level tools that abstract away some of the low-level complexity.

# Answer
> 4 votes
Well, OpenGL is a state machine, so inorder to plot function dependencies you need to plot a state machine, there is this one that models the most recent versions of OpenGL pipeline including ES2.0 and 4.0. Unfortuantely I couldn't find a diagram the plots function dependencies but I guess that can be mostly deduced from the state machine.

---
Tags: opengl, opengl-es, opengl-es2
---


# Question
Title: How to update libgdx scene2d Label text dynamically?
I display a `BitmapFont` on the screen, update its text and the font is updated dynamically on the screen as well.
I seem to fail to do the same with a scene2d `Label` added as actor to a `Stage`.
The `act(delta)` and `draw()` methods are being called in the `render()` method.
My code basically looks as follows:

```
public void init() {
    Label label = new Label(text, labelStyle);
    stage.addActor(label);
}

public void update() {
    updateText(text);
}

@Override
public void resize(int width, int height) {
    /* do some resizing */
    label.setPosition(newPositionX, newPositionY);
}

@Override
public void render(float delta) {
    /* do some rendering */
    stage.act(delta);
    stage.draw();
    update();
}

```

Do I need to do anything other than setting the `Label` text, adding it to the `Stage` as actor, and then updating the text elsewhere? The label displays its original text, though the text updating works fine.

Thanks.

# Answer
I have decided to answer my own question to provide the solution I have come up with, in case someone may find it useful:

I have extended the `Label` class and overridden the `act(float delta)` method of the new custom label:

```
public class CustomLabel extends com.badlogic.gdx.scenes.scene2d.ui.Label {
    private String text;

    public CustomLabel(final CharSequence text, final LabelStyle style) {
        super(text, style);
        this.text = text.toString();
    }

    @Override
    public void act(final float delta) {
        this.setText(text);
        super.act(delta);
    }

    public void updateText(final String text) {
        this.text = text;
    }
}

```

The `updateText(String text)` method is then called from outside whenever the text of the label should be updated.
> 4 votes

# Answer
You can call `.setText("Some String");` on your label in your `Render`-method.
> 11 votes

---
Tags: java, libgdx
---


# Question
Title: How to move a body from one world to another?
I have a Box2D world for each level in my game. When a level is completed, I want the player to be removed from the completed level's world and added to the next level's world. How do I do this?

# Answer
> 1 votes
I would start here ...

http://www.iforce2d.net/b2dtut/removing-bodies

Then end with a sprinkling of ...

http://www.iforce2d.net/b2dtut/bodies

I'm guessing the latter you already did, so essentially you are just doing the first part in reverse.

---
Tags: c++, box2d
---


title: How to increase speed of GameObject?

text:
# Question
Title: How to increase speed of GameObject?
I'm making pong game in unity3d with monodevelop(c#). I want to increase speed of ball when it touch ends of paddle corner.

my ball script:

```
using UnityEngine;
using System.Collections;

public class ball : MonoBehaviour {

    public float InitialSpeed=1.0f;

    void Start () {
    float  xDir=Random.Range(-1.0f,1.0f);
        rigidbody.AddForce( new Vector3(xDir,-1.0f,0)*InitialSpeed);
    }
}

```

# Answer
> 0 votes
I think you want like this.

```
void OnCollisionEnter(Collision collision)
{
    float velo=collision.rigidbody.velocity.magnitude;
    Vector3 V3=collision.rigidbody.velocity;
    V3.x = (collision.transform.position.x - transform.position.x)*8;
    collision.rigidbody.velocity = V3;
    if(collision.rigidbody.velocity.magnitude < velo)
    {
        collision.rigidbody.velocity *= velo/collision.rigidbody.velocity.magnitude;
    }
}

```

Add this code into your script.

# Answer
> -1 votes
Assuming that you are in a 2D plane,speed has is created by 2 separate vectors (because you can move on the x and y axis).If you want to increase the speed of an object which has a certain direction increase/decrease the value for the dimension you want to have your speed increased into.

---
Tags: unity
---


# Question
Title: Only render/calculate the chunks in frustum!
I have a 2D world in form of a Block\[\]\[\]-Array that holds all the blocks of the world. Every block has it's own Box2D Body (I want a "minecraft"-like 2D world for this project). Naturally I don't want to calculate all the box2D-bodies at the same time and I don't want to render what's not on screen neither (SpriteBatch).

So I divided my huge world into "Chunks". They are all of the same width and height. Now I'm a bit stunned though.

Each chunk starts at (0,0) which is the lower left corner of the chunk. Now in my player-class I do the following (if the player has moved)

```
public void calculateChunksToRender()
{
    for(int x = (int) this.getPosition().x - Chunk.chunkWidth * 2 - (Chunk.chunkWidth / 4); x >= 0 && x <= game.getMap().getWidth() - Chunk.chunkWidth && x<= (int) this.getPosition().x + Chunk.chunkWidth; x++)
    {
        if(x % Chunk.chunkWidth == 0)
        {
            Vector2 chunkPosition = new Vector2(x, 128);
            System.out.println(chunkPosition);
            chunksToRender.put(chunkPosition, game.getChunkMap().get(chunkPosition));
        }
    }

```

As the start point of the x-coordinate in the chunk is on the left side, I go 1 3/4 chunks to left and render it, if still visible. Why 1 3/4? Because that way when I'm 3/4 to the right I don't see the left chunk anymore, so I don't need to render it. For the right chunk I do the same, but only with Chunkwidth... I guess it's pretty self-explanatory though.

Obviously this is just the X-dimension and I'm not sure if there isn't a far better way to do this. Why? Because, well, right now I have 3 chunks to render, but basically I have a 8-neighbourhood around the one chunk the player is currently on/in. I fear that I will have to render/calculate (the physics for) far too many bodies the way I'm doing it right now. Currently I have 12k bodies in memory at any given time and around 45-60fps. But that's just 3 chunks!

Each block has its sprite attached to it through the box2D body (userData), maybe I should separate them and separate rendering/physics calculation as well? Not sure though, because if a player jumps to another chunk I want him to collide with the blocks there immediately not after a delay (so he is stuck in the middle).

I also tried to calculate the nearest chunk (just go left on the x-axis and down on the y-axis until you find a chunk) and calculate the surrounding ones, but that's much more of a performance hit (logically)

Any ideas/optimizations?

Kindest regards, Ohuro

# Answer
> 1 votes
Firstly, going left and down to find the nearest chunk isn't necessary - chunk/local (that's the pair of terms I use in my engine) can be calculated like this:

```
ChunkX = Floor(PlayerX / ChunkWidth)
ChunkY = Floor(PlayerY / ChunkHeight)

```

The position relative to that position can be calculated like this:

```
LocalX = Floor(PlayerX % ChunkWidth)
LocalY = Floor(PlayerY % ChunkHeight)

```

This (in case it isn't obvious) means that to get the chunk coordinates you divide by the chunk size on each axis, and to get the coordinates relative to that chunk you get the remainder that doesn't evenly divide into those sizes.

Calculating adjacent chunks to one shouldn't be expensive at all - you just increment the coordinates on each axis. I'm not sure what you're doing currently, but I'd do something like this:

```
List<Chunk> GetSurroundingChunks(Vec2 position, int range = 1)
{
    List<Chunk> chunks = new List<Chunk>();
    int cx = position.X / ChunkWidth;
    int cy = position.Y / ChunkHeight;
    for (int y = cy - range; y < cy + range; y++)
    {
        for (int x = cx - range; x < cx + range; x++)
        {
            chunks.Add(WhereverChunksComeFrom[x, y]);
        }
    }
    return chunks;
}

```

That of course does a square around the given position, but it could be modified to do a circle or what-have-you.

---
Tags: libgdx, box2d, block-world
---


title: Recording time since last collision

text:
# Question
Title: Recording time since last collision
I am trying to record time since the last collision happened.But this is not working as I expect it to.

So, numberLimitOfCollision is equal to 0 only in the begining, Basically, what I am trying to achieve is increase the number of collisions by 1 if new collision occurs with in a second otherwise make the variable back to 1. This is what I have tried so far:

```
void Update()
{
 while (collision == false && numberLimitOfCollision != 0) {
            timeSinceLastCollsiion += Time.deltaTime;
                }
                if (timeSinceLastCollsiion > 0.8 && collision == false) {
                        timeSinceLastCollsiion = 0;
                        numberLimitOfCollision = 1;
                }
             else if (timeSinceLastCollsiion < 2 && collision == true) {
            numberLimitOfCollision = numberLimitOfCollision + 1;
                        }
}

void OnCollisionEnter(Collider col)
{
collision = true;
}
void OnCollisionExit(Collision x)
{
collision = false;
}

```

Where I am going wrong?

# Answer
Why would you start a loop inside Update?

```
float lastCollisionInstant = 0; //Store last collision timing
const float collisionInterval = 1.0f;

void OnCollisionEnter(Collision other)
{
    if(other.gameObject.name == "Enemy")
    {
            float collisionInstant = Time.time; //This collision instant

            if(lastCollisionInstant - collisionInstant < collisionInterval) //Time elapsed since last collision
                numberOfCollision += 1;
            else
                numberOfCollision = 1;

            lastCollisionInstant = collisionInstant; //Set last collision time
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Numerical integration of multiple off-center forces on a solid body
I am trying to develop a little simulation (for the sake of learning a little bit about physics) involving a circle (mass m, radius r, regular density) and two forces f1, f2 that can be applied on any two points within the circle.

I have read that when a force doesn't go through the center of mass, then you have to split it up into two components, one parallel to the offset and one perpendicular to it. The parallel part of that force obviously now goes through the center of mass and thus "a=F/m" applies whereas the perpendicular force applies a torque, allowing me to use "alpha = torque/moment of inertia".

In my tests, this has worked perfectly, for as long as only *one* force acts on the body at a time.

However how (if at all) do I need to resolve multiple forces that influence the same body? At first I thought I can simply resolve each force in the pattern I described above and thus I calculated the sum of the linear forces on the CoM as well as the sum of the torque components. However this doesn't work for a number of examples, such as one where f1 and f2 act on either "side" of the circle in the same direction and both have the same length. For each individual force, there is no parallel component and thus no force is acted on the body. The sum of the torque is 0 as well, thus the body is not accelerated at all. However from playing KSP I realize that the net force applied on the body should be f1+f2.

This problem should have been solved numerous times, however I am unable to find a proper numerical solution (or don't use the right search terms). Can you guys help me out?

# Answer
You were mistaken about how to separate the forces.

The torque applied is the cross product between `a_t` and `r` where r is the vector from center of mass to the point the force is applied to. (or `length(a_t)*length(r)* sin(theta)` with theta the angle between the two)

The translation force is just `a_t`.

These results can be manipulate independently which means that your symmetric forces example (where `theta1==-theta2`) produces no torque (because `length(a)*length(r)* sin(theta)+length(a)*length(r)* sin(-theta)=0` and all acceleration.

On Physic.SE there are several questions explaining it.
> 0 votes

---
Tags: physics, body
---


# Question
Title: Traditional Chunk Loading vs. Chunk Swapping
I'm designing a voxel-based game (aren't we all?), and just yesterday implemented infinite terrain generation. I'd already had the terrain generation working off of simplex noise, so this wasn't a problem, and I've worked a lot with terrain generation before.. Anyway, I found myself hitting performance issues with the huge increase in "stuff to draw", so I started optimizing and disposing of vertex buffers for chunks that were out of frustum, then created a "SurroundingChunks(Vec3 position, int range)" function that as you may assume returns the chunks surrounding a position within a range. I used this to cull the chunks being even considered for drawing before the frustum check.

Performance is pretty good when it isn't generating new chunks (haven't multithreaded yet), but after I had already worked out the performance issue I came across an alternate solution, and I was wondering how it would compare.

In a normal chunk-based terrain, the player moves around in the chunks and chunks are loaded and unloaded depending on some algorithm/methodology. In this alternate method, there are a fixed number of chunks in existance. For the sake of simplicity, let's pretend we have a chunk-view-distance of 1, i.e., 8 chunks around the player and the one he's standing on for a total of 9. Instead of allowing the player to roam around infinite chunks, the chunks are replaced with others as the player proceeds in a direction. This could mean the player never moves, and some movement buffer dictates chunk changing, or it triggers when the player moves over a chunk boundary and then resets the player to the center (like many FPS mouse schemes, but with a player in 3D).

I drew a crappy little diagram in mspaint (don't have better tools on hand) to help illustrate this concept:

I'm curious whether this would perform better than doing all of the detection work for chunks in range and frustum culling followed by unloading any unneeded chunks, since it wouldn't require as much detection work. However, I am concerned that it would complicate things in the future, for example when there are enemy entities - they would have to constantly be position shifted with the land, etc..

I was hoping perhaps you guys would chime in with thoughts, pros, cons, opinions, etc.. :3

# Answer
> 0 votes
Thinking about how we render our virtual worlds you do several things ...

1. setup a vertex buffer
2. setup a shader stack
3. set some constants (world, view, projection) for the frame and object

So logically thinking about that, to move the entire world 1 chunk in any direction what do I actually change on my normal render cycle ...

...

Nothing ... I do the same in my draw calls, but in my update loop I update my root object transform and all children inherit that change and the render loop continues as normal.

So,

With moving a chunk effectively being "free" I can't see an issue moving the whole world when a player steps over a chunk boundary.

However ...

I took a more liberal approach by setting "areas" in which the player could be to prevent a constant recalculation of the transform information.

For example:

lets say im moving ---\>\>\>\>

c1, c2, c3, c4

when i move from c1 to c2 I do nothing, when I move from c2 to c3 I move the world back by 2 chunks.

How does this help ... Lets say a player is having a rather large fight and every frame counts but they are doing this right on a chunk intersection or worse on the corner of a chunk so this applies in 3 dimensions. Having that 1 chunk buffer means I make the change once until the player moves a reasonable distance so the "expensive but still cheap" math only happens once for that area.

I apply the same logic to loading and unloading chunks on my world edges too to sort of apply a "temporary cache" around the currently being rendered terrain.

# Answer
> 0 votes
A combination of both methods is what I've used in the past. Essentially your character is still moving around in the world with a set number of chunks following them. Each axis of the chunk array is like a conveyor belt of chunks, shifted when new chunks are loaded and old chunks unloaded. Make sure you're not reloading chunk data when shifting it, just changing the references. Only the leading edge of the grid of chunks should be loading new.

However, if you wanted to move everything around the player, it's not so bad. If you have the entire world all children of one object transform, and the player outside that world, all you have to do is move the world transform to move everything in the world.

---
Tags: performance, terrain, loading, culling, dynamic-mesh
---


# Question
Title: How to sync gamestate between server and clients in turn based 4x game?
**Background information:**

I am developing a game similar to other 4x games like Sots, MoO,...

I am storing all information about the game(like star/planet/ship/fleet positions, owners and a lot of other stuff) in a data structure in memory. I call this structure the datastore.

I have one client act as server.

All clients should have a copy of the datastore, because in case the server disconnects another client could overtake the server role.

On the end of every turn all changes the clients did should be stored in the server datastore.

If it is important I use C# and Unity Pro.

**Question:**

After all client changes are applied to the server should I just copy the complete datastore to each client or is the way to go to sync only the changes made?

I would appreciate to get answers that not only include personal opinion but more about drawbacks or advantages of the different approaches.

# Answer
The way I see it there are effectively 2 ways to handle this.

1. every "command" a user intends to issue is stacked up in a local list then sent to the "server" at the end of each turn who then forwards on the lists from other players to ensure the data is replicated to all players.
2. Every time a player issues a command to be added to the list of things for this turn its immediately passed to the server then at the end of the turn a final "im done" is received from each player and the server triggers a new turn.

The sync would happen in the same way in both situations a list / list per player is built and at the end of each turn the list(s) are processed by all.

The 2nd approach seems to be a bit better in that at the end of the turn its all action and no waiting for network sync however lists are in a sort of "fluid state" until the end of the turn as a player may chose to undo a previous command I guess as it's technically not "official" until the turn ends.

That said its just a "undo" request each time that happens.

I'm sure there are many other ways to do this but this is essentially how I would go about it :)

By having every client periodically dump key information to disk you could then effectively reload the game if any 1 player had their copy of the data intact.
> 1 votes

---
Tags: networking, multiplayer, client-server
---


# Question
Title: How do game servers / clients handle data?
How do servers handle data? I understand the concept of the client sending the player pos and then the server sending back the area to display and also sending other player positions and such.

But how does a server save al the player positions? In its memory or how?

I was thinking about the client walks so it sends x: 100, y:100 to the server The server validates if the client didn't cheat like walking to fast or through a wall or something and then the server responds with the correct data, other player positions, monster positions and such. Am I miss understanding something how servers work? and how should a server handle / save all the player data? I was thinking at writing everything to the data base once every x minutes?

For the landscape rendering, I was thinking about the server sending back an array with numbers like 1 dirt 2 grass and so on. The recieving client will then display those numbers into goodlooking tiles. Is this a good way to render landscape?

I was like thinking of 2D game like Realm of the mad god.

# Answer
> 3 votes
It's more ...

1. A connection is opened to between the server and the client.
2. The server asks for some basic params like "who are you".
3. Client sends "im this user".
4. Server sends "ok you're at pos xyz, on map, foo, get ready!".
5. player sets up anyhting it needs to in order to get a world rendered and the player in the right part of it.
6. Server begins streaming updates as they happen to all clients connected.
7. Clients push events as the player triggers them.

This is the "simplified version" of course. There are other things like validation taking place but from your question I guess you are referring to something like minecraft where a player at any point can click to add or remove a block.

In this situation the server makes a client call to each client to say "player x added/removed this block" then also makes an internal call to say "save this change to the world data".

that internal call may make the change immediately however it may not ... most game engines due to load / possible file locking / thrashing problems stack up commands and perform them in a batched fashion but there's no law that says this must happen.

So in short ...

The server always has the current up to date state of the current area in which all players are operating, and is able to "own them as you would expect from a server".

Clients react to event notifications as they are given.

With the predictive movement case exception.

Prediction means that I can (for example), when player hits forward key, send packet to server to say "player begins moving" then start the player moving. If the server comes back later and says "oi that's stupid there's a wall in the way, go to pos xyz and stop" then I react to that but in the meantime assuming I as a player didn't do something stupid then all is good and later the server confirms my good choice.

This is why on some games if you get a lag spike you can walk through walls temporarily.

# Answer
> 2 votes
From what I've gathered, and believe me, I'm no expert, the "usual" way to do a client server game is to have the game running on both. The server can also be a player. The way you should look at it is, there's two types of data in the game; synced and non-synced.

All logic that affects how the game is played should be synced between the clients. This logic should only run on the server, and a visual representation should appear on the client. For example, imagine you have a server and one client. You have one player character in the game that can move. So, from this we know we have two copies of the player's data; one on the sever, one on the client. The "real" player should be kept on the server. So, we move the server copy only, and immediately sync the new position, rotation etc to the client so that it can correctly draw the player's current state. The client should only be responsible for a visual representation. Most the game logic is not actually running on the client.

Then there's non-synced data. This may include stuff like particles, or other visual effects that don't need to be synced as they have no affect on game play and may actually be very costly to sync.

You should focus on sending as little data as possible to the clients. If it's not important to the game play, there's not much reason to sync it. Using this method, it's not likely that someone will be able to cheat( unless the sever IS a player ), because all important data comes from the server.

# Answer
> 1 votes
As mentioned in previous comments and answers, there are 2 major scenarios and a few subscenarios... player hosted server and server hosted server being the major setups. However it makes little difference IMO because I feel that even for player hosted servers, the server portion of the code should be separated from the client code even on a player hosted configuration.

The next 2 questions concern how many players the server is designed to handle, and how authoritative the server is over the current state of the game. For small numbers of players (8-16) and a client authoritative design, the server can be little more than a message hub, taking in client packets and replicating them to the other players. For larger numbers of players, server hosts servers and some form of space partitioning on the server is needed so that you are only sending packets that are RELEVANT to each player. Server hosted is almost required at this point because beyond 8-16 players, even the best broadband connection to the net may not be enough for all the outbound network traffic being sent to the players... most network connections have much lower send speeds compared to receive.. for instance, my connection is 20mbits down, 2mbits up... so I can receive a lot more than I can send.

The last section talked about client authoritative design. In server authoritative designs for player hosted servers, the server code is typically very tightly integrated with the client code because the server needs access to the current state of everything that can move in the game, and needs to be at least somewhat aware of the physics of the game. For server hosted servers all of the object state, and at least some of the map state (that part required for setting up physics colliders and such) has to be replicated on the server.

You mentioned predictive motion, and that is a "feature" that can be layered on top of any of these scenarios, and basically involves having the clients and server running on a synchronized clock established when the player connects to the server.. movement update packets must have time stamps so that the client/server can say things like "if the object was HERE in the past, and is moving in this direction at a given speed, I compute where the object is NOW, and possibly where the object will be a short time in the future"... then the network layer kind of lies and tells the client code "the object is moving along this vector (direction/speed) from its current location" with that vector computed to put the object at the future computed location at the desired future time. None of the clients will see exactly the same motion of all the objects, but in general tracking will be smoother without annoying jumps because of network lag.

I found this presentation VERY informative and it might help make things more clear for you

http://www.gdcvault.com/play/1014345/I-Shot-You-First-Networking

---
Tags: c#, server
---


# Question
Title: Box2D `ApplyLinearImpulse` is not working whereas `SetLinearVelocity` works
I need to mimic jumping behavior for the player in my game. Player consists of two fixtures with circle and rectangle shapes. Rectangle I use to detect ground and it is a sensor. Is some point for jumping I do this:

```
float impulseY = body->GetMass() * PLAYER_JUMPING_VEOCITY / PTM_RATIO * std::sin(PLAYER_JUMPING_ANGLE * PI / 180);
body->ApplyLinearImpulse(b2Vec2(0, impulseY), body->GetWorldCenter(), true);

```

and player does not jump. But when I do this:

```
body->SetLinearVelocity(b2Vec2(0, PLAYER_JUMPING_VEOCITY / PTM_RATIO * std::sin(PLAYER_JUMPING_ANGLE * PI / 180)));

```

my player jumps. Also when I change the rectangle shape to be normal (not sensor) shape, its works again. Why? Just in case here are the parameters of my rectangular sensor:

```
b2PolygonShape boxShape;
boxShape.SetAsBox(width * 0.5/2/PTM_RATIO, height * 0.2/2/PTM_RATIO, b2Vec2(0, -height * 0.4 /PTM_RATIO), 0);

b2FixtureDef boxFixtureDef;
boxFixtureDef.friction = 0;
boxFixtureDef.restitution = 0;
boxFixtureDef.density = 1;
boxFixtureDef.isSensor = true;
boxFixtureDef.userData = static_cast<void*>(PLAYER_GROUP);

```

# Answer
I think I got the reason. When I detect jumping time with sensor rectangle, the body at that time sill has velocity towards down. And when I give him impulse towards up direction it decreases its speed towards down (as it turns the impulse was small) and I think that it does not jump. But in case I apply linear velocity, it just starts to move up the the given velocity. Also in case I change the rectangle to be not sensor, I think it collides with ground and its Y velocity becomes 0. Hence is this case when I apply linear impulse it jumps up. Makes sense? :)
> 1 votes

# Answer
Did you try applying an hardcoded (big) impulse instead ? Or check that the mass is not 0 for example (maybe you need to call some recalculate() function to set the mass from density, for sensors).
> 0 votes

---
Tags: c++, box2d
---


# Question
Title: Finding and reading a script on a mouse-selected GameObject
I can't work out how to access and read changes in a script of a gameObject that has been selected. The script selects enemy objects with right mouse button and player objects with left mouse button. I want to be able to make the enemy null and deselect it when its health reaches zero but I cannot get past the

"NullReferenceException: Object reference not set to an instance of an object"

problem. I have commented out the section of code where it should be accessing the enemy's vitals script to see what its health is.

Here is the script I'm using:

```
public class CameraDetectClick : MonoBehaviour
{
        Ray ray;
        RaycastHit hit;
        public GameObject currentlySelectedPlayer;
        public GameObject currentlySelectedFoe;
        public EnemyVitals enemyVitals;
        public bool selected;

        void Start()
        {
                enemyVitals = GetComponent<EnemyVitals>();
        }

        void Update()
        {
                if(Input.GetMouseButton(0))
                {
                        ray = camera.ScreenPointToRay(Input.mousePosition);

                        if(Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.collider.transform.FindChild("SelectedPlayer"))
                        {
                                currentlySelectedPlayer = hit.collider.transform.FindChild ("SelectedPlayer").gameObject;
                                currentlySelectedPlayer.active = true;
                                selected = true;

                        }
                        else if (Physics.Raycast(ray, out hit, Mathf.Infinity) && (hit.collider.name == "Ground"))
                        {
                                if(currentlySelectedPlayer != null)
                                {
                                        currentlySelectedPlayer.active = false;
                                        currentlySelectedPlayer = null;
                                        selected = false;
                                }
                        }
            }
                if(Input.GetMouseButton(1))
                {
                        ray = camera.ScreenPointToRay(Input.mousePosition);

                        if(Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.collider.transform.FindChild("SelectedFoe"))
                        {
                                currentlySelectedFoe = hit.collider.transform.FindChild ("SelectedFoe").gameObject;
                                currentlySelectedFoe.active = true;
                                selected = true;
                                //here, the beasty foe has been selected, so I need to grab and monitor its vitals script so I
                                //can see when it drops to zero. This does not work as it says I need to set it to an instance of an object.
                                enemyVitals = currentlySelectedFoe.GetComponent<EnemyVitals>();
                                if(enemyVitals.currentBeastHealth == 0)
                                {
                                        currentlySelectedFoe.active = false;
                                        currentlySelectedFoe = null;
                                        selected = false;
                                }
                        }
                        else if (Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.collider.name == "Ground")
                        {
                                if(currentlySelectedFoe != null)
                                {
                                        currentlySelectedFoe.active = false;
                                        currentlySelectedFoe = null;
                                        selected = false;
                                }
                        }
                }

        }
}

```

# Answer
The exception says there is no 'EnemyVitals' script attached on the related object. That's -probably- because you're trying to get that script from an inner game object which the ray hits.

You can get it from the root element with something like this:

```
component = targetObject.transform.root.GetComponentInChildren<ComponentName>();

```
> 1 votes

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


# Question
Title: Can't go above max speed with RigidBody2D.AddForce()
I'm having trouble making a character move faster than a certain limit using RigidBody2D.AddForce(). My game is a top-down 2D game (constrained to the x/y plane).

I'm using a float 'MovementSpeed' to scale a normalized vector passed to RigidBody2D.AddForce(), however, when I increase MovementSpeed past 1000, there's almost no noticeable difference in the object's "speed"; going from 100 to 1000 is a drastic difference, but there's almost no noticeable difference going from 1000 to 1000000. Here's my WASDMovement() function (called during FixedUpdate() ):

```
private void WASDMovement() {
    Vector3 translationVector = Vector3.zero;

    if (Input.GetKey(KeyCode.W)) {
        translationVector += new Vector3(0.0f, 1.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.A)) {
        translationVector += new Vector3(-1.0f, 0.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.S)) {
        translationVector += new Vector3(0.0f, -1.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.D)) {
        translationVector += new Vector3(1.0f, 0.0f, 0.0f);
    }

    translationVector.Normalize();
    rigidbody2D.AddForce(translationVector * MovementSpeed);
}

```

Here's a video demonstrating my problem to make it easier to see what I'm doing wrong: http://youtu.be/9kwKvfDOYoo

# Answer
A friend found a potential solution by increasing the Physics2D.velocityThreshold constant, I'm not able to test it currently since it's a 4.5 feature and I currently use 4.3 (downloading/installing 4.5 right now).
> 1 votes

---
Tags: unity, movement, rigid-body-dynamics
---


title: Get rid of the usual MUD cycles

text:
# Question
Title: Get rid of the usual MUD cycles
I am working on a MUD engine and I want to do it a little differently then all the MUD games I played. I find a "cycle" system very boring. One of the idea I had is to make every clients socket working in their own Thread. I am aware that it wont end with hundreds of player but I would like to know if there are problems creating "alot" of thread in a single process.

Or, what other strategy I could use if I want to make it (eg. combats) in "real-time".

I hope you guys understand the question.

Thank you.

# Answer
MUD cycles are generally not there because the server has trouble processing everything within the available time or serving network requests fast enough. They are there because spamming commands as fast as possible should not be a valid tactic.

Simply have a cooldown / charge-up timer associated with each ability. Depending on your social design this might also include "move" and "speak", or not.

Generally, having more than one thread per core for network processing in a game is pointless. If you are packet-processing-bound, then a thread per core will be maxing out your system - more threads would just starve the others of CPU time they need. If you are not packet-processing-bound, a thread per core is small enough that it won't affect the rest of the system via too many context switches.
> 14 votes

# Answer
Sorry about thread necromancy, but this problem is my FAVORITE pet-project for learning and teaching concurrency models and frameworks!

Running every client/mob in their own thread does give a natural division, but as several have noted threads are expensive when you use more of them than you have CPU cores. If this isn't a compelling reason not to use it in your MUD, it's still a good reason to learn a better way.

Running all clients in a single fixed-time game-loop, with actions taking some number of loops, is a familiar method from the world of graphical games. It does bind everything in the world to the same time-cycle, although making the loops sufficiently fine-grained can mask that. The main drawback of this method, as I see it, is that it is not inherently parallelizable. Someone noted that you can create threads to offload constructing/parsing/transceiving I/O, running AI and so on to other threads, but getting the main game logic parallelized requires a fundamental change and a lot of work to keep things thread-safe.

If you did all of that work, you'd probably end up with something akin to my current favorite, the Actor model (http://en.wikipedia.org/wiki/Actor\_model). The Actor model is a time-sharing strategy that ends up working out pretty close to what you were proposing with the one-thread-per-client idea. Using it, you code your "Actors" like they're standalone threads, with a few restrictions: they must be event-driven, and they can only communicate with the rest of the system by passing messages (which is different but simple). The event-driven bit makes room for your truly-independent-timing, by scheduling Actor-specific events to fire at particular times, e.g. when an action is completed or at some client-specific frequency.

Under the hood the implementation uses a queue (or queues) of messages being generated by all the actors, and a pool of threads matching your # of CPU cores. The threads pull messages off of the queues and the invoke the recipient Actor's message-handling methods to handle them, running in the context of that Actor until the message is "handled". From your point of view, each Actor gets its very own thread whenever it is actually running, but from the system's point of view there are only as many threads as there are CPUs to run them.

There are some great Actor frameworks out there, namely Erlang/OTP and Akka, but the basic idea is simple enough that you could implement it in any language without the additional fuss of a framework.

For completeness, the Actor model is really just the combination of message-passing for thread safety, event-driven programming for concurrency, and a thread dispatching mechanism. If you were to remove the thread-dispatch bits, you'd be left with a "reactive" system, which is very in vogue for scalability in general right now (see http://www.reactivemanifesto.org/). You could then map execution to multiple machines in a cloud or whatever... you get the idea... which is all to say that your MUD programming project may be teaching you marketable programming skills. Hooray!
> 5 votes

# Answer
You could allow combat commands as they come in and then add a time delay after commands based on how long they would take to execute.

Dragonrealms uses this method for combat as well as many other actions, it is called Roundtime there. Heavier weapons get a greater time and you can reduce it, but not eliminate it with strength and agility.
> 2 votes

# Answer
Networking is serial in nature anyway (at least until you get into multi-Tbps fibre-optic lines). Having one thread for network I/O separate from game logic and *maybe* some autonomous agent threads makes sense. Everything else is overkill.
> 0 votes

---
Tags: multithreading, mud
---


# Question
Title: Colision detection of disc (Maximum Material Condition aka "Flatness")
I have a 3D-laser scanner which gives me a series of points of a real-world object. The points are related by a common origin.

I know I can derive the equation of a plane from 3 points and that the "maximum material condition", "flatness" or "thickness" of the blob will be defined by a 4th point which has the greatest height-magnitude relative to the plane of the object.

**How do I choose which 3 points from a shape (which happens to look like a CD, as in it's disc-shaped) define the plane of the object?**

To account for any ambiguity in the question, I already know the diameter of this disc so even though that is technically the widest part of my blob, I actually want to know how "flat" it is. Basically if this "disc" were resting on a perfectly flat surface, what would be it's highest point?

**EDITS:** Question has been significantly edited, because I originally asked the "wrong" question. I'm stuck at the part where I'm try to find 3 points that define the plane this disc will rest on, before I find the 4th point that indicates how "thick" it is...

I can guarantee the disc will not rest on it's thin edge as it should almost be level or maybe tilted up to 15° when scanned. Essentially a disc may be scanned at a slight angle/tilt and that should not influence it's maximal thickness.

**Note:** My points come in as cylindrical coordinates initially, but I already wrote functions to convert back and forth to Cartesian3D and Spherical systems. I know which axis will be X, Y and Z but I have intentionally omitted that information as it should be arbitrary to any code.

Conceptual answers are very welcome, I can google to figure out implementation details.

```
using Common.FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Extensions;

namespace Common.Mathematics
{
    // Coordinate system conversions http://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates
    // Cylindrical Coordinates http://en.wikipedia.org/wiki/Cylindrical_coordinate_system
    // http://gamedev.stackexchange.com/questions/81713/how-do-i-translate-a-spherical-coordinate-to-a-cartesian-one
    // http://gamedev.stackexchange.com/questions/44738/spherical-to-cartesian-coordinates

    // World Frame
    /**********************************************************
     *                                                        *
     *                      +Height                           *
     *                   (Polar-Axis)                         *
     *                 (Elevation = 90°)                     *
     *                         |                              *
     *                         |  / +Depth (Rotation = 90°)   *
     *                         | /                            *
     *                         |/                             *
     *  -Length ---------------*--------------- +Length       *
     * (Rotation = 180°)      /|            (Rotation = 0°)   *
     *                       / |            (Elevation = 0°)  *
     *               -Depth /  |                              *
     *     (Rotation = 270°)   |                              *
     *                      -Height                           *
     *                 (Elevation = -90°)                     *
     *                                                        *
     **********************************************************/

    public static class Coordinates
    {
        // Config
        public static double Cartesian_Max_Resolution = 0.0000001;
        public static double Degree_Max_Resolution = 0.0000001;
    }

    public class Cylindrical
    {
        // Public Fields
        /// <summary>
        /// Horizontal vector distance from polar axis to point.
        /// </summary>
        public readonly double Radius;

        /// <summary>
        /// Height along polar axis (Graphically -Down, +Up).
        /// </summary>
        public readonly double Height;

        /// <summary>
        /// Angle (theta) of rotation (+ is counter clockwise) about the polar axis. Rotation of 0° is colinear with the positive Length-axis; 90° is colinear with the positive Depth-axis.
        /// </summary>
        public readonly double Rotation;

        // Constructor
        public Cylindrical(double p_radius, double p_height, double p_rotation)
        {
            // Init
            Radius = p_radius;
            Height = p_height;
            Rotation = p_rotation;

            // Correct Inverted Radius
            if (Radius < 0)
            {
                Radius = -Radius;
                Height = -Height;
                Rotation += 180;
            }

            // Limit Rotation from 0° to 360°
            Rotation = Rotation % 360;
            Rotation = (Rotation < 0) ? Rotation + 360 : Rotation;
        }
        public Cylindrical(Cartesian3D p_coordinate)
        {
            // Init
            double L = p_coordinate.Length;
            double D = p_coordinate.Depth;
            Height = p_coordinate.Height;

            // Horizontal Vector
            Radius = Math.Sqrt(L * L + D * D);

            // Atan2 returns -PI to +PI Radians
            // Adjust angle to be between 0° and 360°
            double DomainValue = Math.Atan2(D, L) * Constants.DEGREES_PER_RADIAN;
            Rotation = ((DomainValue >= 0) ? DomainValue : DomainValue + 360);
        }
        public Cylindrical(Spherical p_coordinate)
        {
            // Init
            double M = p_coordinate.Magnitude;
            double E = p_coordinate.Elevation * Constants.RADIANS_PER_DEGREE;
            Rotation = p_coordinate.Rotation % 360;

            // Calc
            Radius = M * Math.Cos(E);
            Height = M * Math.Sin(E);

            // Limit Rotation from 0° to 360°
            Rotation = Rotation % 360;
            Rotation = (Rotation < 0) ? Rotation + 360 : Rotation;
        }

        // Overrides
        public override bool Equals(object obj)
        {
            if (this == (obj as Cylindrical))
                return true;

            return false;
        }
        public static bool operator ==(Cylindrical A, Cylindrical B)
        {
            // Both null
            if (Object.Equals(A, null) && Object.Equals(B, null))
                return true;

            // Either Null
            if (Object.Equals(A, null) || Object.Equals(B, null))
                return false;

            // Compare fields/properties
            if (Math.Abs(A.Radius - B.Radius) > Coordinates.Cartesian_Max_Resolution)
                return false;

            if (Math.Abs(A.Height - B.Height) > Coordinates.Cartesian_Max_Resolution)
                return false;

            if (Math.Abs(A.Rotation - B.Rotation) > Coordinates.Degree_Max_Resolution)
                return false;

            return true;
        }
        public static bool operator !=(Cylindrical A, Cylindrical B)
        {
            return !(A == B);
        }
        public override int GetHashCode()
        {
            // http://primes.utm.edu/lists/small/1000.txt
            int SomeLowValuePrimeA = 503;
            int SomeLowValuePrimeB = 947;

            // http://stackoverflow.com/a/720282/1718702
            // disable overflow, for the unlikely possibility that you
            // are compiling with overflow-checking enabled
            unchecked
            {
                int Hash = SomeLowValuePrimeA;

                Hash = (SomeLowValuePrimeB * Hash) + Radius.GetHashCode();
                Hash = (SomeLowValuePrimeB * Hash) + Height.GetHashCode();
                Hash = (SomeLowValuePrimeB * Hash) + Rotation.GetHashCode();

                return Hash;
            }
        }
        public override string ToString()
        {
            return
                string.Format("Radius = {0}, Height = {1}, Rotation = {2}°",
                Radius.ToString("0.0000"), Height.ToString("0.0000"), Rotation.ToString("0.00"));
        }

        // Implicit Operators
        public static implicit operator Cylindrical(Spherical p_coordinate)
        {
            return
                new Cylindrical(p_coordinate);
        }
        public static implicit operator Cylindrical(Cartesian3D p_coordinate)
        {
            return
                new Cylindrical(p_coordinate);
        }
    }
    public class Cartesian3D
    {
        // Public Fields
        /// <summary>
        /// Length-axis value (Graphically -Left, +Right)
        /// </summary>
        public readonly double Length;

        /// <summary>
        /// Height-axis value (Graphically -Down, +Up)
        /// </summary>
        public readonly double Height;

        /// <summary>
        /// Depth-axis value (Graphically -Toward camera, +Away from camera)
        /// </summary>
        public readonly double Depth;

        // Constructor
        public Cartesian3D(double p_length, double p_height, double p_depth)
        {
            // Init
            Length = p_length;
            Height = p_height;
            Depth = p_depth;
        }
        public Cartesian3D(Cylindrical p_coordinate)
        {
            // Init
            double Radius = p_coordinate.Radius;
            Height = p_coordinate.Height;
            double Rotation = p_coordinate.Rotation * Constants.RADIANS_PER_DEGREE;

            Length = Radius * Math.Cos(Rotation);
            Depth = Radius * Math.Sin(Rotation);
        }

        // Overrides
        public override bool Equals(object obj)
        {
            if (this == (obj as Cartesian3D))
                return true;

            return false;
        }
        public static bool operator ==(Cartesian3D A, Cartesian3D B)
        {
            // Both null
            if (Object.Equals(A, null) && Object.Equals(B, null))
                return true;

            // Either Null
            if (Object.Equals(A, null) || Object.Equals(B, null))
                return false;

            // Compare fields/properties
            if (Math.Abs(A.Length - B.Length) > Coordinates.Cartesian_Max_Resolution)
                return false;

            if (Math.Abs(A.Height - B.Height) > Coordinates.Cartesian_Max_Resolution)
                return false;

            if (Math.Abs(A.Depth - B.Depth) > Coordinates.Cartesian_Max_Resolution)
                return false;

            return true;
        }
        public static bool operator !=(Cartesian3D A, Cartesian3D B)
        {
            return !(A == B);
        }
        public override int GetHashCode()
        {
            // http://primes.utm.edu/lists/small/1000.txt
            int SomeLowValuePrimeA = 5;
            int SomeLowValuePrimeB = 353;

            // http://stackoverflow.com/a/720282/1718702
            // disable overflow, for the unlikely possibility that you
            // are compiling with overflow-checking enabled
            unchecked
            {
                int Hash = SomeLowValuePrimeA;

                Hash = (SomeLowValuePrimeB * Hash) + Length.GetHashCode();
                Hash = (SomeLowValuePrimeB * Hash) + Height.GetHashCode();
                Hash = (SomeLowValuePrimeB * Hash) + Depth.GetHashCode();

                return Hash;
            }
        }
        public override string ToString()
        {
            return
                string.Format("Length = {0}, Height = {1}, Depth = {2}",
                Length.ToString("0.0000"), Height.ToString("0.0000"), Depth.ToString("0.0000"));
        }

        // Implicit Operators
        public static implicit operator Cartesian3D(Cylindrical p_coordinate)
        {
            return
                new Cartesian3D(p_coordinate);
        }
        public static implicit operator Cartesian3D(Spherical p_coordinate)
        {
            Cylindrical Point = p_coordinate;

            return
                new Cartesian3D(Point);
        }
    }

    public class Spherical
    {
        // Public Fields
        /// <summary>
        /// Magnitude (rho) of vector.
        /// </summary>
        public readonly double Magnitude;

        /// <summary>
        /// Angle (phi) of elevation measured relative to the horizontal plane. Elevation of 90° is colinear with the positive polar-axis; -90° is colinear with the negative polar-axis.
        /// </summary>
        public readonly double Elevation;

        /// <summary>
        /// Angle (theta) of rotation about the polar axis. Rotation of 0° is colinear with positive length-axis; 90° is colinear with positive depth-axis.
        /// </summary>
        public readonly double Rotation;

        // Constructor
        public Spherical(double p_magnitude, double p_elevation, double p_rotation)
        {
            // Init
            Magnitude = p_magnitude;
            Elevation = p_elevation % 180;
            Rotation = p_rotation;

            // Correct Inverted Magnitude
            if (Magnitude < 0)
            {
                Magnitude = -Magnitude;
                Elevation = -Elevation;
                Rotation += 180;
            }

            // Limit Elevation from 90° to -90°
            if (Elevation > 90.0)
            {
                Elevation = 180 - Elevation;
                Rotation += 180;
            }
            else if (Elevation < -90.0)
            {
                Elevation = -180 - Elevation;
                Rotation += 180;
            }

            // Limit Rotation from 0° to 360°
            Rotation = Rotation % 360;
            Rotation = (Rotation < 0) ? Rotation + 360 : Rotation;
        }
        public Spherical(Cylindrical p_coordinate)
        {
            // Init
            double R = p_coordinate.Radius;
            double H = p_coordinate.Height;
            Rotation = p_coordinate.Rotation;

            Magnitude = Math.Sqrt(R * R + H * H);

            // Vector magnitude projected in the horizontal plane will always be positive
            // Therefore angle will always be between 0° and 180°
            Elevation = Math.Atan2(H, R) * Constants.DEGREES_PER_RADIAN;

            // Limit Rotation from 0° to 360°
            Rotation = Rotation % 360;
            Rotation = (Rotation < 0) ? Rotation + 360 : Rotation;
        }

        // Overrides
        public override bool Equals(object obj)
        {
            if (this == (obj as Spherical))
                return true;

            return false;
        }
        public static bool operator ==(Spherical A, Spherical B)
        {
            // Both null
            if (Object.Equals(A, null) && Object.Equals(B, null))
                return true;

            // Either Null
            if (Object.Equals(A, null) || Object.Equals(B, null))
                return false;

            // Compare fields/properties
            if (Math.Abs(A.Magnitude - B.Magnitude) > Coordinates.Cartesian_Max_Resolution)
                return false;

            if (Math.Abs(A.Elevation - B.Elevation) > Coordinates.Degree_Max_Resolution)
                return false;

            if (Math.Abs(A.Rotation - B.Rotation) > Coordinates.Degree_Max_Resolution)
                return false;

            return true;
        }
        public static bool operator !=(Spherical A, Spherical B)
        {
            return !(A == B);
        }
        public override int GetHashCode()
        {
            // http://primes.utm.edu/lists/small/1000.txt
            int SomeLowValuePrimeA = 503;
            int SomeLowValuePrimeB = 151;

            // http://stackoverflow.com/a/720282/1718702
            // disable overflow, for the unlikely possibility that you
            // are compiling with overflow-checking enabled
            unchecked
            {
                int Hash = SomeLowValuePrimeA;

                Hash = (SomeLowValuePrimeB * Hash) + Magnitude.GetHashCode();
                Hash = (SomeLowValuePrimeB * Hash) + Elevation.GetHashCode();
                Hash = (SomeLowValuePrimeB * Hash) + Rotation.GetHashCode();

                return Hash;
            }
        }
        public override string ToString()
        {
            return
                string.Format("Magnitude = {0}, Elevation = {1}°, Rotation = {2}°",
                Magnitude.ToString("0.0000"), Elevation.ToString("0.00"), Rotation.ToString("0.00"));
        }

        // Implicit Operators
        public static implicit operator Spherical(Cylindrical p_coordinate)
        {
            return
                new Spherical(p_coordinate);
        }
        public static implicit operator Spherical(Cartesian3D p_coordinate)
        {
            Cylindrical Point = p_coordinate;

            return
                new Spherical(Point);
        }
    }
}

```

# Answer
I'm not entirely sure I understand the question but, given a 3D point cloud with a 2D "shape" (like a disc) the problem is simply one of dimension reduction.

The algorithm you're looking for is called "Principal Component Analysis". How it works is not trivial, so I'll leave that for you to research if you're not already familiar with PCA. What it will give you is a series of eigenvectors and eigenvalues that will tell you how significant a dimension is. Here's a quick sketch of how this would look in 2D with inherently 1D data (but easily expanded to ND):

This information is usually used to simplify multi-dimensional data by reducing dimensions and removing ones that aren't that significant (e.g. in the above example the red; the data can be treated as linear along the blue without the loss of a lot of information). In your case however, you can find the smallest eigenvalue, and use that as your normal for measuring disk thickness in 3D (or alternatively, cross the two eigenvectors with the largest corresponding eigenvalues and the resulting vector is the normal to the disc pointing up relative to it).

Once you have that vector, it's trivial to find out which point is furthest along on the axis that vector creates. And there you have your thickness!
> 4 votes

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