# Question
Title: How do I call OpenGL methods that require pointers in C#?
I have found the following C++ code in this tutorial to draw a triangle with OpenGL 4:

```
float points[] = {
   0.0f,  0.5f,  0.0f,
   0.5f, -0.5f,  0.0f,
  -0.5f, -0.5f,  0.0f
};
GLuint vbo = 0;
glGenBuffers (1, &vbo);
glBindBuffer (GL_ARRAY_BUFFER, vbo);
glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (float), points, GL_STATIC_DRAW);

```

I use C# and OpenTK, so I tried to translate the code:

```
        float[] points =
        {
           0.0f,  0.5f,  0.0f,
           0.5f, -0.5f,  0.0f,
          -0.5f, -0.5f,  0.0f
        };
        uint[] vbo = {0};
        GL.GenBuffers(1, vbo);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[0]);
        GL.BufferData(BufferTarget.ArrayBuffer, 9 * sizeof(float), ppoints, BufferUsageHint.StaticDraw);

```

The problem is that `GL.GenBuffers()` and `GL.BufferData()` require pointers (Visual Studio shows `*int` or `out int` and `ref float*`, `IntPtr`).

I've tried to fix this, but it didn't work:

```
        float[] points =
        {
           0.0f,  0.5f,  0.0f,
           0.5f, -0.5f,  0.0f,
          -0.5f, -0.5f,  0.0f
        };
        uint[] vbo = {0};
        GL.GenBuffers(1, vbo);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[0]);

        unsafe
        {
            fixed (float* ppoints = points)
            {
                GL.BufferData(BufferTarget.ArrayBuffer, 9 * sizeof(float), ppoints, BufferUsageHint.StaticDraw);
            }
        }

```

So my question is how to use these methods in a good C# style?

# Answer
> 5 votes
The following code should work:

```
    var points = new float[]
    {
       0.0f,  0.5f,  0.0f,
       0.5f, -0.5f,  0.0f,
      -0.5f, -0.5f,  0.0f
    };
    int vbo = GL.GenBuffer();
    GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
    GL.BufferData(BufferTarget.ArrayBuffer, points.Length * sizeof(float), points, BufferUsageHint.StaticDraw);

```

OpenTK provides three overloads for each method with *typed* pointers. For example:

```
const GLfloat* -> ref float, float[], float* (input)
      GLfloat* -> out float, float[], float* (output)

```
1. Use `ref/out float` if you wish to pass/retrieve a single item.
2. Use `float[]` if you wish to pass/retrieve an array of items.
3. Use `float*` when writing unsafe code (e.g. a pointer to unmanaged memory or the stack).

*Untyped* pointers get the same overloads using generics:

```
const GLvoid* -> ref T, T[], IntPtr (input)
      GLvoid* -> out T, T[], IntPtr (output)

```

Starting with OpenTK 1.1, `Gen*` and `Delete*` methods get one additional overload, to simplify usage from F# (and similar functional languages). This is often the optimal approach:

```
int buffer = GL.GenBuffer();

```

Which is equivalent to the more verbose:

```
int buffer;
GL.GenBuffers(1, out buffer);

```

Note that unsigned types get both unsigned and signed overloads. For example, `GLuint` gets both `uint` and `int` overloads. The reason is that unsigned integers are not \[CLS-Compliant\]\[1\] and cannot be used by all .Net languages (e.g. VB.Net). This is something to keep in mind if you are writing a public API to be consumed outside of C#.

\[1\] http://msdn.microsoft.com/en-us/library/12a7a7h3%28v=vs.110%29.aspx

---
Tags: opengl, c#, c++, opentk
---


title: How can I display Unity games in Flex?

text:
# Question
Title: How can I display Unity games in Flex?
We have tried the following methods to upload sample Unity3D build to a desktop application in Flex: HTML Loader, NavigateToURL, iFrame and resolvePath.

But we only see the text content, not the 3D content. What is the solution for that? How can I host a Unity game inside Flex?

# Answer
Sadly, as things are of now, **you can't run Unity3D content in flex**.

There is simply not enough Flex users for Unity to support it with their plugin.

However, there are some hope coming in Unity 5, since it will be possible (at least promised) to build games that run straight with WebGL, discarding the need for a Unity Web player plugin (at least for most projects)

Until then, I would say that the odds of Unity making a plugin for Flex in this "mid transition period" is very unlikely.
> 1 votes

---
Tags: unity, browser-based-games, flex
---


# Question
Title: How to export FBX models to use in SharpDX?
I am trying to export a model from 3ds Max 2014 as a fbx file and use it in my SharpDX driven project. In the SharpDX example solution, there is a project named `ModelRendering.Desktop`. I just modified it to load my exported testmodel.

This is the result when running the program:

As you see, I modeled a cube in 3ds Max. But the sample application shows me something different. When I try to export some more complex models, their renderings are totally broken.

I use the default export settings ("Autodesc Media & Entertainment"). Do I need to hit a special export option or do I need to use some external converter? What is the common way to use fbx models from 3ds Max in SharpDX?

# Answer
> 1 votes
Make sure that the culling order is correct. This depends on whether you're using LR or RH. If you're not sure, then just try both `GraphicsDevice.RasterizerStates.CullFront` and `GraphicsDevice.RasterizerStates.CullBack` to see which one looks correct.

Also, you might want to try rendering with your camera's world matrix through `Matrix.Transpose`.

---
Tags: models, 3dsmax, sharpdx, fbx, assimp
---


# Question
Title: Depth of overlap between circle and rectangle
I have a circle and a rectangle one of the two objects is moving the other is static. How can I prevent them from overlapping each other? For now there is only one thing that I don't know how to calculate - the depth between the two objects. Could you tell me how to do that? I am using monogame

```
public void CircleVsRectangle(CircleBody circle, RectangleBody rect)
{
  float circleDistanceX = Math.Abs(circle.CenterX - rect.CenterX);
  float circleDistanceY = Math.Abs(circle.CenterY - rect.CenterY);

  Vector2 circleDistance = new Vector2(circleDistanceX, circleDistanceY);

  if (circleDistance.X > (rect.Width / 2 + circle.Radius)) { return false; }
  if (circleDistance.Y > (rect.Height / 2 + circle.Radius)) { return false; }

  if (circleDistance.X <= (rect.Width / 2)) { return true; }
  if (circleDistance.Y <= (rect.Height / 2)) { return true; }

  float cornerDistance_sq = ((circleDistance.X - rect.Width / 2) * (circleDistance.X - rect.Width / 2)) + ((circleDistance.Y - rect.Height / 2) * (circleDistance.Y - rect.Height / 2));

  if( (cornerDistance_sq <= (circle.Radius * circle.Radius)))
  {
  float dept = CalcDept() // ??????
  if(circle.IsMoving) circle.position += dept;
  else if(rectangle.IsMoving) rect.position += dept;
  }
}

```

# Answer
To get the distance and the separation/collision normal you reduce the "circle to aabb" to a "point to plane" problem which can be easily solved.

In detail:

* Get closest point from circle center to aabb
* Get distance from closest point to circle center
* Create a normalized version of this distance vector (Separation normal)
* Project the distance onto the separation normal (Voila, you have your depth scalar)

There is one downside for this approach, if the circle center is inside the aabb you need to find the axis for the smallest penetration instead and use a point to plane approach again.
> 1 votes

# Answer
You should take a look at this classic tutorial on the Separating Axis Theorem.

There is too much maths involved to reasonably reproduce it here.

---

Note that, in your code, you've got `CalcDept` returning a `float` (1D value), and you're attempting to add it to `position` (a 2D value). This is not correct.

If you look at Section 3 of the tutorial, you'll note that there are six possible axes along which a rectangle and a circle could interpenetrate. So your "depth" is always going to be associated with an axis (a direction) - so it will be a 2D value (a `Vector2`).

---

In most cases, however, you should use a pre-built solution such as Velcro Physics Engine.
> -1 votes

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


# Question
Title: How can I do a weighted cascade down a path in a 3D environment?
I am trying to perform a weighted cascade down a path in a 3D environment. Now, what I am trying to do is have one object(a cube) in the environment scan from its coords 1 in every direction for another cube, and then if it finds another cube, it will scan around that cube for another cube etc all the way to the end of the path, or it has reached its limit of 40 cubes, and I would like it to have a weight for each step down the path it takes so it will stop if it has travelled more than 40 cubes down the path.

Now, I have no idea on where to go from scanning directly around the first cube. How do I make it move onto the next cube, then the next cube, then the next etc without writing a really long method that considers each cube along the path?

Before pathfinding algorithms such as A-Star or BFS/DFS come into this, I have already tried that and found it way too complicated, it was unnecessary complicated just for this one part of my program.

Thanks.

Edit: I forgot to mention that these cubes do not move, they stay wherever the player puts them.

# Answer
> 1 votes
you say it's so complicated to implement a path-finding algorithm, but it isn't...

and what's even better, once you have implemented one you can use that algorithm whenever needed again...

i can provide you with an simple one (A\* it is - and **it is easy**) and it's so open you can use it on hexfields, squared fields or even on cubes...

```
private ArrayList<Node> oList = new ArrayList<Node>(); //open list
private ArrayList<Node> cList = new ArrayList<Node>(); //closed list
public ArrayList<Point> getShortestPath(
    Point startPoint, Monster walker, StaticMap map,
    Point targetPoint, int maxPathLength) {

    int xs = startPoint.x;
    int ys = startPoint.y;
    //int zs = startPoint.z;

    int xe = targetPoint.x;
    int ye = targetPoint.y;
    //int ze = targetPoint.z;

    oList.clear();
    cList.clear();

    Node start = new Node(xs,ys); //Node start = new Node(xs,ys, zs); //
    Node end = new Node(xe, ye); //Node end = new Node(xs,ys, zs); //
    oList.add(start);

    boolean noWayFound = false;
    while(true){
        Node current = getLeastF(oList);

        if (current == null){
            noWayFound = true;
            break;
        }

        if (current.isSamePos(end) ){
            noWayFound = false;
            end.from = current.from;
            break;
        }

        //this is just an abortion criteria if you can't
        //guarantee a shortest path
        if (current.g > maxPathLength*10){
            noWayFound = true;
            break;
        }

        oList.remove(current);
        cList.add(current);
        expandNode(current, map, walker, end);

    }

    ArrayList<Point> path = new ArrayList<Point>();
    if (!noWayFound){
        Node n = end;
        while(n != null){
            path.add(new Point(n.x, n.y) );
            //path.add(new Point(n.x, n.y, n.z) );
            n = n.from;
        }
    }

    return path;
}

```

what's different on any map is `expandNode` ... this implementation depends on your map... it looks at the current node and looks into all neighbours (4 on a real squared map, 8 on a semi squared map, 6 on a hex map and **also 6 on a 3d squared map** )...

```
private void expandNode(Node current, StaticMap map, Monster walker, Node end) {

    Node nNode = new Node(current.x, current.y-1);
    Node eNode = new Node(current.x+1, current.y);
    Node sNode = new Node(current.x, current.y+1);
    Node wNode = new Node(current.x-1, current.y);
    //Node upNode = new Node(current.x, current.y, current.z-1);
    //Node nownNode = new Node(current.x, current.y, current.z+1);

    if (checkIsPassable(nNode, walker, staticMap) ){ //true if you can go north
        addIfRequired(nNode, current, end, 10); //10 is the walking cost
    }
    if (checkIsPassable(eNode, walker, staticMap) ){
        addIfRequired(eNode, current, end, 10);
    }
    if (checkIsPassable(sNode, walker, staticMap) ){
        addIfRequired(sNode, current, end, 10);
    }
    if (checkIsPassable(wNode, walker, staticMap) ){
        addIfRequired(wNode, current, end, 10);
    }

    //if (checkIsPassable(upNode, walker, staticMap) ){
    //  addIfRequired(upNode, current, end, 10);
    //}
    //if (checkIsPassable(downNode, walker, staticMap) ){
    //  addIfRequired(downNode, current, end, 10);
    //}
}

```

the last point is to add a field (a cube) if required ^^

```
private void addIfRequired(Node nNode, Node current, Node end, int distance) {
    if ( !isPosInList(nNode, cList) ){
        if ( isPosInList(nNode, oList)  ){
            Node can = getPos(nNode, oList);
            if (can.g < nNode.g){
                can.from = current;
                can.g = current.g + distance;
                can.f = can.h + can.g;
            }
        }else{
            nNode.from = current;
            nNode.h = 10*  ( Math.abs(end.x-nNode.x)+Math.abs(end.y-nNode.y)   );
            //nNode.h = 10*  ( Math.abs(end.x-nNode.x)+Math.abs(end.y-nNode.y) +Math.abs(end.z-nNode.z)   );
            nNode.g = current.g + distance;
            nNode.f = nNode.h + nNode.g;
            oList.add(nNode);
        }
    }
}

```

if you're wondering what a node is..

```
public class Node {
    int f;
    int g;
    int h;
    int x;
    int y;
    //int z;
    Node from;

    Node(int x, int y){
        this.x=x; this.y=y;
    }

    //Node(int x, int y, int z){
    //  this.x=x; this.y=y;this.z=z;
    //}

    boolean isSamePos(Node n){
        if (n != null && n.x==x && n.y==y) return true;
        //if (n != null && n.x==x && n.y==y && n.z==z) return true;
        return false;
    }

    @Override
    public String toString() {
        return ""+x+"/"+y+" g="+g+" h="+h+" f="+f;
        //return ""+x+"/"+y+"/"+z+" g="+g+" h="+h+" f="+f;
    }
}

```

this would be the a\*algortihm for path finding.... i've added in comments `//...` how you have to adjust that code for 3D path finding...

---
Tags: java, 3d, algorithm, path-finding
---


# Question
Title: libgdx glClearColor not setting right color?
i just new to libgdx and trying to understand the example code, the following code sets the bg color

```
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        Gdx.gl.glClearColor(60,181,00,0f);

```

my expected color is green, R:60 Green:181 B:0, but the about code show me yellow color in my android app, anything i'm doing wrong?

http://rapid-tools.net/online-color-picker/

# Answer
`glClearColor` expects color values to be in `0 .. 1` range, everything outside of this range gets clamped to it. In your case numbers are getting clamped to `(1, 1, 0, 0)` which is indeed yellow.

Try setting `glClearColor(60/255.0, 181/255.0, 0.0, 0.0);` instead.
> 7 votes

---
Tags: opengl, libgdx
---


# Question
Title: How do I procedurally animate a cell eating another cell?
The entities in my game are soft-body, amorphous cells. I'd like to create an animation where enemies are engulfed by the player's cell. That is, I want to generate a "cell eating another cell"-effect. See this video for the type of motion I want: https://www.youtube.com/watch?v=iO\_vOFFf1uQ

I'm considering using fluid dynamics to achieve this, but I'm lost as to where to start. I'm working in Unity2D, and Fluvio doesn't seem to provide what I need. Does anyone have advice on the best way for me to proceed?

# Answer
> 7 votes
What may be a good way of simulating entities which may vary a lot is to use a force field that you draw with a marching square algorithm.

So the eating entity would be a set of fields that you have moving together using a flocking strategy or similar, to get a 'cell' effect. You have to use a number of force field large enough to allow for opening a 'mouth' within it. Maybe 6 - 10 fields would be ok.

The marching square can be made quite fast with careful implementation. Notice that you only need it if you need the edges of your entity, otherwise you might just draw carefully using gradients and it might look good. If you write a webgGL shader, you could most likely make all this real-time.

I just rushed a small example, re-using an old project.

jsfiddle.net/gamealchemist/7tjfhhre/

It's using the canvas's context2d, radial gradients and blend modes.
If you think about it, you can consider that the lightness of a point is the strength of the field in that point, and you can consider a radial gradient lowering to zero as a force field, ==\>\> drawing gradients is exactly like computing the field in each (x,y) point of the screen.
Again, you'll still need marching cubes if you want to draw the edges (more 'cartoonish') .

2 screenshots (try it live it's nicer ! )

ScreenShot when mouth closed :

mouyh opened :

# Answer
> 5 votes
Fluid dynamics is one of those super hard things to set up, that once you've got it working allows for a whole range of interesting effects. It's probably overkill for most games, unless you actually need things to move like a fluid (as in, flow from one point to another). For soft-body masses, I would considering instead using nets of springs to simulate your bodies; much more straightforward to implement, and far easier to handle from a gameplay point of view.

As a possible initial implementation: imagine that your body would have a centroid, that you could apply forces to and move around. Around that centroid, you'd attach additional nodes, linked to the centroid with a spring, and linked to each other to form a network that holds its shape. For example a hexagon of 6 nodes around the outside, each linked to their neighbour and also the centroid via springs. As you apply forces to the centroid, the springs act to pass on that force to the outer parts of the body; the front compresses towards the centroid, the rear elongates as it is pulled with the centroid. That's not the only way to do it, you can have the movement forces applied equally to all the nodes, it all depends on how you imagine these bodies to work internally. Apply forces to all nodes equally, and the body won't deform unless it encounters something else.

And it's in encountering "something else" that things get interesting, and cause your body to deform nicely. Bear in mind you're simulating something soft and squishy, not a bunch of hard spheres connected together. So maybe instead of using rigid body collision, give each of the nodes a repulsion from the other objects in your simulation. Then, as you move your body towards an object smaller than itself, the gap between nodes will widen to allow the object to slip between them. After the object has passed through, the springs that hold the body together will cause it to reform into its original shape. Objects larger than the body won't be able to fit through the gaps, so your body should collide with the larger object and flatten against it. It's possible you want to implement rigid body physics as well, to prevent a squishy object penetrating through something that should be solid, but it should be a backup to the repulsion-based forces that are simulating the squishy exterior of your body.

In terms of rendering, you can get a nice blobby effect with a pixel shader or render-to-texture approach, basically rendering a circle around each node such that the overlaps are invisible, but around the edges there are nice soft circular edges.

So look up spring networks and Verlet integrated spring simulations, and you should be able to get the foundations of a system that will let you do 'blobby' physical mechanics without doing full on free-moving fluid simulations.

# Answer
> 1 votes
I'd look into spring systems first before diving straight into fluid dynamics. They can help building a somewhat stable cell structure, and you can visualize this with normal effort (e.g. using alpha-blended particles, iso-lines, image-based effects on top of convex hulls etc..)

Fluid dynamics and final-element simulations are of course much more realistic and when combined with marching cubes or squares or ray-marching, they can give stunning visuals. It also comes with sufficient complexity that will keep you entertained for quite a bit.

The trick with fluids is that you need cohesion factors for different types of fluids or objects, so that you can update the characteristics of the 'eaten' bits when enclosed by another fluid. To test whether a point is complete enclosed in 2D, you can build convex hulls for the enclosing fluid and then test each object if it is in the hull or not. Check Melkman's algorithm for a fast incremental implementation. The same works in 3D, though you probably will want to switch to voxels.

---
Tags: unity, animation, physics, fluid-dynamics
---


# Question
Title: Ambient occlusion of cubes, a specific case
After much fiddling around and thinking I've got my AO working on my game engine as intended; except one specific case.

When a block is nestled between others on two sides, but the corner block is missing, that corner doesn't get occluded. This isn't too shocking, because there's no logic to do otherwise. However, I can't think of a way to neatly solve that case. If I make it detect a block on each pair of sides, then check for the corner piece, we will end up with lots of broken AO in various scenarios, and that will be a lot of checks to boot.

Here's the table I came up with today which finally solved the missing bits of my AO algorithms:

Click for larger view

The logic in my code (C# MonoGame) essentially enforces this table.

If nobody comes up with anything better, I'll put a series of booleans in the checks for each side, then run through each combination and adjust as though a pair of side block were the corresponding corner block.

# Answer
> 0 votes
Fixing the table helped a lot, but the main issue I had was I was assigning the wrong AO values to the NegZ and PosZ face vertices. This meant that when I tried to fix things, other things broke as I tried to compensate for the unknown variable of the Z axis being rotated.

The table in the original post is updated, but basically the side cases shouldn't affect their own axis, and should affect the others. There were also a few mistakes of which values in a few spots. Everything's good now!

This table would have been invaluable to me if I'd found it online when starting this, so hopefully someone else finds it useful. If you do, let me know - I'd like to hear that all the work I put into that table is appreciated by others. :3

---
Tags: xna, c#, lighting, voxels, occlusion
---


# Question
Title: How to preserve topology for penetration correction?
I have a sorted list of blocks - some may overlap some may not. Each block has an ideal starting position and may be constrained to one axis. There are no velocity or acceleration or other forces involved - just the position. Some blocks are totally fixed and can never be moved (boundary blocks).

How do I solve the penetrations in a way that the blocks don't overlap anymore, but stay in the initial order?

I can easily solve the penetrations with normal position correction methods, like Baumgarte's stabilization in combination with separation axis theorem. The problem though, a separation normal might be found which pushes the block in a way that the order is changed, which is not what I want, because the application I am writing is a numerical simulation with some visualizations.

I created a simple javascript sample to show what I mean: http://jsfiddle.net/358hra2j/1/

# Answer
> 1 votes
I updated the JSFiddle sample with the solution: Here's the updated version.

It was just two lines of code:

```
var sign = shapeA.id - shapeB.id > 0 ? 1 : -1;
n.multScalar(sign);

```

# Answer
> 0 votes
Found a solution, using the sign from the shapes order as a multiplication factor for the normal solved the problem.

Just two lines of code:

```
    // Fix direction based on order of creation
    var sign = shapeA.id - shapeB.id > 0 ? 1 : -1;
    n.multScalar(sign);

```

---
Tags: collision-detection, collision-resolution, topography
---


# Question
Title: Minkowski Portal Refinement collision detection algorithm
*Preface*: While I was learning the basics of collision detection, I read in various places that the SAT and GJK algorithms don't natively return contact points. So I decided to research the MPR algorithm. I've found very little information about it online.

My questions are the following:

1. What are the steps it takes?
2. Does MPR detect collisions continuously? If not, is it feasible to upgrade it?
3. Does it return contact points, or a simple true/false on collision? How does it calculate them?

(I'm targeting 2D, but it would be nice to know the differences in 3D.)

# Answer
> 1 votes
If you decided to research the MPR algorithm, I'd advice you to deal with GJK first. However I'm not sure, that the MPR is what you are looking for. The main idea of these two algorithms is very close, more over MPR does not provide information about contact point either. It should be mentioned that in contrast with GJK, MPR does not give the shortest distance between separated shapes

I'd never worked with MPR, but it is said, that in comparison with GJK, MPR is simpler and more numerically robust. Once you understand the GJK, this article will be enough to understand MPR.

I'm not sure, but I think that it is possible to make MPR incremental. In case of GJK, for example, you can cache the simplex from the last iteration and use it in next step, thus it would take less iterations. Perhaps, it may be possible to cache a portal.

To get the set of contact point, you have to use other algorithms. SAT can be extended to get the contact set.

You should take into account the fact, that the number of real intersections would be much less than the number of intersection tests. Thus it is likely that the pair of GJK algorithm and something simple to process intersecting polygons would be rather effective. If you have a pair of intersecting polygons, i.e. you can just do an edge to edge clip of each polygon against the other.

---
Tags: collision-detection
---


# Question
Title: Can I mix the use of VAO and direct usage of glVertexAttribPointer?
Let's say I am not using VAOs. I have an array of vertex positions in memory that I want to send to the shader. I do the following (assume I have enabled the corresponding vertex attrib arrays):

```
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertexDataAsFloats);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, textureData);
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, someOtherData);
glDrawArrays(...);

```

This works well and I see the mesh with proper textures. `someOtherData` is sent to the shader correctly as well. Now I decide to put the `vertexDataAsFloats` and `textureData` in `VBOs`:

```
BindVAO(1); // binds the VAO with a handle generated from glGenVertexArrays()
glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, textureData);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
UnBindVAO();

```

Later, before drawing:

```
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, someOtherData);
BindVAO(1);
glDrawArrays(...);
UnBindVAO();

```

Can I mix the calls to `glVertexAttribPointer` and `VAO` before the draw call, where `someOtherData` is **not** in a `VBO`? Currently, this approach is not working as I am not receiving valid data for `someOtherData` in the shader.

I realize that `someOtherData` should go in a `VBO` as well and bound with the `VAO`. There is some legacy code that I have to work with which does not use `VBOs`. In any case, I would like to know if the above is legal in OpenGL.

# Answer
It would appear that mixing `VAOs` with `glVertexAttribArray()` calls where the latter does not use a `VBO` does not work and emits no `OpenGL` errors. This means that if you decide to use `VAOs` then all `glVertexAttrbArray()` calls must be made to a corresponding `VBO`.
> 0 votes

# Answer
The gl\*Pointer calls will store the currently bound buffer object and use it as the data source no matter what buffer object is bound during glDrawArrays and other draw calls.

So as long as you unbind the buffer object before you call glVertexAttribPointer it will interpret its source argument as an absolute address instead of an offset into a buffer object.

EDIT: apparently it used to be possible because the extension was based on the APPLE VAO extension, but isn't anymore. Refer to the revision history in https://www.opengl.org/registry/specs/ARB/vertex\_array\_object.txt

I guess nowadays you should really just use streaming with buffer objects in a double buffer setup.
> 0 votes

# Answer
The specification for GL\_ARB\_vertex\_array\_object is clear on this:

> ...client memory cannot be accessed through a non-zero vertex array object...

However, there is a workaround for you here. You can use use VAOs for everything else, but just bind VAO 0 and then issue the full set of glVertexAttribPointer calls (i.e referencing both buffer objects and client memory) for the legacy part of your code.
> 0 votes

---
Tags: opengl, vbo, vertex-buffer, vao
---


title: Protecting tilesets

text:
# Question
Title: Protecting tilesets
I have a game and my tilesheets are placed in the images/ folder.

If a user edits the tilesets, they can make them transparent (I use white as my transparent color on them) and in game basically remove all obstacles and stroll to the level exit.

What's the common or most sensible way of sorting out so the user can't tamper with them?

EDIT: I've already encrypted the file, if the user replaces the file with anything else with the same name it still attempts to load it and place transparent tiles, allowing the user to exit unhindered.

# Answer
> 3 votes
A determined modder can and will always modify any part of your game which runs on the users system. You can put obstacles in their way to make their life harder, but you can't stop them. Creating a hash of your assets can be countered by finding that hash in your executable and changing it too. When you encrypt your assets, people will find the decryption key and algorithm in your executable. When you obfuscate your executable, they will find a deobfuscator. You can buy an expensive license for a commercial anti-cheat tool and add it to your game, but these tools can't protect themselves from getting hacked. They are just software, and any software can be hacked when the hacker has access to them. For every ACT there is a hack which counters it.

Conclusion: It's futile.

But when your game is **offline**, then why bother? The cheaters are only cheating themselves. When they enjoy your game more when it provides no challenge at all, good for them. Let them have their "fun". They aren't hurting anyone except themselves.

However, when your game is **online**, it's something different. Cheaters can destroy the fun for any honest players who try to compete with them. The only good way to prevent cheating in a multiplayer game is by having an authoritative server which receives raw input from the clients, calculates all game mechanics itself and sends only those results to each client which it is supposed to know. That way the user can modify their client as much as they want. It won't help them when the server won't accept any illegal moves and won't give them any useful information the player isn't supposed to know.

There is, however, one family of cheats an authoritative server can't prevent: Automation. Be it aimbots in a FPS or a farmbot in an MMO - the only way to detect them is with heuristics or with observant moderators.

# Answer
> 2 votes
Once you've finalized your texture, create a hash of the file. Store that hash somewhere else in assets. When the level is loaded, create a new hash when you load the texture and compare it to the hash created when you finalized. If the hashes are different, the file has been altered.

Further, you might really consider what your motivation is for preventing modification of the game. Some people like to tinker with their games. This is a common behavior and often rewarding, and if the effect is negative, it only ruins the experience for the tinkerer.

If your game is multiplayer and competitive, you'll probably want to make some efforts to prevent modification. However, this quickly becomes a diminishing returns type situation. The more advanced your anti-hack, the smaller the target audience is (because fewer people have the skills to perform advanced hacking). This means that the most challenging work you can put into preventing hacking is only going to stop the smallest number of users.

You may want to focus your efforts on simple, broad changes that prevent casual hacking. It's more important that you finish your game and it's fun to play, then preventing a small fraction of its players from cheating.

---
Tags: tiles, security
---


# Question
Title: Circle-line segment collision resolution
I'm trying to make a side-scrolling game using this method and I'm having some trouble getting it to behave right. The collision shapes consist of multiple connected line segments and I'm checking them one at a time in order from first to last, so in one direction the collisions are resolved in the wrong order and the circle can't move over the connection point.

Is there a way of fixing this that isn't a hack, or should I try preventing the collision from happening in the first place instead?

ETA: The circle is moved straight up if the overlapping line segment is below and not too steep (approx. 50 degrees maximum) to enable it to move on slopes without resistance. In all other cases, the minimum displacement vector is used to resolve the collision.

# Answer
> 0 votes
I think the only true non-hack way to do this is to directly solve for collision between the object (rectangle, here) and the area/volume swept by the moving object (circle).

In many applications that's overkill, in some it's paramount - your decision. I'll assume you're OK with hacks for the rest.

What you've described here (esp. your choice to bump "straight up") suggests a platformer (beyond just being a side-scroller), in which case a very simple first-pass hack might be to check the "top" segment first. That's often the most important surface, so you might get reasonably good behavior with this alone.

Another naive hack, if your game has the spare cycles, would be to approximate the direct solution by interpolating across the desired motion. Then just use the final non-colliding position as the result. Something like this:

Then if you want sliding along an edge, you could record the remaining distance parallel to that surface and use it to kick off another motion with checks. Like so:

There are of course a lot of ways to handle collision, most of them far more clever than what I describe here, but perhaps this will give you some ideas about how to progress.

---
Tags: collision-resolution, side-scroller
---


# Question
Title: When using deferred rendering technique, what space should my normals be? Why?
I'm implementing a deferred shading technique and the following question arose:

**When storing the normals, should I transform to view space, or may I keep them in world space? Why?**

Will any of the alternatives be better than the other for calculating lighting?

# Answer
> 0 votes
I found the answer to my question by experiencing. Take a look here to learn how to reconstruct position from depth buffer. As you can see, converting do view-space is a little cheaper. So that's what I chose. Position and Normals on view space. The only drawback is having to project your lights position from world to view space, but that's done only once per frame on GPU, is kinda MUCH better than once per pixel.

---
Tags: rendering, deferred-rendering, normals
---


# Question
Title: Why does my A* implementation overflow the stack?
I'm fairly new to game dev and working on my first ever attempt at 2D pathfinding. I'm using the A\* algorithm as detailed here.

For the most part, it seems to be working correctly and as intended. However upon attempting to wrap my path around a building in the map, a stack overflow is caused in `ClosedList` (the list storing coordinates of the path). It appears that at some point in the path, the algorithm is switching back and forth between two tiles, but I cannot work out why.

The code probably isn't the best way to do things but this is my first attempt. Apologies if it offends anyone. :P

```
void CheckSquare(Vector2 Start, Vector2 End)
{
    //Check for Invalid Start/End Points
    if (Start == End ||
        grid.PTileArray[(int)Start.x, (int)Start.y].CurrentType.Passable == 0 ||
        grid.PTileArray[(int)End.x, (int)End.y].CurrentType.Passable == 0)
    {
        return;
    }

    //Check which adjacent tiles are passable
    if (grid.PTileArray[(int)Start.x - 1, (int)Start.y].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x - 1, Start.y)); //LEFT
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x - 1, (int)Start.y + 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x - 1, Start.y + 1)); //TOP LEFT
        gValues.Add(14);
    }
    if (grid.PTileArray[(int)Start.x, (int)Start.y + 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x, Start.y + 1)); //TOP
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x + 1, (int)Start.y + 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x + 1, Start.y + 1)); //TOP RIGHT
        gValues.Add(14);
    }
    if (grid.PTileArray[(int)Start.x + 1, (int)Start.y].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x + 1, Start.y)); //RIGHT
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x + 1, (int)Start.y - 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x + 1, Start.y - 1)); //BOTTOM RIGHT
        gValues.Add(14);
    }
    if (grid.PTileArray[(int)Start.x, (int)Start.y - 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x, Start.y - 1)); //BOTTOM
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x - 1, (int)Start.y - 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x - 1, Start.y - 1)); //BOTTOM LEFT
        gValues.Add(14);
    }

    //Remove the parent from the Possible choices
    for (int n = 0; n < OpenList.Count; n++)
    {
        if (OpenList[n] == ClosedList[ClosedList.Count - 1])
        {
            OpenList.RemoveAt(n);
        }
    }

        //Calculate H Values
        for (int n = 0; n < OpenList.Count; n++)
        {
            float x = Mathf.Abs(End.x - OpenList[n].x);
            float y = Mathf.Abs(End.y - OpenList[n].y);
            float final = 10 * (x + y);
            hValues.Add((int)final);
        }

    //Calculate F Values
    int lowest = 10000;
    int reference = 0;
    for (int n = 0; n < OpenList.Count; n++)
    {
        int g = gValues[n];
        int h = hValues[n];
        int final = g + h;
        fValues.Add(final);
        if (fValues[n] < lowest)
        {
            lowest = fValues[n];
            reference = n;
        }
    }

    //Add the square with the lowest F Value to the closed list as part of the path
    ClosedList.Add(OpenList[reference]);

    //Clear Lists
    OpenList.Clear();
    gValues.Clear();
    hValues.Clear();
    fValues.Clear();

    //If the final Location in ClosedList is not the end then continue
    if (ClosedList[ClosedList.Count - 1] != End)
        CheckSquare(ClosedList[ClosedList.Count - 1], End);
}

```

Help or nudges in the right direction would be greatly appreciated.

# Answer
A typical implementation of A\* will use a loop instead of recursion. Change the `if (ClosedList[ClosedList.Count - 1] != End) CheckSquare(...)` into a while loop.

However, I suspect the code won't work correctly even with that change, because you're clearing all the data after you check just one square. A\* needs all that data (OpenList, gValues, etc.) so you don't want to clear it before you're finished finding the path. You're going to need to change more to make it work.

If you're looking for some sample code, see my article. I try to keep the sample code as simple as I can.
> 6 votes

# Answer
Your best bet is to attach the debugger and see where things are going wrong. If you're getting a stackoverflow it means you're recursing too far into your `CheckSquare` method. That either means your map is too large, or you're checking the same tiles multiple times. I'd bet on the latter given your screenshot.

Depending on the IDE you're using, you can cause the debugger to break after the line you're targeting has been reached a certain number of times. That means you can place a break point at the beginning of your `CheckSquare` method and set it to break after 50 or so iterations.

It could be that you're adding squares to your open list that are on your closed list. Which can result in you going in circles when the path is not straight forward.

You might want to switch to an iterative approach to more easily track down your problems.
> 1 votes

---
Tags: 2d, path-finding
---


# Question
Title: Use of SpriteFonts without installing on host machine
I am working on a Windows game for my university project. In this project I am using a custom TrueType font which is not installed on any university computers. For submission my game is required to run in debug mode and a demonstration given. Therefore is there any possible way to read the font from within my project rather than installing the font on each computer that the project will be viewed on.

# Answer
> 3 votes
Just build the XNB file on your personal machine, and use that file in your project.

Remove the `.spritefont` file from your content project. Then add the built XNB file to your game project, in an appropriate directory (generally "Content") and set its properties (select it and press F4) to "Copy if newer".

This is off the top of my head. So look at the output directory to see if it's working correctly.

---
Tags: xna, c#, xna-4.0, monogame, windows
---


# Question
Title: Arbitrary number of VBO to Vertex Shader
I am currently using standard modern OpenGL way to render a mesh via VBO and attributes

```
    glEnableVertexAttribArray(aVertexPosition);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glVertexAttribPointer(aVertexPosition, 3, GL_FLOAT, GL_FALSE, 0,0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

```

and in the GLSL code also the standard way to received into as `in vec3 aVertexPosition`.

However, I wonder if there is anyway to make this for a dynamic amount of VBOs. Let's say my software creates a number of VBOs that depend on the inputs, and I successfully create and allocate memory for all of them, how do I pass all of them to the shader? Does the number need to be constant? If so, what is the best way to do it?

# Answer
In DirectX this is called the input signature. In older version of DX (DX9) you could skip to plug a stream-source, and then all unplugged things in the shader would default to zero value. (zero value filled from void by the pipeline).
I would suppose OpenGL also does this kind of things.

Note the newer versions of the graphics libraries (DX10+) do not accept unbound data to be passed to a vertex shader. I don't know the details on OpenGL core 3.3+ on this subject, but if it followed DX10 philosophy then there is no way to do this flexibly.

You need to create all the combinations of the shaders that will accept the streams as input, and your engine (on the CPU side) needs to plug the good shader according to the attributes combination that you have got.
You can generate the combinations using `#defines` and turning them ON/OFF using binary counting at compile time, in a loop, and store the whole thing using an integer ID as a key, that you can create as a binary flag combination of the presence of your attributes. This is a compact hash so you can use an array to store the result, but careful, 5 attributes = 32 combinations.
Then in the shader, you can also use the defines to do something with the source when it is present.
> 2 votes

# Answer
I agree with what v.oddou said. An extra point, changing the number of inputs of the shader can be thought of as changing an interface of a function, they are not strictly the same but the concept applies. So expect by default a recompile for your shaders to add more input streams, you also need to modify your code to pass those streams. You can use `#define` to support multiple inputs.
> 1 votes

# Answer
I'm not quite sure whether I understand you correctly, but you can assign different buffer objects to different attributes. The buffer object currently bound while calling glVertexAttribPointer will be used as the data source:

> If a non-zero named buffer object is bound to the GL\_ARRAY\_BUFFER target (see glBindBuffer) while a generic vertex attribute array is specified, pointer is treated as a byte offset into the buffer object's data store.
>
> Also, the buffer object binding (GL\_ARRAY\_BUFFER\_BINDING) is saved as generic vertex attribute array client-side state (GL\_VERTEX\_ATTRIB\_ARRAY\_BUFFER\_BINDING) for index index.
> 0 votes

---
Tags: opengl, glsl, vbo, vertex-buffer
---


title: Implementing a motorized hinge joint

text:
# Question
Title: Implementing a motorized hinge joint
I have a 2d physics engine, with three boxes: "body", "left wing" and "right wing". The wing boxes are connected to the body using a hinge joint. The physics world has no gravity.

I'm attempting to rotate the wings around their hinge connection, as if the joint is motorized but I'm not exactly sure how to achieve that. If I exert force with a downward vector on the center of the wings, the body itself flies down. This is undesirable. With an actual hinge motor, only the wings will rotate about the hinge, affecting the body only when they hit it.

Which forces should be added to the wings, and at which origin points?

I'm using Phaser.io, with P2.js physics, but the question is platform-agnostic.

# Answer
> 1 votes
Apply two forces in opposite directions. The one at the far end of the wing turns it. The other at the hinge - applied to the wing not the body at that point - zeros out the first so the whole craft doesn't move.

Note that the far-end force is perpendicular to the line from the hinge to where it is applied. That's not essential, but it won't accomplish anything useful to have it at some angle.

# Answer
> 0 votes
This exact same question from the exact same person has already been answered on another site.

http://www.html5gamedevs.com/topic/8824-p2-motorized-hinge-joint/

You can use the motor in the joint to create the rotation around the joint: To make things simpler, how about enabling the motor on the constraint?

```
constraint.enableMotor();
constraint.setMotorSpeed(1);

```

Documentation: http://schteppe.github.io/p2.js/docs/classes/RevoluteConstraint.html

Demo: http://schteppe.github.io/p2.js/demos/car.html

---
Tags: physics
---


# Question
Title: libgdx universal tween engine how to control the tweening speed?
How can i control the speed of a tweening sprite? Here is the code:

in create ()

```
/*try tween*/
            w = Gdx.graphics.getWidth();
            h = Gdx.graphics.getHeight();

            texture = new Texture("nube_png_by_diieguiitoh-d4vhyzb.png");
            texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

            sprite1 = new Sprite(texture);
            sprite1.setPosition(50,0.25f*h);

            Tween.registerAccessor(Sprite.class, new SpriteAccessor());
            manager1 = new TweenManager();
            Tween.to(sprite1,SpriteAccessor.POSITION_X,1000f) //** tween POSITION_X for a duration **//
                    .target(w-100) // ** final POSITION_X **//
                    .ease(TweenEquations.easeInOutQuad) //** easing equation **//
                    .repeat(10,1000f) //** ten more times **//
                    .start(manager1); //** start it
            startTime = TimeUtils.millis();
/*try tween*/

```

In render()

```
        batch.begin();

        delta = (TimeUtils.millis()-startTime)/1000; // **get time delta **//
        manager1.update(delta); //** update sprite1 **//
        sprite1.draw(batch);

        batch.end();

```

# Answer
> 1 votes
You don't. That defeats the purpose of a tween. A tween is supposed to control the speed itself using an easing function and giving it a total time. If you want to control the speed of an object, you'll have to give it a velocity yourself and update it through your normal game loop.

---
Tags: libgdx, tweening
---


title: How to move Vector2 along angle?

text:
# Question
Title: How to move Vector2 along angle?
These are my Vector2's that I am using for this function.

```
public Vector2 position = new Vector2();
public Vector2 velocity = new Vector2();
public Vector2 movement = new Vector2();
public Vector2 direction = new Vector2();

```

Here is the function that I use to move the position vector along an angle. setLocation() just sets the new location of the image.

```
public void move(float delta, float degrees) {
    position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2);
    direction.set((float) Math.cos(degrees), (float) Math.sin(degrees)).nor();
    velocity.set(direction).scl(speed);
    movement.set(velocity).scl(delta);
    position.add(movement);
    setLocation(position.x, position.y); // Sets location of image
}

```

I get a lot of different angles with this, just not the correct angles. **How should I change this function to move a Vector2 along an angle using the Vector2** class from com.badlogic.gdx.math.Vector2 within the LibGDX library?

I found this answer, but not sure how to implement it.

---

**Update: I figured out part of the issue. Should convert degrees to radians. However, the angle of 0 degrees is towards the right. Is there any way to fix this? As I shouldn't have to add 90 to degrees in order to have correct heading. New code is below**

```
public void move(float delta, float degrees) {
    degrees += 90; // Set degrees to correct heading, shouldn't have to do this
    position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2);
    direction.set(MathUtils.cos(degrees * MathUtils.degreesToRadians), MathUtils.sin(degrees * MathUtils.degreesToRadians)).nor();
    velocity.set(direction).scl(speed);
    movement.set(velocity).scl(delta);
    position.add(movement);
    setLocation(position.x, position.y);
}

```

# Answer
I think you could switch your cos with sin and vise versa if you're really against adding 90 in your function, but I think adding 90 is a perfectly viable solution. Once a function works, you shouldn't have to care what's inside of it.
> 3 votes

---
Tags: libgdx, vector, angles
---


# Question
Title: Design question: best way to model and visualize a long grid of data
Perhaps some noob questions for a scientific application that you can assist with: I am trying to render a large, evenly spaced grid of data in 2D. The full data set dimensions could be anywhere from 48x250,000 to 1000x15,000,000 points/pixels.

The data is evenly spaced, but I need to change the aspect ratio, and then render only a section of that data on the screen at a time. I need the users to be able to smoothly scroll forward or backward along the long dimension with user input, or press the "play" button and have it move forward or backward at certain speed.

I am looking for advice on how to handle this via DirecX or OpenGL (probably using SharpDX or OpenTK).

The basic approach I am considering is to use textures that the application generates on the fly from the data and then map them to a very simple model. I would keep the graphics card supplied with a large enough scene so that as the user scrolls or moves around that they don't have to wait for the application. Questions I have are:

1) does this approach make sense? i am presuming this is way more efficient and faster than creating a bunch of primitives with discrete colors. true?

2) is there a particular texture format that is good to use and easy to create (or do i create it directly)? I have the data in application memory as large arrays and it loads/unloads from disk as needed. I would map the scalar values to a color as I create the image/texture blocks.

3) would mipmaps be useful? i could have an aspect ratio (or small enough window) that there are fewer screen pixels than data in the viewable range. Or, would it just automatically subsample?

4) if mipmaps are used, most of the scaling is along the long dimension, so could i uses non-square subsamples?

4) does creating compressed images make sense? or, would the compression overhead yield much benefit (or how might i determine this)

5) how would i go about finding an optimal texture size?

Any other general advice?

Hopefully this is a straightforward problem for the cool stuff y'all do in games!

# Answer
> 1 votes
1. Yes, this is a fine approach - it will be orders of magnitude faster than creating a primitive per data point.
2. Assuming single-channel data, you should use whatever `DXGI_FORMAT` (or equivalent in OGL) maps to your source data, and convert in the pixel shader. There are native types for 8, 16, and 32-bit integers, as well as 32-bit floats. You should also only create a few textures up front and then reuse them - don't create them on the fly. Instead, keep track of which ones are off-screen and overwrite the data of e.g. the least-recently-used one.
3. If you allow scaling out significantly, MIP maps will be useful. Be sure to enable 16x anisotropic filtering though, since you'll have a huge uv-delta mismatch basically all the time. 4(first): Anisotropic filtering does precisely this.
4. I wouldn't bother with GPU compressed formats initially. Your bottleneck will almost certainly be disk IO, so if anything I would use something like LZMA to compress the chunks of data on disk.
5. A good size would be to use a height of whatever your data height is (48 - 1000), and use 1024 or 2048 for your width. This should offer a good balance of texture count versus total memory used (and the ability to swap out LRU texture data).

Other tips:

1. You might intially think to create a geometry and camera that you conceptually scan accross it. A much simpler approach is to create a full-screen quad, and just update the texture coordinates on the fly using a cbuffer with scale/offset parameters.
2. Do all your visualization math (color gradients, etc.) in the pixel shader - don't convert on upload unless it's required to fit into one of the hardware native formats (e.g. if you're using a custom number format for some reason). Sub-point: if your data is double-precision, use the `R32G32` format, then in the shader use the `asdouble(color.r, color.g)` instruction to get the original value back. Note that double-precision support is an optional feature though - not all hardware supports it.

---
Tags: opengl, 2d, textures, directx, grid
---


title: Skipping a loop in foreach?

text:
# Question
Title: Skipping a loop in foreach?
I'm trying to get Unity to filter through a list of nodes, but I am unsure on how to do so. This is what I have derived.

```
foreach (TileNode z in map.nodes)
        {
            int num = TileNode z;
            if(num%2==0){
                continue;
            }

            z.collider.enabled = true;
        }

```

However an error prompt states that 'z' is an unexpected symbol. Any advice on the proper syntax to deal with this will be greatly appreciated.

Also, an example of how do peform filtering using LINQ will be helpful.

# Answer
This line:

```
int num = TileNode z;

```

You are declaring a `TileNode` with symbol `z`, but you are assigning that to an `int`. You can't assign a symbol declaration under any circumstances, so the compiler is yelling at you for it. It also doesn't make any sense; you probably want to assign that `int` to some property of `z`, right?

This is doubly wrong because you already declared that same symbol in the foreach loop, though the above line would be wrong regardless.

---

The linq syntax is exactly as you wrote it, except you change your conditional statement into a nearly-identical lambda expression. You can read all about them here.
> 3 votes

---
Tags: unity, game-loop
---


# Question
Title: ConcurrentDictionary as a main container for game objects?
I wonder if it is wise to use ConcurrentDictionary as a main container in a game? That is it will be used to:

* update every object inside it in a parallel.Foreach loop;
* add (but not remove) objects inside it in a parallel.Foreach loop (sometimes while updating);
* retreive data from the dictionary with a Linq query/ simply by index in sometimes a parallel loop, but mostly in the main thread;
* remove data from it in a parallel loop (but NOT when updating objects) \<- this step can be done in the main thread.

What could be the disadvantages of this list compared to HashSet (we are using the latter now, but we are only reading from it in parallel - when updating models). What lists are used in big engines?

# Answer
I wouldn't expect significant performance disadvantages to using a ConcurrentDictionary in your case, but as with anything concurrent I'd recommend tests/profiling.

Also, I haven't the foggiest idea what the big engines are using. Sorry.

That said, let's check your 4 uses against the information here: http://arbel.net/2013/02/03/best-practices-for-using-concurrentdictionary/ (Interesting read, esp. for cautionary notes.)

1. Updating should be no different, though you'll want to think about whether it's an issue for you that the enumerator can change during the loop. (The enumerators aren't snapshots.)
2. You may need some bookkeeping to control updates on mid-update-loop additions. It seems like these additions won't cause significant contention thanks to the multiple-lock design, but you'll want to verify that for yourself.
3. Retrieving "by index" seems a little fishy to me, depending on what exactly you have in mind. Linq seems fine.
4. Removing should be fine, though again the enumerator can change so be careful with the parallel loop.

It seems to me that your biggest risk in using a ConcurrentDictionary is, unsurprisingly, bookkeeping/correctness. That comes with the territory, especially if you're shifting back and forth between distributed and centralized (main thread) logic.

As long as you carefully compare your usage/assumptions against what the CD is doing, the change should yield a solid scalability win over your HashSet implementation. Considering the additional complexity, though, if you haven't yet verified that the HashSet is a significant bottleneck, you may want to do that first.
> 1 votes

---
Tags: scene-graph
---


# Question
Title: How can I send matrix data to shaders without the Effects11 framework?
I'm making a Direct3D engine but I'm stuck with this one little problem.

I want to not use effect files but instead use shader files. What can I use to send matrix variables to shaders if I don't use `ID3D11XEffectMatrixVariable`?

# Answer
> 2 votes
To send constant values to shaders without using the effect framework, you create constant buffers and bind them to the pipeline with (for example) `VSSetConstantBuffers`.

For example:

```
// You can of course eschew the structure, but this allows you to stuff more data
// into the pipeline with a minimum of fuss; you should generally create constant
// buffers based on what you would update together (per frame versus per object
// state, for example) rather than one-buffer-per-variable.
struct MyConstantBuffer  {
  XMFLOAT4X4 transform;
  // ...optionally more stuff...
};

MyConstantBuffer instance;
instance.transform = someMatrixValue;

// Create buffer description and resource data objects.
D3D11_BUFFER_DESC description = { 0 };
description.ByteWidth = sizeof(MyConstantBuffer);
description.Usage = D3D11_USAGE_DYNAMIC;
description.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
description.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

D3D11_SUBRESOURCE_DATA data = { 0 };
data.pSysMem = &instance;

// Create the buffer and bind it.
ID3D11Buffer * result = nullptr;
device->CreateBuffer(&description, &data, &result);
context->VSSetConstantBuffers(0, 1, &result);

```

MSDN has a how-to page as well.

---
Tags: c++, directx11, c
---


# Question
Title: Convert triangle mesh to group of line segments
I have a 3D `.OBJ` model file that is loaded in my OpenGL ES 2 Android application using ASSIMP library. All the faces are triangulated.

I want to draw the wireframe for my mesh. In OpenGL we have something called `glPolygonMode` that enables wireframe drawing just in one line.

Is there a function I can use to convert those triangulated faces into a pair of Line segments and then draw these line segments using `GL_LINES`?

Any better approach to draw wireframe for 3D mesh in OpenGL ES 2 would be appreciated. Maybe something based on GLSL shader.

# Answer
A (triangular) face is created using tree or more vertices. An `aiModel` contains a list of all vertices in the model and a list of faces. Each `aiFace` contains the indices to vertices that make up this (triangle) face. An index is the position in the list of vertices where the vertex we want is.

Here is some pseudo code that retrieves the thee vertices of the first face.

```
vertex0 = aiMesh.mVertices[aiMesh.mFaces[0].mIndices[0]];
vertex1 = aiMesh.mVertices[aiMesh.mFaces[0].mIndices[1]];
vertex2 = aiMesh.mVertices[aiMesh.mFaces[0].mIndices[2]];

```

You can now draw lines between vertex0-vertex1, vertex1-vertex2, vertex2-vertex0 to accomplish wireframe rendering.

Note that an `aiMesh` can have 0 or more vertices, 0 or more faces, and an `aiFace` can have 0 or more vertices.

For more information see: http://assimp.sourceforge.net/lib\_html/structai\_mesh.html
> 2 votes

# Answer
There are two possibilities, as far as I know:

1. Draw your geometry using one of the GL\_LINE\* topologies: `GL_LINE_STRIP`, `GL_LINE_LOOP`, `GL_LINES`.
2. Use a fragment shader and some math to define the wireframe on-the-fly, without changing the topology. See this very nice example using WebGL: Wireframe display with barycentric coordinates.
> 1 votes

---
Tags: android, opengl-es2, assimp
---


# Question
Title: Calculating aim point to pass through other point
We know for an object:

* Initial point O(x,y)
* Initial speed (s\_x,s\_y)
* Constant ***vector module*** aceleration (A)
* A point P(i,j) where we have to pass through in the future.

We need:

* A point W(x, y) so the angle alpha (or only the angle alpha), formed between O and W, can be used to calculate acceleration in both axis:

Ax = A * cos(alpha)

Ay = A * sin(alpha)

so that the object passes through W.

How do I define an elliptic motion system knowing two points of the orbit (and Vo)?

I'll appreciate alternatives to design a guided rocket too.

My attempt for solving this:

1. Calculate module of initial point O, initial speed So, destination point D. (Aceleration module A is given)
2. Use these terms to calculate the time we need to arrive to D with the equation:

D = O + So\*t + 1/2 A * t^2
3. Find out the value of alpha from this equation, knowing time:

Dx = Ox + Sox * t + 1/2 A * cos(alpha) * t^2

I tried to implement this, but for some reason it doesn't work. Should this theorically work?

# Answer
> 2 votes
If I understand your problem correctly, you wish to determine, for a given initial location, initial velocity, desired target, and constant magnitude acceleration, what constant point the acceleration must be aimed at in order to pass through the desired target point at some future time.

This is the definition of circular motion around the aiming point, for a circle of radius *r* passing through both the initial location and the target, where by the well-known kinetic equations of circular motion the radius can be derived as:

```
r = v^2 / a

```

where *v* and *a* are respectively the magnitude of the starting velocity and acceleration.

Now it is sufficient to obtain, using some basic Euclidean geometry, the location of the point that is distance *r* from both the starting point and the target location, on the desired side so that the intersection occurs in the future rather than the past.

---
Tags: movement, movement-prediction
---


title: Remove item after crafting

text:
# Question
Title: Remove item after crafting
I'm having one last problem with my crafting system. Say an item takes 2 rocks, 1 twig, and 1 vine. When I craft the item, only 1 of each item is removed instead of the correct amount of items related to the crafting recipe.

```
foreach (ItemRecipe recipe in player.PlayerCraftingSystem.CraftingList)
{
    if (recipe.Name == item.ItemName)
    {
        var commonItems = recipe.Items.Intersect(player.PlayerInventory.Items, new ListComparer()).ToList();

        var nameMatches = player.PlayerInventory.Items.Where(x => commonItems.Any(y => y.ItemName == x.ItemName));

        foreach (var match in nameMatches)
        {
            match.ItemCount--;
                if (match.ItemCount == 0)
                    match.ItemName = "empty";
        }
    }
}

```

I know this is wrong because -- will only take away one item, but I am having trouble with ideas of how to remove the correct amount of items. Does anyone have any ideas? I was thinking looping through the items being removed and using a while loop to keep removing items until it was correct, but I tried that and it froze up the game.

The item variable is the item being crafted.

Edit:

I tried adding a loop like this, but it doesn't work. It removes too many items

```
foreach (var match in nameMatches)
{
    foreach(Item itemCount in recipe.Items)
    {
        match.ItemCount -= itemCount.ItemCount;
        if (match.ItemCount == 0)
            match.ItemName = "empty";
    }
}

```

# Answer
If you look at the first line inside the foreach for the matches, you're reducing the item by 1. Without knowing your item/recipe structure I can offer this. Your recipe should know the quantity of each item it needs. So when it makes a match it should be doing something along the lines of this.

```
match.ItemCount -= recipe.ItemQuantity(match).

```

This way the recipe controls how much of them item is removed. If you want to change the amount of an ingrediant later, you can modify the number on the recipe and be done.

Edit in response to your edit.

Look at that loop closely. You're looping over each match.ItemCount for as many items are in the recipe, for each match. You don't need that inner loop. Just a similar line to the one above. Your foreach would look like this.

```
 foreach (var match in nameMatches)
 {
      match.ItemCount -= receipt.ItemQuantityFor(match);
      if (match.ItemCount == 0)
           match.ItemName = "empty";
 }

```
> 1 votes

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


# Question
Title: Heuristics used for determining device performance
Often times PC games offer an elaborate settings page which lets you turn 20 different knobs. Users can modify these settings at will in the pursuit of performance, or conversely, visual quality.

But, the first time you launch the game, how does it know what settings to apply? I'm guessing there is something smarter going on than just using the 'MEDIUM' configuration for everything, and then letting the user figure out the right configuration...

In fact, I'd further guess that settings are chosen on first launch in the interest of performance, i.e. the game will choose the correct settings for this particular machine so it can run at 60 FPS and not crash from out of memory... So, if there is indeed a runtime algorithm employed that selects the appropriate settings, what kind of heuristics are used to choose those settings?

* Is there a database of devices, or hardware components, that can be used to determine the correct performance of a device? (I assume not.)
* Is there a scoring system based on the various specs of system components: system memory size, D3D feature level, GPU memory, etc... This seems more believable, but I'd like to know if there are examples of this being done.

And, there are other strategies that I'm *not* interested in, e.g. doing a mini profiling run and then determining the correct settings based on framerate of that run. Or, dynamically tuning the performance on the fly, e.g. detect the framerate is dropping, and then somehow degrade the quality to improve.

Both of those approaches aren't what I'm after. I'm looking for some heuristics to employ when the game launches, and I'd like those heuristics to be able to spit out some sort of performance criteria for the device so I can know what settings to run my game at.

If I get it wrong, the user can always go back and turn the knobs in the settings page, but I'd like to do most of the work for them!

# Answer
Basically, there will be a mapping from graphics performance level setting (low/medium/high/et cetera) to particular values of a variety of internal knobs and dials in the underlying graphics engine. It can affect almost anything: texture sizes, maximum LOD level, multisample passes, toggling entire features (such as reflection) that often require extensive extra GPU resources, and so on. It is not a fixed list of features and will vary from game to game or engine to engine.

Usually these mappings will be decided experimentally or via simple algorithms based entirely on the range of hardware (from the minimum spec upwards) the game is expected to ship on.

Sometimes studios will amass a database of particular GPU versions and bugs or hidden issues with those GPU and/or related drivers that they will use to toggle features behind-the-scenes as well (although this practice was far more common in the earlier days of GPUs, where graphics APIs were much younger and there was much less standardization across the hardware).

There is no general solution for the heuristics you're looking for. It depends on the demands and needs of *your* game. But you're right that most PC games tend to run a basic hardware check to "auto-detect" the appropriate settings. You can implement this relatively easily yourself once you've established what your game's performance breakpoints will be.

Both major graphics APIs offer ways to query their support for particular features -- for example, whether or not they support particular kinds of multisampling, or how many extra render targets you could make. Many settings can be "auto-detected" simply by creating a graphics device and asking the API directly.

For all the rest, you can simply probe them experimentally (for example, try to allocate textures of the maximum size you want for your highest setting; if it fails, fall back to lower setting breakpoints until you succeed).
> 4 votes

---
Tags: performance
---


# Question
Title: How do I make an 8 bit sprite sheet using GIMP or Paint.NET?
I'm looking to create a sprite sheet for an 8 bit, 2D RPG I'm making. All I need to do at the moment is render in some textures. To do this, I want to make an 8x8 sprite sheet. Now, I am really bad at using anything to do with GIMP or Paint.NET, so I came here for some help.

*Are there any ways to create an 8x8 blank sprite sheet using either GIMP or Paint.NET?*

I have some other info you might need for whatever reason down here:

* I'm using Java to code this game.
* I'm following Ryan van Zeben's (DesignsByZephyr) tutorials, and I'm trying to make the same sprite sheet he made in Episode two of his series.
* At the moment, I don't have access to Photoshop or anything that requires a lot of money (I'm quite young).
* I'm willing to use plugins and/or other free photo-editing programs.
* I am using Windows 7 as my OS, and Eclipse Luna as my IDE.

# Answer
> 3 votes
Sure, this is quite simple really. I'll guide you through Paint.net.

1. Open the application and go to New.
2. In the dimensions, put 8 for width and 8 for height.
3. A new 8x8 canvas will open, typically I zoom in all the way to 3200%.
4. I'll also get rid of the white background layer, by making a new layer, then deleting the background one.
5. Now you have the canvas to work on, you can save it as a .pdn file.
6. When you are ready to save the tile/image/sprite, go to File -\> Save As, and choose file type: PNG.
7. A "Save Configuration" box will open up and you can choose "Bit Depth: 8-bit" to save the completed work.

# Answer
> 0 votes
Note: This question specifically asks how to make an 8\*8 sprite sheet using 8 bit graphics. A sprite sheet is a series of images meaning more than one image on a single image(not 8px\*8px). You can do all the editing and creating you want to do before changing the image to the indexed format using Gimp which will convert the image to the required 8 bit format. Palettes are used when pictures are 1 bit, 4 bit, or 8 bit. Both, Paint.net and GIMP 2 have there own unique good and bad qualities. Where one is lacking the other usually does not so I use both for a single sprite sheet. Some of the features the manipulation programs have are not simple and require some time and effort to acquire a working knowledge of the tools.

To make the 8\*8 sprite sheet using 8 bit graphics I will walk you through this using Gimp.

1. Open the application.
2. Click New
3. You will want to make the sprite sheet so that it is in a nice easy to retrieve size such as 32\*32 or 64\*64 or 128\*128 example: (32\*8 = 256) or use preferred way of measuring
4. Select Advanced options and fill with transparency
5. Click OK
6. The menu option is at the top of the screen- click image
7. Hover Mode- select indexed
8. Now you have the option of generating a palette or choosing another way of retrieving a palette
9. Enabling dithering may be a good option
10. Now when you view the toolbox the choice of foreground and background colors will give you a nice choice of 8bit color per pixel to work with.

Make sure you pay close attention to the measurement on the top and left of the screen so that you keep your sprites within the boundaries you set when creating the 8\*8 sprite sheet. If you choose 32\*32 then each sprite should stay within those measurements with a total of 64 sprites to use in your RPG which should be plenty to work with for your first RPG. You can make your sprite sheet with as many pixels of your choosing and still use the 8bit per pixel rule. Also, with Gimp you can choose to use the rectangle tool which can be very useful making your sprites the right size. You can drag the rectangle/square to size and then work within the boundaries of the rectangle/square without worrying about drawing over another sprite which keeps them all perfectly square and neat. Good Luck. Your sheet should look something like the following image made with gimp for 8\*8 pixel sprites on a 64px\*64px layer . Each square represents a space for a sprite...

---
Tags: spritesheet
---


title: Isometric View of "Voxel-Style" Terrain

text:
# Question
Title: Isometric View of "Voxel-Style" Terrain
Suppose you have an arrangement of data for a terrain set up like this: `terrain[layer][cart-x][cart-y]`. Each location (*ex.* `terrain[0][0][0]` *for the top left corner of the lowest layer*) in the array simply stores `-1` for air, `0` for water or `1` for dirt. How should I loop over this data to produce a "camera?" For example, given a focal point, world, and screen size, iterate over only the visible blocks and call the block-render function.

I have some semi-working Javascript, but I have several issues;

**How can I find the minimal number of tiles to draw so that the screen edges are covered, while keeping the `position` centered on screen?** I've gotten this done but it's messy.

**When the layer depth varies, how do I properly account for that** as far as offsets are concerned? Currently, I can make an offset calculation for a depth. But it doesn't carry to other depths. Like say, you are viewing an area where there is terrain at layer 15. The camera is offset by a certain amount to restore the focal point to center. But if you move to an area where the height is only 14, then you'll start to see a drop off toward one edge. This also happens when there is something much lower on the "forward" side.

**How do I prevent drawing blocks that are completely obscured?** This one is very important and should be seen as the priority of these, but I don't think I can move on to it yet.

## Here's what I've made so far:

View working (hacky) example on Codepen

(Showing only what I think are the important parts here)

```
function screenPos(x,y,z)
{
  var op = {
    x: (x-y)*th,
    y: ((x+y)*th/2)-(z*td)
  };
  return op;
}

function drawTerrain(position, world, ctx, minElev, maxElev) {
  minElev = (minElev===undefined? position.z : minElev);
  maxElev = (maxElev===undefined? position.z+1 : maxElev);

  var cen = {
        a: position.x + position.y,
        b: position.x - position.y
      },

      max = { //Use testSize instead of canvas size so we can see overdraw
        a: Math.floor(testSize.y/th),
        b: Math.floor(testSize.x/ts)
      },

      startPos = {
        x: ((cen.a - max.a) + (cen.b - max.b))/2,
        y: ((cen.a - max.a) - (cen.b - max.b))/2
      },

      offset = screenPos(startPos.x, startPos.y);

  //account for testSize offset
  offset.x-=50;
  offset.y-=50;

  //regular offsets
  offset.y += th/2;
  offset.y -= (th)*minElev;

  ctx.textAlign = "center";
  ctx.textBaseline = "middle";

  for(var z = minElev-1; z < maxElev; z++) {
    for(var a = cen.a - max.a -1; a < cen.a + max.a +3; a++) {
      for(var b = cen.b - max.b -1; b < cen.b + max.b+2; b++) {
        if ((b&1) != (a&1)) continue;

        var x = (a+b)/2,
            y = (a-b)/2;

        drawTile(x, y, z, offset, world, ctx);

        i++;
      }
    }
  }
}

```

Some thoughts on possible solutions: I think that *at least* one step of conversion between x/y and a/b could be removed here, as it's gotten all convoluted while trying to make things work. There are lots of things like that, I realize. The Codepen page shows exactly how thrown-together the current solution is. The only thing I'm interested in is fixing and optimizing the main loop and any methods/data necessary to drive it.

P.S. I didn't feel the need to include the drawTile function on this page as it has very little conditional logic, only basic stuff, and calls to the same screenPos function. That said, you can see it at the Codepen Example

# Answer
Here's how most people start out in it for "basic" terrain height maps ...

Create my volume (voxel array). Generate a Y value for each x,z im interesting (terrain heightmap generation). Loop through a column of voxels from 0 to terrain height and set their values as "inside the volume" (on).

Generate a mesh based on examination of the volume by looping through each voxel and asking "is the voxel on each face resulting in a sign switch".

For example ... Lets take the most basic way of handling voxel data and assume all voxels are boolean true or false where true is "something" and false is "nothing".

I have a height map value of say ... 3 so using 1 for true and 0 for false my data for the current column would be ...

111000...

This tells my mesh generator that at point x,3,z I will need to render "something".

taking this a step further we can then do the check on all sides of our "volume of space for a voxel and its neighbours" ...

Assuming a voxel is a cube (which makes sense when storing as a voxel\[\]\[\]\[\]) you can do something like ...

```
var xyz = (1,1,1);

if !(y + 1) { top face visible }
if !(y - 1) { bottom face visible }
if !(x - 1) { left face visible }
if !(x + 1) { right face visible }

```

...

You get the idea ...

Most people use float values for their voxel data as this allows more precision in the mesh generation as you are looking for a point at which the data evaluates to 0 for a given "cell" where a cell is a chunk of 27 voxels and you are evaluting the center voxel.

for example ...

if the center voxel = 0.5 and the voxel above = -0.4 the sum of the two values is -0.1 which means that the surface you want to render is -0.1 from the top of the voxel space for your center voxel. Meshing algorithms like Marching cubes, or Dual Contouring work this way.
> 0 votes

---
Tags: mathematics, rendering, isometric, viewport
---


# Question
Title: Collider2D and Rigidbody2D, how do they work?
I have been learning JavaScript and Unity for a week now. I learned how to make Cube as a Ground and another Cube as a player and I used this code to make the Player Cube move forward and backward and jumping

```
var walkspeed: float = 5.0;
var jumpheight: float = 250.0;
var grounded = false;

function Update() {

    rigidbody.freezeRotation = true;

    if (Input.GetKey("a"))
       transform.Translate(Vector3(-1, 0, 0) * Time.deltaTime * walkspeed);
    if (Input.GetKey("d"))
       transform.Translate(Vector3(1, 0, 0) * Time.deltaTime * walkspeed);

    if (Input.GetButton("Jump")) {
        Jump();
    }
}

function OnCollisionEnter(hit: Collision) {
    grounded = true;
}

function Jump() {
    if (grounded == true) {
        rigidbody.AddForce(Vector3.up * jumpheight);
        grounded = false;
    }
}

```

I also learned how to make a character hit box. how to make a sprite and animation. pretty much the basic stuff.

Couple of days ago I created simple ground in Photoshop and a simple character and imported them to Unity3D. Whenever I use my code above the character keeps falling from the scene. Like the character has nothing to stand on. After thinking about it it make sense because I really didn't make anything to make the player character understand that he should stand on something so I started reading about this issue and I realized that there is something called `Collider2D` and `Rigidbody2D`.

Now I'm really stuck here I just don't know what to do. I applied the `rigibody2d` to my character picture and the `Collider2D` to the ground picture but whenever I play the project the gravity makes my character falls down.

This is my question:

How can I make the `rigibody2d` object realize that it shouldn't fall if there is a `Collider2D` object under it? So when I jump it's going to jump and the gravity going to bring it back to the ground.

# Answer
> 2 votes
Here is a bullet point list of items you may want to look over.

1. Your function for the collision is wrong. You’re using “OnCollisionEnter” when you need to be using “OnCollisionEnter2D” if you’ve attached 2D versions of the components to your game objects.
2. For your left/right input do not use transform.Translate, this ignores physics calculations and can cause weird effects (like appearing partially in a wall and being bounced back out of it). Use rigidbody2D.AddForce(...) or rigidbody2D.MovePostion(...). This takes physics into account when moving the object.
3. Your ‘floor’ and ‘character’ both need a Collider2D component. The moving object ‘character’ also needs the Rigibody2D component. Without a Collider2D component on both objects, collision will not be detected by the Rigibody2D.
4. Make sure your objects are actually intersecting. If you’re in 2D space, make sure they are both at the same Z (or whatever axis you’ve chosen to represent your depth into the screen).
5. Make sure the bounds of the Collider2Ds are intersecting. Select both objects in the hierarchy to see the green outline of the Collider2D, make sure they’re large enough. Hopefully these point you in the right direction.

Quick overview of Collider2D and Rigidbody2D.

Objects which have Rigidbody2D components will interact with Collider2D components automatically (unless they've specifically been told not to through some other method).

Collider2D have two modes to them, trigger and non trigger.

A trigger Collider2D does not invoke physics on a Rigidbody2D. They can be triggered by other Collider2Ds and are pushed through the OnTriggerEnter2D/Stay2D/Exit2D methods.

A non-trigger Collider2D will invoke physics on a Rigidbody2D. This typically means the Rigidbody2D item will apply various forces if its Collider2D hits another Collider2D.

# Answer
> 0 votes
Rigidbody2D controls the physics, but your character needs a Collider2D as well otherwise no collision will occur.

```
- Character GameObject
   - Collider2D
   - RigidBody2D

- Any GameObject that character will collider with
   - Collider2D

```

# Answer
> 0 votes
First of all, it is best to work strictly in a 2D environment by disregarding any form of 3D entity such as cubes. I recommend importing in sprites and re-configuring your Unity project so that all the scripts are working in accordance to them.

Also, in order to make your RigidBody2D be able to recognize impact with a Collider2D, your RigidBody2D must have a Collider2D (BoxCollider2D, etc) assigned as well.

The reason for this is because the RigidBody2D simply handles the physics of its assigned entity. However, in order for the entity to even be able to collide and interact with the environment, you must define its boundaries/collision area through assigning a Collider2D.

http://docs.unity3d.com/ScriptReference/Rigidbody2D.html

"... Adding a Rigidbody2D component to a sprite puts in under the control of the physics engine. By itself, this means that the sprite will be affected by gravity and can be controlled from scripts using forces. By adding the appropriate collider component, the sprite will also respond to collisions with other sprites."

---
Tags: unity, physics
---


# Question
Title: Handling player and AI in a component based structure dynamically?
I'm trying to find a way to allow both input and AI to call actions of an actor in a component based structure for a 2d turn based game. The actions make use of the components. To keep the system flexible I don't want to statically set what actions the actor has in the actor class.

Right now I have action classes who have ids and I'm using maps to hold the actions and allow the input and AI to execute actions by calling a function in the actor class. Now I've run into all sorts of issues like it not working well with using different parameter types or amounts and other things. So is there a better way to do what I try to achieve?

This is my actor class that holds a map with actions that take two ints:

```
class Actor
{
    friend Scene; /* allows the scene to move the acotr */

public:
    Actor();
    ~Actor();

    int getCellX() { return m_CellX; }
    int getCellY() { return m_CellY; }

    void addComponent(Component* component);

    void addAction(PositionAction*);

    bool executeAction(string, int, int);

private:
    int m_CellX = 0;
    int m_CellY = 0;

    map<string, Component*> m_Components;

    map<string, PositionAction*> m_PositionActions;
    map<string, TargetableActorAction*> m_TargetableActorActions;
};

```

This shows the hierarchy of the action class:

```
class Action
{
public:
    Action();
    ~Action();

    virtual string getID() = 0; /* used to identify the action in the map */
};

class PositionAction : public Action
{
public:
    PositionAction();
    ~PositionAction();

    virtual bool execute(int, int) = 0;
};

class MoveAction : public PositionAction
{
public:
    MoveAction(MoveComponent&);
    ~MoveAction();

    bool execute(int, int);

    string getID() { return "move"; }

private:
    MoveComponent& m_MoveComponent;
};

```

And this is what the move action does:

```
MoveAction::MoveAction(MoveComponent& moveComponent) : m_MoveComponent(moveComponent)
{
}

MoveAction::~MoveAction()
{
}

bool MoveAction::execute(int dX, int dY)
{
    /* will check whether some conditions hold */

    /* move the actor, returns false if failed */
    bool sucess = m_MoveComponent.move(dX, dY);

    return sucess;
}

```

This creates the player actor with a move component and the move action.

```
Actor* player = new Actor();

MoveComponent* moveComponent = new MoveComponent(scene);

player->addComponent(moveComponent);
player->addAction(new MoveAction(*moveComponent));

return player;

```

And you can execute an action like this:

```
actor.executeAction("move", 1, 0);

```

# Answer
It sounds like what you want is named **delegates**. If I understand it correctly, your actions are just a call to a function in an existing component. Then all you need is to store a member function pointer and a pointer to the component, instead of a custom class.

You can do this directly with member function pointers, or wrap it in a delegate class. It would look something like this:

```
class Actor
{
    // ... same as before
    typedef delegate<bool(int,int)> Action;
    void addAction(const string& actionName, Action action);
    bool executeAction(const string& actionName, int arg1, int arg2);
private:
    map<string, Action> m_Actions;
};

Actor* player = new Actor();
player->addAction("move", Actor::Action(moveComponent, &MoveComponent::move));

```

The trick is to build a templatized delegate class that will handle any component and, as long as your signature stays the same (return a bool, take two ints) then you can abstract all the actions easily.

If you need to take multiple components, then you'll have to fall back to your original method, especially if you want to bind the components in advance. If not, then you can have the action perform the lookup, if it's quick enough, and implement actions as free functions:

```
class Actor
{
    // ... same as before
    typedef delegate<bool(Actor,int,int)> Action;
};

bool MoveAction(Actor* actor, int dX, int dY)
{
    MoveComponent* moveComponent = actor.getComponent("move");
    if (moveComponent) return moveComponent->move(dX, dY);
    return false;
}

Actor* player = new Actor();
player->addAction("move", Actor::Action(MoveAction));

```

There are many resources for how to implement a delegate class like that. This is a great starting point, maybe simpler than this implementation which works well and is broadly used. There may be better ways to do this in C++11.

Roughly speaking, you use templates to bind the member function or free function pointer to an automatically generated function that knows how to call it.
> 0 votes

# Answer
There isn't necessarily a reason to have all these *action* classes you are defining but instead have a component that represents specific state about a certain use case. So your movement component has a series of booleans that indicate forward, backward, left, right, etc.

Now each game tick, you have system that inspects all movement components and sees what their current state is and calculates a velocity and direction and passes that to physics for simulation.

In the case of players, your PlayerController interprets keyboard/mouse operations and sets state on the movement component. Similarly your AIController interprets behavior tree results for AI and sets appropriate state on the movement component. From this point, they both follow the same path of execution through the movement system which interacts with physics.
> 0 votes

---
Tags: c++, architecture, ai, input, component-based
---


# Question
Title: How to change the position of a circle in pygame in three stages
I will try to explain it as well as I can excuse me if I'll fail. I have the following simple game situation:

I know the coordinates of each point. So each of the green points try to hit the blue one. I know the target of each green point. What I would like is to acquire a nice movement effect so that lets say each green point will change the coordinates in 3 steps before getting to the target. For example: if a point would be at (2,2) and the target is at (8,9) it would change to (3,3), then (6,7) then (8,9). The idea is how to aceive this? Is there some math involved with sin and cos? I don't know if choosing a random number for example between (2,8) and (2,9) for the new x and y coordinates will do it. I don't know if so it follows the correct direction of the point towards the target. I use pygame, but if you don't know pygame but can help me with how to aceive this effect is cool. Thanks a lot!

# Answer
> 1 votes
I don't think you need sin/cos. This is simple vector math. A vector is calculated by subtracting a point from another, as in target minus the source.

In your case, the vector from (2,2) to (8,9) would be (8-2,9-2) = (6,7). Now you can always recover the target by adding the vector to the source (6,7)+(2,2)=(8,9).

If what you want is to have 3 steps, just divide the vector by 3 and add that to the source. After you add it three times you'll be at the target, and you'll stay in the line that connects source and target. In your example, each step would be (2,2.33) and your intermediate points would be (4,4.33) and (6,6.66).

More generally, you can "normalize" the vector, by calculating the length and dividing by it. The length of a vector is:

```
length = sqrt(v.x*v.x + v.y*v.y)
normal.x = v.x / length
normal.y = v.y / length

```

Interestingly, this also gives you the distance between source and target. Once you have a normal vector, you can use it to move as much or as little as you want while staying in the line that connects source and target. Just multiply it by that amount and add it to the source.

If you think about it, multiplying by the distance will actually give you the target back. Multiplying by a third of the distance will have the same effect as dividing the vector by three, as we did before.

---
Tags: python, pygame, coordinates
---


# Question
Title: Box2D object wont move until tons of force is used
Im making a game for android im using LibGDX and Jbox2D it is a space flying exploration game controlled with the accelerometer. so I have set the world to no have no gravity. the objects in Box2D don't like having forces applied to them apparently. Just to get an object moving more then a few pixels at a time I need to use over 10,000 in applyForceToCenter()

in the Game class I get the accelerometer in the update method and create a direction vector from the input and pass that to the player

```
    accelX = Gdx.input.getAccelerometerX();//get the various tilts
    accelY = Gdx.input.getAccelerometerY();
    accelZ = Gdx.input.getAccelerometerZ();

    //These are backwards because the game is in landscape and not portrait
    p1Direction.x = (accelY/10); //getAccelerometer comes back -10 to 10
    p1Direction.y = -(accelX/10); //reduce this to -1 to 1;

    p1.setDirection(p1Move);
    p1.update(Gdx.graphics.getDeltaTime());

```

Then In the player I apply a force to the object based on the direction:

```
    acceleration.x += (directionVector.x * SPEED)*deltaTime; //speed is set to 200
    acceleration.y += (directionVector.y * SPEED)*deltaTime;

    this.getBody().applyForceToCenter(acceleratiom, true);

```

to try and get it moving I had to add:

```
    acceleration.x += (directionVector.x * SPEED)*deltaTime*1000; //speed is set to 200
    acceleration.y += (directionVector.y * SPEED)*deltaTime*1000;

    this.getBody().applyForceToCenter(acceleratiom, true);

```

now it moves a little better, but once it gets moving it won't stop

Is there a way to fix this?

Update: The Mass, Friction, density, and restitution are all 1 right now here's the camera:

```
    camera = new OrthographicCamera(screenWidth,screenHeight);
    camera.setToOrtho(false,screenWidth,screenHeight);
    camera.position.set(0, 0, 0);

```

and the player is rendered with

```
batch.draw(playerTexture, this.getBody().getPosition().x, this.getBody().getPosition().y,
    (playerTexture.getWidth()/2), (playerTexture.getHeight()/2),
    playerTexture.getWidth(), playerTexture.getHeight(),
    1.0f, 1.0f, this.getBody().getAngle(), 0, 0,
    playerTexture.getWidth(),  playerTexture.getHeight(),
false, false);
//Texture position half width(so the texture rotates in the center), width and height of the texture, scale of 1, rotate by the angle (doesn't rotate right now) source position source width and height

```

# Answer
LET THIS BE A CAUTIONARY TALE ABOUT BOX2D! Haha! Here's the solution I came up with

The problem I amrunning into is due to the fact that Box2D uses meters instead of pixels for the scale, in my game a screen that is 1920x1080 would be 1920 meters wide and if I am using sprites a small sprite will be only as many meters wide as it is in pixels.

The reason it needs so much force is because the object is not moving in relationship to the screen well a velocity of 1 would only move it 1 pixel per step assuming Box2D iterates 1 time per "step"

to compensate for this you need to scale up the game world and then apply a pixels to meter ratio. for example:

```
//using this will get you the current screen resolutions
int screenWidth = Gdx.graphics.getWidth();
int screenHeight = Gdx.graphics.getHeight();

//Now set a Pixels to Meters ratio
final int PTM_RATIO = 48; //A 48 pixel wide image will be 1 meter wide

//Now set your orthographic camera to the number of meters that the current screen fits
// this way the screen will only be 4-10 meters wide
camera = new OrthographicCamera(screenWidth/PTM_RATIO,screenHeight/PTM_RATIO);
camera.position.set(0, 0, 0)
camer.update();

//Now when rendering you want to make sure that you are telling the game to use the
//PTM_RATIO When doing anything PIXEL related:

 batch.draw(playerTexture,
            //Body is in meters
            this.getBody().getPosition().x, this.getBody().getPosition().y,
            //This is the position of the image from the position above
            //You divide by PTM_RATIO to get the correct meter position
            (playerTexture.getWidth()/2)/PTM_RATIO,
            (playerTexture.getHeight()/2)/PTM_RATIO,
            //Again multiply the texture width in pixels by PTM_RATIO
            (playerTexture.getWidth()/PTM_RATIO),(playerTexture.getHeight()/PTM_RATIO),
            //Scale and angle are not in pixels
            1.0f, 1.0f, this.getBody().getAngle(), 0, 0,
            //EXCEPTION: this is asking for the width and height of the lower right
            //corner of the sprite, setting this to the PTM_Ratio will yield 1
            //Which would get you only the first pixel(not what we want)
            playerTexture.getWidth(),  playerTexture.getHeight(),
            false, false);

```

Overall this should fix the problem I you are running into. tweaking the scale of the projection will allow you to zoom in and out without moving the positions or scaling of any of the objects in LibGDX with the OrthographicCamera this can be done with:

```
camera.setToOrho(false, (screenWidth/PTM_RATIO)*scale,(screenHeight/PTM_RATIO)*scale);

```

Hope this helps anyone who also runs into a similar issue! It always happens! I somehow talking about it helps me figure it out!(don't you hate when that happens?)

**Final note, your object don't need to be in "meters" consider them "units" in my case its a space game and I am calling it 1 "Ship Length" because my ships are not 1 meter wide but it gives me a sense of scale things smaller then a ship are less then 1 larger then a ship is bigger (planets are like 10-20 Ship lengths for example)**
> 2 votes

---
Tags: java, libgdx, box2d
---