# Question
Title: Converting a 2D curve into points for data storage
I’ve created an algorithm which converts any curve i.e. path into minimum number of points so that I can save it into a file or database.

The method is simple: it moves three points in equal steps and measures the angle between the lines these points form. If the angle is bigger than the tolerance then it creates a new cubic curve to that point. Then it moves the lines forward and measures the angle again…

For those who know Android **Path** Class - Note that the **dstPath** is a custom class, which records the points into an Array so I can save the points later, while the **srcPath** is the result of a Regions union and therefore has no key points for me to save.

The problem is that the circle does not look smooth as you can see in this image, produced by the code below, where the source path consists of a perfect circle and rectangle. I tried to change angle of tolerance and the steps length, but nothing helps. I wonder if you can suggest any improvement to this algorithm, or a different approach.

EDIT: I have now posted the entire code for those who use Android java, so they can easily try and experiment.

```
public class CurveSavePointsActivity extends Activity{

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(new CurveView(this));
    }

    class CurveView extends View{

        Path srcPath, dstPath;
        Paint srcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Paint dstPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        public CurveView(Context context) {
            super(context);

            srcPaint.setColor(Color.BLACK);
            srcPaint.setStyle(Style.STROKE);
            srcPaint.setStrokeWidth(2);
            srcPaint.setTextSize(20);

            dstPaint.setColor(Color.BLUE);
            dstPaint.setStyle(Style.STROKE);
            dstPaint.setStrokeWidth(2);
            dstPaint.setTextSize(20);

            srcPath = new Path();
            dstPath = new Path();

        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);

            //make a circle path
            srcPath.addCircle(w/4, h/2, w/6 - 30, Direction.CW);

            //make a rectangle path
            Path rectPath = new Path();
            rectPath.addRect(new RectF(w/4, h/2 - w/16, w*0.5f, h/2 + w/16), Direction.CW);

            //create a path union of circle and rectangle paths
            RectF bounds = new RectF();
            srcPath.computeBounds(bounds, true);
            Region destReg = new Region();
            Region clip = new Region();
            clip.set(new Rect(0,0, w, h));
            destReg.setPath(srcPath, clip);
            Region srcReg = new Region();
            srcReg.setPath(rectPath, clip);
            Region resultReg = new Region();
            resultReg.op(destReg, srcReg, Region.Op.UNION);
            if(!resultReg.isEmpty()){
                srcPath.reset();
                srcPath.addPath(resultReg.getBoundaryPath());
            }

            //extract a new path from the region boundary path
            extractOutlinePath();

            //shift the resulting path bottom left, so they can be compared
            Matrix matrix = new Matrix();
            matrix.postTranslate(10, 30);
            dstPath.transform(matrix);

        }

         @Override
            public void onDraw(Canvas canvas) {
                super.onDraw(canvas);
                canvas.drawColor(Color.WHITE);
                canvas.drawPath(srcPath, srcPaint);
                canvas.drawPath(dstPath, dstPaint);

                canvas.drawText("Source path", 40, 50, srcPaint);
                canvas.drawText("Destination path", 40, 100, dstPaint);
         }

         public void extractOutlinePath() {

             PathMeasure pm = new PathMeasure(srcPath, false); //get access to curve points

             float p0[] = {0f, 0f}; //current position of the new polygon
             float p1[] = {0f, 0f}; //beginning of the first line
             float p2[] = {0f, 0f}; //end of the first & the beginning of the second line
             float p3[] = {0f, 0f}; //end of the second line

             float pxStep = 5; //sampling step for extracting points
             float pxPlace  = 0; //current place on the curve for taking x,y coordinates
             float angleT = 5; //angle of tolerance

             double a1 = 0; //angle of the first line
             double a2 = 0; //angle of the second line

             pm.getPosTan(0, p0, null); //get the beginning x,y of the original curve into p0
             dstPath.moveTo(p0[0], p0[1]); //start new path from the beginning of the curve
             p1 = p0.clone(); //set start of the first line

             pm.getPosTan(pxStep, p2, null); //set end of the first line & the beginning of the second

             pxPlace = pxStep * 2;
             pm.getPosTan(pxPlace, p3, null); //set end of the second line

             while(pxPlace < pm.getLength()){
             a1 = 180 - Math.toDegrees(Math.atan2(p1[1] - p2[1], p1[0] - p2[0])); //angle of the first line
             a2 = 180 - Math.toDegrees(Math.atan2(p2[1] - p3[1], p2[0] - p3[0])); //angle of the second line

             //check the angle between the lines
             if (Math.abs(a1-a2) > angleT){

               //draw a straight line to the first point if the current p0 is not already there
               if(p0[0] != p1[0] && p0[1] != p1[1]) dstPath.quadTo((p0[0] + p1[0])/2, (p0[1] + p1[1])/2, p1[0], p1[1]);

               dstPath.quadTo(p2[0] , p2[1], p3[0], p3[1]); //create a curve to the third point through the second

               //shift the three points by two steps forward
               p0 = p3.clone();
               p1 = p3.clone();
               pxPlace += pxStep;
               pm.getPosTan(pxPlace, p2, null);
               pxPlace += pxStep;
               pm.getPosTan(pxPlace, p3, null);
               if (pxPlace > pm.getLength()) break;
             }else{
               //shift three points by one step towards the end of the curve
               p1 = p2.clone();
               p2 = p3.clone();
               pxPlace += pxStep;
               pm.getPosTan(pxPlace, p3, null);
             }
             }
             dstPath.close();
         }
    }

}

```

Here's a comparison between the original and what my algorithm produces:

# Answer
> 6 votes
I think you have two problems:

# Non-symmetric control points

Initially you start with equal distances between p0 to p1 and p1 to p2. If the tolerance angle between the line segments is not met, you move p1 and p2 forward, but keep p0 where it was. This increases the distance between p0 to p1 while keeping the distance between p1 to p2 the same. When you create a curve using p1 as the control points, it can be heavily biased towards p2 depending on how many iterations have passed since the last curve. If you would move p2 twice the amount than p1, you would get even distances between the points.

# Quadratic curves

As mentioned in other answers as well, quadratic curve is not very good for this case. Adjacent curves you create should share a **control point and a tangent**. When your input data is just points, Catmull-Rom Spline is a good choice for that purpose. It's a cubic Hermite curve, where the tangents for the control points are calculated from previous and next points.

The Path API in Android supports Bézier curves, which are a little different than Hermite curves regarding parameters. Fortunately Hermite curves can be converted to Bézier curves. Here is the first example code I found when Googling. This Stackoverflow answer also seems to give the formula.

You also mentioned the problem of sharp edges. With the input data you have, it's impossible to detect if there is an actual sharp corner or just a very steep curve. If this becomes a problem, you can make the iteration more adaptive by increasing / decreasing the step on-the-fly as needed.

**Edit:** After further thinking quadratic curves could be used after all. Instead of drawing a quadratic curve from p0 to p2 using p1 as the control point, draw it from p0 to p1 using a new point p0\_1 as the control points. See the picture below.

If p0\_1 is in the intersection of the tangents in p0 and p1, the result should be smooth. Even better, since `PathMeasure.getPosTan()` returns also tangent as the third parameter, you can use actual accurate tangents instead of approximations from adjacent points. With this approach you need less changes to your existing solution.

Based on this answer, the intersection point can be calculated with the following formula:

```
getPosTan(pxPlace0, p0, t0); // Also get the tangent
getPosTan(pxPlace1, p1, t1);
t1 = -t1; // Reverse direction of second tangent
vec2 d = p1 - p0;
float det = t1.x * t0.y - t1.y * t0.x;
float u = (d.y * t1.x - d.x * t1.y) / det;
float v = (d.y * t0.x - d.x * t0.y) / det; // Not needed ... yet
p0_1 = p0 + u * t0;

```

This solution however works only if both u and v are non-negative. See the second picture:

Here the rays don't intersect although the lines would, since u is negative. In this case it's not possible to draw a quadratic curve that would smoothly connect to the previous one. Here you need the bézier curves. You can calculate the control points for it either with the method given earlier in this answer or derive them directly from the tangents. Projecting p0 to the tangent ray p0+u\*t0 and vise versa for the other ray gives both of the control points c0 and c1. You can also adjust the curve by using any point between p0 and c0 instead of c0 as long as it lies on the tangent ray.

**Edit2:** If your drawing position is in p1, you can calculate the bezier control points to p2 with the following pseudo code:

```
vec2 p0, p1, p2, p3; // These are calculated with PathMeasure
vec2 cp1 = p1 + (p2 - p0) / 6;
vec2 cp2 = p2 - (p3 - p1) / 6;

```

With these you can append a path from p1 to p2:

```
path.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, p2.x, p2.y);

```

Replace the vector operations with per component operations on float\[\] arrays to match your code. You start by initializing `p1 = start;` and p2 and p3 are the next points. p0 is initially undefined. For the first segment where you don't have p0 yet, you can use a quadratic curve from p1 to p2 with cp2 as the control point. The same for the end of the path where you don't have p3, you can draw a quadratic curve from p1 to p2 with cp1 as the control point. Alternatively you can initialize p0=p1 for the first segment and p3=p2 for the last segment. After every segment you shift the values `p0 = p1; p1 = p2; and p2 = p3;` when moving forward.

When you are saving the path, you just save all points p0 ... pN. No need to save the control points cp1 and cp2, as they can be calculated as needed.

**Edit3:** As it seems to be hard to get good input values for the curve generation, I propose another approach: Use serialization. Android Path doesn't seem to support it, but fortunately Region class does. See this answer for the code. This should give you the exact result. It might take some space in the serialized form if it's not optimized, but in that case it should compress very well. Compression is easy in Android Java using GZIPOutputStream.

# Answer
> 13 votes
# What would the W3C do?

The internet has had this problem. The World Wide Web Consortium noticed. It has a **recommended standard solution** since 1999: Scalable Vector Graphics (SVG). It's an XML-based file format specifically designed for storing 2D shapes.

# "*Scalable-what?*"

**Scalable Vector Graphics**!

* **Scalable**: It's meant to scale smoothly to any size.
* **Vector**: It's based on the mathematical notion of vectors.
* **Graphics**. It's meant to make pictures.

Here's the technical specification for SVG version 1.1.
<sup>(Don't be scared by the name; It's actually pleasant to read.)</sup>

They've written down exactly how basic shapes like circles or rectangles are to be stored. For example, rectangles have these properties: `x`, `y`, `width`, `height`, `rx`, `ry`. (The `rx` and `ry` can be used for rounded corners.)

Here's their example rectangle in SVG: (Well, two really -- one for the canvas outline.)

```
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="12cm" height="4cm" viewBox="0 0 1200 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example rect01 - rectangle with sharp corners</desc>

  <!-- Show outline of canvas using 'rect' element -->
  <rect x="1" y="1" width="1198" height="398"
        fill="none" stroke="blue" stroke-width="2"/>

  <rect x="400" y="100" width="400" height="200"
        fill="yellow" stroke="navy" stroke-width="10"  />
</svg>

```

Here's what it represents:

As the specification says, you're free to leave out some of the properties if you don't need them. (For example, `rx` and `ry` attributes weren't used here.) Yes, there's a ton of cruft at the top about `DOCTYPE` which you won't need just for your game. They're are optional too.

# Paths

SVG paths are "paths" in the sense that if you *put a pencil to a paper, move it around and eventually raise it again*, you have a path. They don't *have* to be *closed*, but they might be.

Each path has a `d` attribute (I like to think it stands for "draw"), containing path data, a sequence of **commands** for basically just *putting a pen to a paper and moving it around*.

They give the example of a triangle:

```
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="4cm" height="4cm" viewBox="0 0 400 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <title>Example triangle01- simple example of a 'path'</title>
  <desc>A path that draws a triangle</desc>
  <rect x="1" y="1" width="398" height="398"
        fill="none" stroke="blue" />
  <path d="M 100 100 L 300 100 L 200 300 z"
        fill="red" stroke="blue" stroke-width="3" />
</svg>

```

See the `d` attribute in the `path`?

```
d="M 100 100 L 300 100 L 200 300 z"

```

The `M` is a **command** for *Move to* (followed by coordinates), the `L`s are for *Line to* (with coordinates) and `z` is a command to close the path (i.e. draw a line back to the first location; that doesn't need coordinates).

Straight lines are boring? Use the cubic or quadratic Bézier commands!

The theory behind Bézier curves is covered well elsewhere (such as on Wikipedia), but here's the executive summary: Béziers have a start and end point, with possibly many control points that influence where the curve in between is going.

The specification also gives instructions for converting most basic shapes into paths in case you want to.

# Why and when to use SVG

Decide carefully if you want to go down this path (pun intended), because it's really quite complicated to represent any arbitrary 2D shape in text! You can make your life so much easier if you e.g. limit yourself to just paths made of (potentially really many) straight lines.

But if you do decide you want arbitrary shapes, SVG is the way to go: It has great tool support: You can find many libraries for XML parsing at the low level and SVG editor tools at the high level.

Regardless, the SVG standard sets a good example.

# Answer
> 4 votes
Your code contains a misleading comment:

```
dstPath.quadTo(p2[0] , p2[1], p3[0], p3[1]); //create a curve to the third point through the second

```

A quadratic bezier curve does *not* go *through* the second point. If you want to go through the second point you need a different type of curve, such as a hermite curve. You may be able to convert the hermite curves into beziers so that you can use the Path class.

Another suggestion is instead of sampling the points, use the mean of the points you're skipping over.

Another suggestion is instead of using an angle as a threshold, use the difference between the actual curve and the approximate curve. Angles aren't the real problem; the real problem is when the set of points doesn't fit a bezier curve.

Another suggestion is to use cubic beziers, with the tangent of one matching the tangent of the next. Otherwise (with quadratics) I think your curves won't match up smoothly.

# Answer
> 4 votes
To get a smoother intersection of two paths, you could scale them up before intersection and scale them down after.

I don't know if it's a good solution, but it worked well for me. It's also fast. In my example, I intersect a rounded path with a pattern I created (stripes). It looks good even when scaled.

Here my code:

```
    Path mypath=new Path(<desiredpath to fill with a pattern>);
    String sPatternType=cpath.getsPattern();

    Path pathtempforbounds=new Path(cpath.getPath());
    RectF rectF = new RectF();
     if (sPatternType.equals("1")){
         turnPath(pathtempforbounds, -45);
     }
     pathtempforbounds.computeBounds(rectF, true);

     float ftop=rectF.top;
     float fbottom=rectF.bottom;
     float fleft=rectF.left;
     float fright=rectF.right;
     float xlength=fright-fleft;

     Path pathpattern=new Path();

     float ypos=ftop;
     float xpos=fleft;

     float fStreifenbreite=4f;

     while(ypos<fbottom){
         pathpattern.moveTo(xpos,ypos);
         xpos=xpos+xlength;
         pathpattern.lineTo(xpos, ypos);
         ypos=ypos+fStreifenbreite;
         pathpattern.lineTo(xpos, ypos);
         xpos=xpos-xlength;
         pathpattern.lineTo(xpos, ypos);
         ypos=ypos-fStreifenbreite;
         pathpattern.lineTo(xpos, ypos);
         pathpattern.close();
         ypos=ypos+2*fStreifenbreite;

     }

     // Original vergrössern

     scalepath(pathpattern,10);
     scalepath(mypath,10);

     if (sPatternType.equals("1")){
         Matrix mdrehen=new Matrix();
         RectF bounds=new RectF();
         pathpattern.computeBounds(bounds, true);
         mdrehen.postRotate(45, (bounds.right + bounds.left)/2,(bounds.bottom + bounds.top)/2);
         pathpattern.transform(mdrehen);
     }

     RectF rectF2 = new RectF();
     mypath.computeBounds(rectF2, true);

     Region clip = new Region();
     clip.set((int)(rectF2.left-100f),(int)(rectF2.top -100f), (int)(rectF2.right+100f),(int)( rectF2.bottom+100f));
     Region region1 = new Region();
     region1.setPath(pathpattern, clip);

     Region region2 = new Region();
     region2.setPath(mypath, clip);

     region1.op(region2, Region.Op.INTERSECT);

     Path pnew=region1.getBoundaryPath();

     scalepath(pnew, 0.1f);
     cpath.setPathpattern(pnew);

public void turnPath(Path p,int idegree){
     Matrix mdrehen=new Matrix();
     RectF bounds=new RectF();
     p.computeBounds(bounds, true);
     mdrehen.postRotate(idegree, (bounds.right + bounds.left)/2,(bounds.bottom + bounds.top)/2);
     p.transform(mdrehen);
}

public void scalepath(Path p,float fscale){
     Matrix mverkleinern=new Matrix();
     mverkleinern.preScale(fscale,fscale);
     p.transform(mverkleinern);
}

```

Looks still smooth when zooming with canvas.scale():

# Answer
> 3 votes
Look at polygon interpolation (http://en.wikipedia.org/wiki/Polynomial\_interpolation)

Basically, you take n equispaced nodes (optimal interpolation is not equispaced, but for your case it should be good enough and easy to implement)

You end up with a polygon of order n which decreases the error between your curve **if** (\<-- big if) your line is **smooth** enough.

In your case, you're doing **linear** (order 1) interpolation.

The other case (as *GriffinHeart* recommended) was to use Splines (http://en.wikipedia.org/wiki/Spline\_interpolation)

Either case would give you some form of polynomial **fit** for your curve.

# Answer
> 2 votes
If the point of the conversion is for storage only, and when you render it back on the screen you need it to be smooth, then the highest fidelity storage you can get, while still minimizing the total storage required to persist a given curve might be to actually store the attributes of the circle (or an arc, rather) and re-draw it on demand.

Origin. Radius. Start/stop angles for drawing the arc.

If you need to convert the circle/arc into points anyway for rendering, then you can possibly to that upon loading it from storage, while always storing just the attributes.

# Answer
> 2 votes
Is there a reason for going for curves as opposed to straight lines? Straight lines are simpler to work with, and can be rendered efficiently in hardware.

The other approach worth considering is to store a couple of bits per pixel, stating if it's inside, outside or on the outline of the shape. This should compress well, and might be more efficient than lines for complex selections.

You might also find these articles interesting / useful:

# Answer
> 1 votes
Take a look at curve interpolation - there's a few different types you can implement that will help smooth your curve. The more points you can get on that circle, the better. Storage is pretty cheap - so if extracting 360 close nodes is cheap enough (even at 8 bytes for position; 360 nodes is hardly expensive to store).

You can place with some interpolation samples here with only four points; and the results are quite good (my favourite is the Bezier for this case, although others might chime in about other effective solutions).

You can play around in here, too.

---
Tags: java, android, mathematics, curves, serialization
---


title: XNA Games running on Windows 8

text:
# Question
Title: XNA Games running on Windows 8
Will Games developed on XNA work under a Windows 8 environment?

I know the XNA project was killed off, and you can't develop it on Windows 8 (apparently), but will they still work under windows 8? I don't care about metro integration or whatever, even if they run in desktop mode that's fine.

I've been looking around and finding a bunch of contradictory answers - so maybe I can get a clear one from here.

# Answer
> 4 votes
Yes, the applications you write for XNA will still run on the desktop mode but not metro mode. If you care about Metro integration, check out MonoGame. I develop normal XNA and MonoGame applications on Windows 8 and run them here as well; I can assure you they both function perfect on desktop mode.

---
Tags: xna, windows, windows-8
---


title: When do I use VBO?

text:
# Question
Title: When do I use VBO?
My drawing code currently draws by calling **glVertex3f(x, y, z)** for each of my object's vertexes, and I've been suggested to use VBO as it'd enhance the performance of my drawing code.

After checking how VBOs works, it seems I need to pass a **float array** of the vertexes I'm going to draw, and this is a problem.

My object class looks like this:

```
class Vertex
{
    public:
        float positionX, positionY, positionZ;
        //more stuff
}
class Object3D
{
    public:
        //bunch of stuff
    private:
        Vertex* vertexes;
}

```

So when I create and load a new **Object3D**, I have an array of **Vertex** with the positions. If I were to pass a float array, I would need to:

```
void Graphics::Draw(Object3D* object)
{
    float* vertexArray = new float[object->totalVertexes];

    //fill vertexArray, send it to the card

    delete[] vertexArray;
}

```

Do I need to do this every frame, or just once (and I just call **glDrawArrays()** after it's loaded)?

Do I use VBOs on models that will be constantly changing, such as a character, or just for static objects? (If I were to use, I'd have to call the above code every frame, wouldn't it be a bad idea?)

Also, should I separate VBOs by objects, or just group them up by what's changing or not? (For example, I create 1 VBO ID that holds all my terrain and non-animated objects, or should I create 1 VBO ID for each object on my screen?)

# Answer
Functions such as **glVertex** are marked as *deprecated* in modern OpenGL and don't even exist in OpenGL ES, so indeed VBOs are preferred way of drawing static and dynamic objects.

If the data is not changing you don't need to send it to the GPU every frame - instead you do that once (e.g. at the beginning of the level) and when the time comes bind the right VBO and call the draw function.

If the model is being translated/rotated/scaled it usually makes more sense to pass a model transform matrix to to the shader and translate all the vertices there (and not to change the VBO every frame). If the model is really being transformed (the distances of vertices are being changed, new vertices are added...) and you can't/don't want to do that with a geometry shader, then update the VBO. Usually you don't want to update the whole VBO, so use functions **glBufferSubData** and **glMapBuffer** which can be more efficient.

I think you can group some static data together (terrain and different assets on it) but when doing so think about *loading the data*. If there's a lot of terrain, then pushing all the data on your GPU isn't the best idea.
> 2 votes

---
Tags: c++, opengl, vbo
---


# Question
Title: How do I create a camera for a strategy game?
How do I make a camera for a strategy game? Think something in the style of Warcraft 3, so you can lower the camera angel and view the world in a somewhat 3D format. Do I need to have some coordinate system where you put every single unit, building, etc., in it and then use an algorithm for the camera to render everything between certain coordinates?

Edit: To clearify the question abit more. How do you render the graphics for a strategy game when the map of the game is bigger then what the players camera view is?

# Answer
Having discussed it with you, I believe your question is simply "How do I implement a 3D camera in directX?" The principles are the same regardless of the genre of the game (i.e., the "strategy game" detail is not relevant). And the example video we looked at together is just 3D, not "somewhat 3D".1

In any event, how to implement a camera is something that comes up quite a bit. This answer from Josh Petrie is pretty good and has some handy tutorial links:

> There are several ways of going about this (see tutorials here, here and here for example, with plenty more available on the Internet via Google). The technology used in the resources you may find online may vary slightly (in terms of D3D, XNA, OpenGL, et cetera), but the underlying principles are going to be the same:
>
> * your camera object maintains its position and its direction, and optionally another pair of vectors that, alongside the direction, form an orthogonal basis for the camera's coordinate system.
> * your camera's public API exposes methods for yawing, pitching, and optionally rolling the camera around it's basis vectors -- the act of adjusting the camera orientation will update the basis vectors for subsequent use.
>
> You can elect to store the vectors directly, or recompute the underlying view matrix every time, as you need and prefer. There's a lot of flexibility to the technique, so if you need help beyond those general steps you may want to post a new question with a more specific query.

1It may be that you're thinking of that video (at 3:50) as not truly 3D because the game does not give the player control over the camera.
> 1 votes

---
Tags: c++, directx, camera, strategy
---


# Question
Title: What is better for the overall performance and feel of the game: one setInterval performing all the work, or many of them doing individual tasks?
This question is, I suppose, not limited to Javascript, but it is the language I use to create my game, so I'll use it as an example.

For now, I have structured my HTML5 game like this:

```
var fps = 60;
var game = new Game();

setInterval(game.update, 1000/fps);

```

And `game.update` looks like this:

```
this.update = function()
{
    this.parseInput();
    this.logic();
    this.physics();
    this.draw();
}

```

This seems a bit inefficient, maybe I don't need to do all of those things at once. An obvious alternative would be to have more intervals performing individual tasks, but is it worth it?

```
var fps = 60;
var game = new Game();

setInterval(game.draw, 1000/fps);
setInterval(game.physics, 1000/a); //where "a" is some constant, performing the same function as "fps"
...

```

With which approach should I go and why? Is there a better alternative? Also, in case the second approach is the best, how frequently should I perform the tasks?

# Answer
> 5 votes
A single task is definitely better.

You don't want nondeterministic behaviour.

While Javascript normally runs all your code in one thread and won't interrupt it (it will not preempt other JS code), there's no guarantee of how often, or in what order or proportion, several timers will really run. If one timer event is a bit slow, others might get skipped.

In general, you probably want to be using requestAnimationFrame for rendering, and doing your game logic however often suits you.

I use a fixed timestep with interpolation, because that way I get deterministic behaviour. I trigger it all from requestAnimationFrame, and look at the clock to see if enough time has passed to run another game-logic "tick".

# Answer
> 0 votes
Dunno why but i can't add a comment so i had to use an answer \>.\>

For my game, I ditched set interval for request animation frame, If the user minimizes the browser the game will not continue running and so frees up your CPU which is why i preferred that particular method.

# Answer
> 0 votes
requestAnimationFrame is not your (logic's) friend recommends:

```
function render() {
    // Update the DOM, or Canvas, or anything else graphics-related
    requestAnimationFrame( render );
}

function gameStep() {
    // Update the player's location, health, or anything else logic-related
    // Process the game logic at a target 60 FPS.
    setTimeout( gameStep, 1000 / 60 );
}

```

Author says his physics plugin got better FPS after switching to this technique.

---
Tags: javascript, html5, performance
---


title: Cut a translucent square in a texture

text:
# Question
Title: Cut a translucent square in a texture
How to remove (cut-out) a transparent rectangle in a Texture, so that the hole will be translucent.

On Android I would use the Xfermodes approach:

https://stackoverflow.com/questions/8115732/how-to-use-masks-in-android

But in libgdx I will have to use opengl. So far I almost achieved what I was looking for, by using the the glBlendFunc From this nice and very helpful page I learend that

```
glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);

```

should solve my problem, but I tried it out, and it did not quite work as expected:

```
batch.end();
batch.begin();

batch.setBlendFunction(GL20.GL_ZERO,
        GL20.GL_ONE_MINUS_SRC_ALPHA);
// Draw the background
super.draw(batch, x, y, width, height);
// draw the foreground
mask.draw(batch, x + innerButtonTable.getX(), y
        + innerButtonTable.getY(), innerButtonTable.getWidth(),
        innerButtonTable.getHeight());
// result = {foreground}*{0,0,0,0} +
// {background}*(1-sourceAlpha)

batch.end();
batch.setBlendFunction(GL20.GL_SRC_ALPHA,
        GL20.GL_ONE_MINUS_SRC_ALPHA);
batch.begin();

```

It is just making the mask area plain black, whereas I was expecting transparency, any ideas.

This is what I get:

This is what I expected:

# Answer
> 4 votes
I solved my problem by using the stencil buffer:

```
Gdx.gl.glClear(GL_STENCIL_BUFFER_BIT);
batch.end();
//disable color mask
Gdx.gl.glColorMask(false, false, false, false);
Gdx.gl.glDepthMask(false);
//enable the stencil
Gdx.gl.glEnable(GL20.GL_STENCIL_TEST);
Gdx.gl.glStencilFunc(GL20.GL_ALWAYS, 0x1, 0xffffffff);
Gdx.gl.glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

batch.begin();
//draw the mask
mask.draw(batch, x + innerButtonTable.getX(), y
        + innerButtonTable.getY(), innerButtonTable.getWidth(),
        innerButtonTable.getHeight());

batch.end();
batch.begin();

//enable color mask
Gdx.gl.glColorMask(true, true, true, true);
Gdx.gl.glDepthMask(true);
//just draw where outside of the mask
Gdx.gl.glStencilFunc(GL_NOTEQUAL, 0x1, 0xffffffff);
Gdx.gl.glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
//draw the destination texture
super.draw(batch, x, y, width, height);
batch.end();
//disable the stencil
Gdx.gl.glDisable(GL20.GL_STENCIL_TEST);

```

---
Tags: opengl, java, libgdx, opengl-es2
---


# Question
Title: Moving the camera as in a first person shooter
I am trying to implement the movement of the camera with the mouse. The result I want to achieve is the same that you get when you move your aim in a first person shooter.

Here is the code I wrote, where "camera" is the vector which contains the location of the camera, "center" is the vector which contains the location of the point to which the camera is pointing at, and "move\_vector" is simply "center" minus "camera"

```
    if(mouse_move_x != 0 || mouse_move_y != 0){

        float a0 = Array_norm<float>(move_vector,3);
        Array_copy<float>(move_vector,move_vector2,3);

        //perform mouse horizontal axis movement
        current_x_angle = atan2(move_vector[2],move_vector[0]);
        current_x_angle = current_x_angle + mouse_move_x * input::MOUSE_sensitivity * 0.017;

        move_vector[0] = cos(current_x_angle)*a0;
        move_vector[2] = sin(current_x_angle)*a0;

        //perform mouse vertical axis movement
        temp = sqrt(move_vector2[0]*move_vector2[0]+move_vector2[2]*move_vector2[2]);

        current_y_angle = atan2(move_vector2[1],temp);
        current_y_angle = current_y_angle - mouse_move_y * input::MOUSE_sensitivity * 0.017;

        move_vector2[1] = sin(current_y_angle)*a0;
        if(move_vector2[0]==0){
            move_vector2[2] = (move_vector2[2] >= 0) ? cos(current_y_angle)*a0 : -cos(current_y_angle)*a0;
        }
        else{
            temp2 = move_vector2[2]/move_vector2[0];
            temp = cos(current_y_angle)*a0*sqrt(1/(1+temp2*temp2));
            move_vector2[0] = (move_vector2[0] >= 0) ? temp : -temp;
            move_vector2[2] = move_vector2[0]*temp2;
        }

        //join x and y movements
        Array_sum<float>(move_vector,move_vector2,move_vector,3);
        Array_normalize<float>(move_vector,move_vector,3);

        center[0] = move_vector[0] + camera[0];
        center[1] = move_vector[1] + camera[1];
        center[2] = move_vector[2] + camera[2];

    }

```

Two questions:

* the code works only when I consider only one of the due movements (either horizontal movement or vertical movement). The code does not work when I get both movements combined and I cannot understand why
* Is there a better (and more mathematically compact) approach to compute the new camera position and focus point? I am sure there is :)

Thank you

# Answer
Well I decided to change to a much easier approach.

```
        float radius = Array_norm<float>(move_vector,3);
        current_y_angle = acos(move_vector[1]/radius) + mouse_move_y * input::MOUSE_sensitivity * 0.017;
        current_x_angle = atan2(move_vector[2],move_vector[0]) + mouse_move_x * input::MOUSE_sensitivity * 0.017;

        move_vector[0] = radius*cos(current_x_angle)*sin(current_y_angle);
        move_vector[2] = radius*sin(current_x_angle)*sin(current_y_angle);
        move_vector[1] = radius*cos(current_y_angle);

        center[0] = move_vector[0] + camera[0];
        center[1] = move_vector[1] + camera[1];
        center[2] = move_vector[2] + camera[2];

```

This code works perfectly. It is based on the idea of "Spherical coordinate system". It is perfectly explained in Wikipedia.

I found this one, it does the job and it is pretty much mathematically compact. Any other approach that you think it is worth mentioning?

Thanks
> 1 votes

---
Tags: c++, input, windows, mouse, winapi
---


# Question
Title: Looking to create a game with a small indie team, where to start?
A group of friends and I would like to start developing a small indie game for fun. It's something to do over a period of time as a hobby. We're in school, so it's not like we can go to a college or anything, we'd mainly learn off books. I have some VERY BASIC experience in the field of programming. I've been focusing on C++ for quite some time (about 5 months), and am thinking of building a game around the C++ language. My colleagues have no experience whatsoever, and am wondering what you readers believe would be a good place to start. So, my question would be: What are we expecting to create within the next 2 years? (will we get anywhere?) Should we use C++, or a more basic language such as Java (I don't know much about Java but have read it is simpler than C++). Hope we can get somewhere with this and you don't hammer me too hard for asking probably a dumb question to most of you. -Thanks in advance, Aresous. \- Thank you for your answers. Helped me out quite a bit and answered my questions. Sorry for not making it too straight forward. I had the feeling the question wasn't really for the site, I just wanted to make sure I was getting information from more experience game developers.

# Answer
> 1 votes
I'd suggest using C# in conjunction with XNA, because in my experience, C# is a better programming language to start off with when you're making a game, because its syntax is kind of more straightforward, and it is a lot like Java, so if you ever want to switch from one to another, it's easy enough, somewhat easier than switching from C++. Also there are tons of XNA tutorials out there, for example Microsoft's official tutorial site.

As for the game part, you and your team should create a Game Design Document, which is like a super detailed description of your game. It should cover not only every basic mechanic and rule of your game, but also describe the expected behavior of every game object. Not only it helps to communicate how the game works (any part of it) to your teammates and potential distributors, but it also allows you to keep everything on paper instead of holding the whole concept in your head. And in the end programming language is a way to describe how things work with basic terms, and so is the Design Document — it's very easy to translate it to code after it's written.

If you're really serious about making a game, decide which platform you're targeting, since it may greatly affect the way it looks and is controlled.

---

I guess it doesn't necessarily apply to every beginner indie team out there, but I'd say in two years you may very well have a finished game to show off. Most indie teams these days are created in hopes of releasing an ok product that maybe some bigger studio will notice or think of as a good enough excuse to let them in and teach some more about gamedev.

But more ambitious and talented people end up making a great game that everybody loves and buys, so they earn more than enough money to get by, and you probably have heard of them already.

Take your time to decide if you're going to dedicate the next five years to making great games and becoming a popular game studio, or maybe it's just your hobby that you're not willing to turn into your lifetime career.

# Answer
> 1 votes
Biggest mistake new independent developers make is aiming too high. Start making a really simple game engine, with extendability in mind, and slowly add things to it. Never go too long with an engine that doesn't run, and MAKE LOTS OF REGULAR BACKUPS.

---
Tags: c++
---


title: Switching to a vertex shader

text:
# Question
Title: Switching to a vertex shader
**TL;DR** I need to switch from a vertex array passed to the pixel shader with a real vertex shader approach.

---

In my prototype, the terrain is procedurally generated and I have the following result:

The terrain vertices are passed directly to the pixel shader through an array:

```
//Number of vertices in terrain array
static const int verticesCount = 20;

//The vertices array, in pixel coordinates
float2 terrain[verticesCount];

//A fixed distance between neighbor vertices
float fixedDistance;

float4 PixelShaderFunction(float2 pixelCoords : VPOS,
                           float2 textureCoords :TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, textureCoords);
    int i = pixelCoords.x / fixedDistance;
    float delta = (pixelCoords.x - terrain[i].x)/(terrain[i+1].x - terrain[i].x);
    if(smoothInterpolate(terrain[i].y, terrain[i+1].y, delta) >= pixelCoords.y)
    {
        color.rgba = 0;
    }
    return color;
}

```

As you can see I just interpolate between the vertices and mask the texture to the terrain.

Now I need a different approach because I'm using a view matrix for the camera and it does not affect these vertices that do not go through the vertex shader, how can I replace the terrain array with a vertex shader to get a similar result?

All suggestions are welcome!

# Answer
> 1 votes
Rendering it as a quad (two triangles) and passing the heights as an 1D texture, like a heithmap texture, can do the trick.

---
Tags: xna, shaders, hlsl
---


title: Unity: OnCollisionEnter not called

text:
# Question
Title: Unity: OnCollisionEnter not called
I created a sphere object, added a rigidbody component (no kinematics) and attached a script to it like this:

```
function Update () {
}

function OnCollisionEnter(collision : Collision) {
    Debug.Log("OnCollisionEnter");
}

```

I then created a cube under the ball, added a box collider component with no trigger of course.

Then, when I run the game, the ball falls down onto the cube, but nothing happens. The `OnCollisionEnter` function isn't called.

What should I do?

# Answer
> 8 votes
I move the comment here, so we can eventually close the post.

Remember that both `GameObject` MUST have a `Collider` attached in order the `OnCollisionEnter` to be called.

As side notes:

* A `MeshCollider` cannot collide with another `MeshCollider`.
* Even if your colliders as marked as `trigger`, at least one of the 2 `GameObject` involved must have a `RigidBody` attached.
* Collision between `GameObject` can be selective enabled depending on the layer the `GameObject`'s belong to. Have a look at Layer-Based Collision Detection.

---
Tags: 3d, collision-detection, unity
---


title: OpenGL ES screen to world coordinate

text:
# Question
Title: OpenGL ES screen to world coordinate
I am currently attempting to convert my screen coordinates to world coordinates, to be able to interact with objects. I am using glm and unProject to try and achieve this, so far this is my code:

```
glm::vec4 viewPort = glm::vec4(0.0f, 0.0f, width, height);
glm::mat4 tmpView = sceneCamera->updateView();
glm::mat4 tmpProj = sceneCamera->updateProjection();
glm::vec3 screenPos = glm::vec3(touchPosition.x, height - touchPosition.y - 1.0f, 1.0f);
glm::vec3 worldPos = glm::unProject(screenPos, tmpView, tmpProj, viewport);

Renderer->SceneObjects[120]->translateX(worldPos.x);
Renderer->SceneObjects[120]->translateY(worldPos.y);

```

I am trying to get a sprite to equal the position where I tap. The issues is that the further I click going down the screen, the further the sprite overshoots, and the same horizontally. So if I click 2/3 the way down the screen, the sprite will overshoot the bottom of the screen.

# Answer
Your math looks sound, so it's hard to say for sure, but based on the description of your bug I think your touch coordinates are in a different range from your viewport.

If your pixel locations are in a range of x:\[0,800), y:\[0,600), but your touch coordinates are in x:\[0,1024), y:\[0,768), you would see a scaling effect where the farther you tap away from the origin, the farther the sprite overshoots its intended target.
> 1 votes

---
Tags: opengl, iphone, ios, opengl-es
---


title: Tile Maps in Java JFrame Game

text:
# Question
Title: Tile Maps in Java JFrame Game
I am making a 2D Java game with Java's own drawing library. I was wondering how I would make a tile map display on the screen. I would prefer to use a GUI application to make the maps. I'm looking for orthogonal projection: a top down view.

# Answer
> 0 votes
You can try using Tiled Map Editor. This editor has GUI for you to import tiles, make maps and outputs in XML format. You will need to parse the XML data in your game according to your needs. The XML format is described here and you can refer to this page for java XML parsers. There is a lot of sample games made with Tiled and documentation here.

---
Tags: java, swing, jframe
---


title: Setting Up GLEW with VS2012

text:
# Question
Title: Setting Up GLEW with VS2012
I'm trying to set up GLEW with Visual Studio 2012 and I'm having some trouble with it.

I downloaded the GLEW binary from http://glew.sourceforge.net/ and moved the contents from it's **lib** folder to **C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib** folder, and the contents from the **include\GL** folder to **C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Include\GL** folder.

Then I started up Visual Studio, and linked the glew32.lib in the linker properties section.

When I try to compile, I get the error: **error LNK1104: cannot open file 'glew32.lib'**.

How can I get this to work, preferably without copying the libs to system32? (I'll do that if I really can't get this to work)

# Answer
After downloading the binary you can extract the whole folder anywhere. For this example lets say `C:\glew-1.9.0\`.

After doing so you can go in VS2012, right click on your project, go to `Configuration Properties`, `VC++ Directories`, select `Include Directories`, from the dropdown list select `<Edit...>`, click on `New Line (Ctrl+Insert)` and paste in `C:\glew-1.9.0\include`, then press `OK` and repeat same steps by selecting `Library Directories` and add `C:\glew-1.9.0\lib`.

After that you can simply use `#pragma comment(lib, "glew32")`.
> 3 votes

---
Tags: opengl
---


# Question
Title: Moving A Sprite In The Direction Its Facing XNA
There are many questions on this site that explain this except they seem to all be in Java. I want to move a sprite in the direction it's facing, in XNA. I know you must use Radians and lots of complicated maths which I am not too familiar with. I tried doing this:

```
position.X += RotationAngle * 5;

```

This code obviously makes no sense whatsoever, and that's why I need help with it. How can I accomplish the rotation?

# Answer
> 8 votes
To do this requires a little bit of knowledge of trigonometry to work out exactly where to move the sprite.

C#'s Math class and XNA's MathHelper class can help considerably, but you will still need to know how to apply them.

Your entity would first need to have the following two fields.

```
public Vector2 Position { get;set; }
public float RotationAngle { get;set; }

```

If you want RotationAngle to be able to be set using degrees rather than Radians you can use the MathHelper functions to do so:

```
// RotationAngle is set using a value in degrees (the float f).
public void SetRotationAngle(float f)
{
    RotationAngle = MathHelper.ToRadians(f);
}

```

Then to apply a change in position using Rotation angle you would do some trig:

```
// This method applies the effects of movement to our entity.
// Speed is the number of pixels the object should move per call.
public void MoveEntity(float speed)
{
    Vector2 direction = new Vector2((float)Math.Cos(RotationAngle),
                                    (float)Math.Sin(RotationAngle));
    direction.Normalize();
    Position += direction * speed;
}

```

Here we determine the direction we want to travel in using the rotation factor of the sprite. We normalize the Vector so that it has a velocity of 1 unit. We then multiply our direction vector by speed to give us a direction and velocity we want. Finally we apply this directional velocity to our current position.

The thing to bear in mind here is that XNA sprites are initialized to be "right facing" meaning a 0 degree rotation angle will push your sprite right (along the x axis).

Finally, when we call our sprite to be drawn it should look something like this, though it will vary slightly based on where your objects are stored:

```
spriteBatch.Draw(texture,
                 new Rectangle((int)entity.Position.X,
                               (int)entity.Position.Y,
                               texture.Width,
                               texture.Height),
                 null,
                 Color.White,
                 entity.RotationAngle,
                 new Vector2(0, 0),
                 SpriteEffects.None, 0);

```

---
Tags: c#, xna-4.0, rotation
---


# Question
Title: How to implement homing missiles with loops while in transit?
I have implemented missiles that steer towards a target, however this feels kind of boring.

I want to add **loops**! Loops are cool! To do this I thought I could use catmull-rom splines, but that seems very static - loops would always end up at the same position unless I made several premade patterns.

Anyone have any other ideas on how I can do this?

I'm using a simple steering function: **EDITED**

```
         var toTarget = player.Position - missile.Position;
        toTarget.Normalize();

        float turnSpeed = 0.1f;
        float momentum = 3f;
        float speed = 1f;

        currentDirection = Vector2.Lerp(lastDirection, toTarget, turnSpeed);

        currentDirection.Normalize();

        lastDirection = currentDirection;
        lastPosition = missile.Position;

        player.Update(gameTime);
        missile.Update(gameTime);

        missile.Position = lastPosition + currentDirection * speed + lastDirection * momentum;

```

I have tried using the player as an attractor object which kind of works - the missile orbits the player object, but it mainly looks like it's moving backwards and forwards while the player object is standing still.

# Answer
You can use the steering to create loops. Simply have two targets for your missile. The player is one, and a loop target is the second.

Every N seconds, set the loop target to the missiles current position (plus a small random amount to either side of the missile's heading), and set the missile to steer towards that target. Since it's already in flight, it'll have to pull a u-turn to make it back to the loop target. Once it's either touched the loop target, or come "close enough" to the loop target, switch its target back to the player.

I imagine this will produce loops and probably even figure 8s (dual loops). The small random amount to either side means the turn direction for loops will change, you can set it to the same side each time if you want loops in the same direction.

Alternatively, you can have the rocket steering be normal, but have an additional force on the rocket. This force would be perpendicular to the direction of travel and the strength would vary over time (perhaps with a sine wave). You'd have to test it out, but I think that would give you bigger loops, without changing the turning radius of your rockets. Perhaps something like the rockets in The Clone Wars (the only clip I could find showing this, rockets just past the 56 second mark).
> 3 votes

# Answer
Instead of having just one target (the actual target), you can setup another "loop" target that updates as time passes to move in a circle. Instead of steering towards just the actual target, you can do some weighting to factor in the loop target. To make the loop target more prominently weighted at times, you could increase the loop weight every so often.

This would achieve both the effect of looping WHILE still moving towards the target.
> 0 votes

---
Tags: physics, motion
---


# Question
Title: Proper approach to handle transformation matrix and extract its components
Basically I have a Transformation component object with following structure(pseudo):

```
TransformComponent{
  Vec3 position;
  Vec3 rotation; //in euler angles
  Vec3 scale;
  Mat4 worldMatrix; //transformation matrix in world space
  Mat4 localMatrix; //transformation matrix relative to parent transform
  Mat4 worldToLocal; //Matrix to convert children worldMatrix in localMatrix
  TransformComponent parent;

  /* calculates worldMatrix using position,rotation & scale.
   * Also calculates inverse of worldMatrix and stores it in worldToLocal;
   */
  void CalculateWorldMatrix();

}

```

Then I do some transformations like:

```
    transform.position = [1,1,1]; //set new position

    transform.CalculateWorldMatrix(); //recalculate worldMatrix with new translation coordinates.

    //Multiply worldToLocal with worldMatrix in order to get localMatrix.
    localMatrix = transform.parent.worldToLocal * transform.worldMatrix;

```

After that, I have localMatrix with position, rotation etc relative to parent transform. But I can't figure out **how to get components(position,eualerAngles,scale) out of localMatrix**.
As far as I googled I found some really difficult solutions, which I couldn't understand, and as I'm writing on JavaScript I hope there is a simple solution.
**Maybe I am using wrong structure for transform object?**
**What is the common approach here?**
I read that its preferred to use quaternions, but only advance they give is about gimbal lock, at this moment because of simplicity I would like to stick with euler angles if it's possible.

# Answer
> 2 votes
I think your approach is backwards. You maintain data (like position and Euler angles) to produce matrices. Why try to extract that data from the matrix? (That isn't really how to use a matrix anyway; I will explain in paragraph two.) Use the source data when you need the source data, use the matrix when you need the matrix. Don't try to interchange them back and forth.

As for your question about how to "extract" a position from two multiplied matrices: you multiply your global position vector by the combined transformation matrix. That's it.

You seem to have an incomplete understanding of matrices, what they are and how to use them. I suggest that you dedicate some time to studying this topic on your own. It will make your project that involves a transform hierarchy much more feasible. Also, maybe you'll decide you don't even need to reinvent the wheel, and you can use someone else's js matrix library. Like this guy's or even Apple's.

---
Tags: matrix, transformation
---


# Question
Title: How to fire a bullet in a specific direction?
I am developing an Android game. I have problem with bullet firing. It's a space ship that has to fire bullets but right now it's firing in a random direction. I have to fire a bullet to the enemy from the only one point on the nose of the ship. Right now the bullets fire sometimes from the tailpart or other. So that's a problem. How do I give a bullet direction and how to fire it from only the head of my space ship?

```
private void fireBullet()
{
    float plusX = 16;
    float plusY = plusX * mPlayer.getRotationValue();
    Bullet mBullet = new Bullet(mPlayer.getX()-plusX, mPlayer.getY()+plusY, 8, 8, this.mGameController.mBulletTextureRegion, this.mPhysicsWorld, mPlayer);
    mBulletList.add(mBullet);
    //System.out.println("size is :" + bulletList.size());
    mScene.getTopLayer().addEntity(mBullet.getSprite());
    mSoundManager.playGunShot();
}

```

What is defect here?? it does not fire bullet from ship's nose?? What can be done..??

# Answer
You would need to have its position start at the ship's nose, and give it an x velocity proportional to the cosine of the angle you want to fire it at and a y velocity proportional to the sine of that same angle. You would multiply those values by the linear velocity that you want the bullet to have.
> 3 votes

# Answer
You can fire the bullet from the ship front face, if you have camera behind the ship than you have to cast a ray in the opposite direction of the camera and the position of the bullet creation is the position of the ship.

you can achieve the position of the bullet by this

```
bullet.position.x = ship.position.x;

```

You just need a reference point by which you can cast the ray.
> 0 votes

---
Tags: java, android, andengine
---


# Question
Title: Common practice when handling sprite animation
Let's say I'm using the following sprite as a sample to try LibGDX Animation and TextureRegion.

http://www.smackjeeves.com/images/uploaded/comics/7/8/78bc6b62fEySW.gif

As you can see, the provided image above has different width & height per image. The width when Zero performs a slash is different when Zero stands.

Is it a good practice to create a padding / margin for every image so they have similar width & height. Or should I just have all the sprite cramped like that and try to handle it in the backend?

Thanks

# Answer
> 6 votes
It depends.

There's a few things to think about here:

1. Are you using a lot of memory on textures already?
2. If you make all your texture rect sizes uniform (rects being the slice of the texture that represents a single frame of animation) and draw them all on the same size quad, are you drawing a lot of transparent pixels to the point where it's taking too long to render a frame? (more problematic on mobiles)
3. Are your art assets already in one format or the other?
4. Is it easy for whoever is creating your art to do one way versus the other?

The advantage of uniform rect sizes is that they're stupid-easy to deal with in code, and may or may not be easy to deal with from an art perspective. Some artists work by default drawing their sprites such that the character is already centered. This *is* less efficient both in terms of memory and (potentially) in terms of what you're making the GPU render, but before you start worrying about that you need to identify that this is even causing a problem for you.

Real world examples:

I've worked on a couple of 2D projects recently where each used a different approach.

The first had an isometric view, so our artist was modelling and animating characters in Maya then exporting them as a series of PNGs. Instead of making him pack together his own sprite sheet, I used a sprite packing tool that automatically generated frame positions and dimensions for each frame of the animation that he exported.

The second project was a platformer and our artist was animating each frame by hand. After doing a rough sketch of each frame in a character's animation, he would lay out a sheet in photoshop and draw directly on that. With this setup we figured that re-packing the sprite frames would have just been a waste of time. Thus we used the other approach where we just divided the spritesheet evenly in code and identified each frame by a single index.

This also enabled us to make a fun little animation file parser that let you easily mix and match animation frames. It's very possible to do with packed sprites, but I would have had to put a little more brainergy into making it happen.

Here's what the animation files looked like:

```
# Texture filename
GuySheet.png
# Frames across,down
7,12

# Basic Animations
idle            0-5
walk            6-12
jump            13-18
climb           19-23
dig_DOWN        24-29
dig_UP          30-35
dig_SIDEWAYS    36-41
swim            42-49
attack          50-56
split           57-64
death           65-71
falling         72-75
land_and_get_up 76-83

# Special animations made out of frames from animations above
unsplit         61-57
pulsate         66-69,68-67,57-63,62-57

```

# Answer
> 3 votes
Best practice for your backend/engine, or however you draw them, depends entirely on your game. Best practice for artists is probably a different story. So what you *should* do is really tough to answer.

You could add the padding when it is imported as a game asset. Or the code could keep a list of dimensions along with a list of texture coordinates for every animation frame, and draw different sized rectangles.

This community question has many websites dedicated to the subject. I know that more than a few of them will lead you to advice about best practice for the content itself. But again, that should be secondary concern to making content that fits your own game.

---
Tags: sprites, libgdx
---


title: lemniscate of Bernoulli

text:
# Question
Title: lemniscate of Bernoulli
I am trying to learn and teach myself openGL and I wanted to draw a figure 8 in a 3D setting but I'm having a problem. Please forgive me, I am very new at this but I'll attempt to explain what I have done so far

I understand that I can use the Lemniscate of Bernoulli to draw a nice figure 8, so I've have adopted that idea into my code. I just want to draw it along the x and z plane. My code looks like this

```
#define PI 3.1415926535f
#define MAX_STEPS 100.0f
//...
Vector3 PointOnCurve1(Vector3 p1, float t)
{
    Vector3 tempPoint = {0.0f, 0.0f, 0.0f};
    float scaler = 2/ (3- cos(2*t));

    varX = scaler * cos(t);
    varZ = scaler * sin(2*t) / 2

    tempPoint.x = varX+p1.x;
    tempPoint.y += p1.y;
    tempPoint.z =varX+p1.z;

    return tempPoint;
}

Vector3 g_Point    = {-4,  0,  0};
glBegin(GL_LINE_STRIP);
    for(float t = -PI; t <= PI; t += PI / MAX_STEPS)
    {
        vPoint = PointOnCurve1(g_Point, t);
        glVertex3f(vPoint.x, vPoint.y, vPoint.z);
    }

glEnd();

```

All I'm getting is one straight green line instead of a figure 8. any ideas? Am I missing something here? I'm basing this equation from this gamedev article

How can I move an object in an "infinity" or "figure 8" trajectory?

# Answer
Looks like a simple typo - you are updating tempPoint.z using varX, not varZ, so your coordinates move in unison and the shape collapses to a line. This is a common sort of mistake when writing componentwise math and you should learn to recognize the symptom.

Avoiding this mistake can be helped by using vector operations where possible, like `p1 + var` where var is a vector instead of varX and varZ.
> 3 votes

# Answer
You're viewing the figure 8 from the side, so it just looks like a line. Try building it on the XY plane instead of the XZ plane.
> 0 votes

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


# Question
Title: How can I create a 2D camera with upscaling and translation?
I've computed a Viewport that is fair in size (a proper aspect ratio to the given device) and then I calculate my ScaleMatrix like so:

```
  scaleMatrix = Matrix.CreateScale(
        (float) GraphicsDevice.Viewport.Width/virtualWidth,
        (float) GraphicsDevice.Viewport.Width/virtualWidth,
        1f);

```

That by itself, works great. The game scales and everything works fine. However, I'm not trying to add translation to track my character and some things are going a bit wonky.

I'm trying to construct my full transform like so:

```
   _transform =
                Matrix.CreateTranslation(new Vector3(-pos.X, -pos.Y, 0))*scale
                * Matrix.CreateTranslation(new Vector3(_viewPortWidth * 0.5f, _viewPortHeight * 0.5f, 0));

```

Am I doing something wrong? The results are not what I expected; the position is the position of the character. Before i added the scaling code, something like this worked for translation.

Here's an image to demonstrate what I want, sorry for the excessive size: =

Here's a screenshot of what I currently get:

I'm looking to find a way to achieve the first result with automatic scaling to the maximum viewport size.

# Answer
There are two parts to the problem :

1. To compute the camera size you will only need to scale it down from your maximum camera size if the map is smaller than that size. When scaling, you need to select the smallest dimension of your map, vertically or horizontally, and work out the \>1 ratio of width:height or height:width. You want to do this because you always want the graphics to fill the scene-view and the larger of the two dimensions to reach off-screen. Working that out and using it to scale your map will assure that your scene-view is always full.
2. You also want to do a separate bounds check, as Cong Xu mentioned, so your camera follows your character, except the camera's position is bound within a camera safe region. That region will be 1/2 camera width and half camera height in from the edges. Notice that this will need to be recomputed for each map as the camera size will change.
> 0 votes

---
Tags: c#, matrix, monogame, transformation
---


title: Should I learn OpenGL 1.5?

text:
# Question
Title: Should I learn OpenGL 1.5?
I want to start learning OpenGL with a book I have since a long time ago (Beginning openGL Game Programming) and it uses OpenGL 1.5 so my question is, should I learn OpenGL using this book and then learn a higher version? or should I start learning a higher version at once? are the same core concepts applied to higher versions?

# Answer
> 13 votes
**No.** Modern OpenGL and OpenGL 1.5 have very little in common. It's better to learn the modern OpenGL directly. Here is a good online tutorial for that: Learning Modern 3D Graphics Programming.

---
Tags: opengl
---


title: Packaging XNA game studio with project

text:
# Question
Title: Packaging XNA game studio with project
I published an XNA game (for Windows only) using Visual Studio's publish feature which is supposed to handle dependencies and all that.

When I installed it on myself it verified system requirements and installed correctly.

When I tried to install it on a fresh PC, it gave me an error that I was missing the XNA redist. I had to download it separately and then install the game. Is there a way of setting it to download XNA redist automatically as part of the 'one click' installation process? Or will the end user have to stay downloading the redist earlier?

# Answer
> 3 votes
**Background:** ClickOnce generates two files: The `.application` file - the "ClickOnce Application Deployment Manifest", and a `setup.exe` bootstrapper.

`setup.exe` will check for prerequisites, install any that are missing. When it's finished it will then run the `.application` file. The `.application` file will install and then run your application.

You can invoke the `.application` file directly, but then the prerequisites won't be installed.

**Possible causes:** Either you ran the `.application` file instead of `setup.exe`. Or the prerequisites specified in the bootstrapper are misconfigured.

**How to fix:** You can select which prerequisites are installed by opening the properties of your game project, selecting the Publish tab, and clicking "Prerequisites":

This will open a Prerequisites window, where you can select what redistributables will be installed by the bootstrapper.

For XNA, you need:

* Microsoft .NET Framework 4 Client Profile (x86 and x64)
* Microsoft XNA Framework Redistributable 4.0
* Windows Installer 3.1

These are automatically selected by the default Game Project template, so it should "just work".

The only other thought is that the computer you were installing on wasn't able to install XNA for some reason. Possibly it could not connect to Microsoft's website to get the installer. Although I would expect it to display an error during installation in this case. It is safe to run `setup.exe` repeatedly.

---
Tags: xna, windows, publishing
---


title: XNA 4 Content Pipeline dependency

text:
# Question
Title: XNA 4 Content Pipeline dependency
I tried to create something to parse XML with, which needs the inclusion of the `Microsoft.Xna.Framework.Content.Pipeline;` reference. This was fine and all, but as soon as I tried to debug, I got the error that it could not be resolved because it was in the wrong target framework; my main project uses the Client one.

What confuses me is that I can use the SkinnedModelProcessor in the same solution with no problems when *it* uses said non-Client framework. Why is this? Can I get mine to work without changing the main project's target framework?

# Answer
The XNA content pipeline assemblies depend on the full version of the .NET Framework (instead of the Client Profile). This is because they use features not available in the client profile (probably the MSBuild stuff).

You can select which version of the framework to build against in the properties window for your assembly:

**However:** The XNA Content Pipeline assemblies are **not** redistributable. So anyone using your game would need to install Visual Studio (Express) *and* XNA Game Studio by downloading them manually from Microsoft. Not exactly user-friendly!

(Also the full version of the framework is much larger than the client profile and takes longer to install, which may be a consideration for distribution as well.)

My recommendation would be to parse your XML at build-time using a content pipeline extension. Or load your XML using some other .NET XML reading method. Or use a different serialisation format entirely, maybe simple text files, or something using `BinaryReader`/`BinaryWriter`.
> 2 votes

---
Tags: xna-4.0, xna-content-pipeline
---


# Question
Title: Flixel: Is it possible to use a spritesheet for FlxButtonPlus?
I'm trying to change the graphic on a FlxButtonPlus. I want to get the graphic from a spritesheet. However, if I try the ' regular' way (make an animation and play it), it refuses to use just the part of the spritesheet I want and instead insists on showing the complete spritesheet.

Creator of the sprite:

```
public function ButtonSprite(c:int){
    loadGraphic(ImgButtons, true, false, 30, 80);
    addAnimation("static", [c]);
    play("static");
}

```

How I try to add it to the button:

```
currentButton = new FlxButtonPlus(30, 80, playLevel, [0], "Unlimited", buttonWidth * 3, buttonHeight);
var sprite = new ButtonSprite(1);
currentButton.loadGraphic(sprite, sprite);

```

Thanks!

# Answer
I have not been able to find a way to do this. So for now I'm going with:

No, it is not possible to get the Sprite for a FlxButtonPlus from a spritesheet.
> 0 votes

---
Tags: flash, actionscript-3, spritesheet, flixel
---


# Question
Title: Isometric Error: decrement iteration removes tiles
I am new to isometric and game programming in general.

Just cannot figure out how to iterate the grid from behind. I want to do it so that the tiles overlap properly.

My grid starts at \[0\]\[0\] which translates into the tile closest to the left edge.

This is how my a smaller version of my map grid looks like:

```
var map = [
[1, 1, 1],
[1, 0, 0],
[1, 1, 1]
];

```

I have no trouble displaying it when I loop forward through the arrays:

But when I try to iterate backwards through the Y array, it starts bugging, and does not display all tiles and have no clue why:

**I hope the images are large enough, else please "Zoom in" or open them in a new tab.**

Cheers

# Answer
> 2 votes
You're not drawing for y==0 in the second loop. That's why you don't have everything.

You can fix your loop as

```
for (var y=map.length-1; y>=0; y--) {

```

or more concise :

```
for (var y=map.length; y-->0;) {

```

---
Tags: javascript, isometric
---


title: Bullet Manager Class

text:
# Question
Title: Bullet Manager Class
I'm making a game in AS3, and it's a rather simple shooting game because I'm original. Anyway, probably the most subjective question here yet: what is the best way to implement bullets in my game?

Would it be smarter to make a universal bullet manager class on the game that handles all the bullet related data or have every entity that has bullets (players, enemies) have this sort of 'bullet manager'?

Make a level-wide bullet manager --or-- bullet manager for each entity?

Oh, and a side question: I actually have an enemy manager class. How would I check for collisions from the aforementioned bullet manager class.

# Answer
You can treat your bullets just like other gameobjects in your system. There is no real reason to separate every type of gameobject( there is no need to have managers for everything). Use a clean interface class(not gui) so that you can treat them all the same. For example your interface can contain an update function so all of your gameobjects have an update function that is called in your gameloop.

As for collision detection, you could consider a manager that deals with spacial portioning where your gameobjects are separated into their own spatial bounded groups and only checks collision for the objects that are in that specified coordinate boundaries. When analysing objects for spatial partitioning you can check whether they are even relevant to collision. If not simply ignore them.

You can give your bullets a grouping type/tag. So that you can separate player and enemy bullets during the process of separating your spatial objects. When collision occurs you can send out an event that's caught somewhere where the appropriate action is taken.
> 1 votes

---
Tags: actionscript-3, oop
---


# Question
Title: What are the benefits of using a 2D game engine on Android?
I have thought about just coding a 2D game on Android using just pure Java and the Android SDK, no engines like libdgx, cocoa-2dx attached. I don't know if I really need to use a game engine or not. Doesn't Java already come with basic libraries and APIs for most things already?

I'm not interested in the cross-platform aspect of game engines. The game is 2D, so there's no complex issues with 3D, importers, or what not. I also don't like to have to code around level editors or pre-built constructs like a character or tile class.

Given this, are there any other benefits for me using a game engine to code my Android 2D game? For example, I'm clueless with OpenGL so if I'm doing it w/o an engine I would be using pure Java, would that be significantly slower than using an engine like libgdx?

# Answer
> 3 votes
As an observation to Byte56's answer: (especially) with Android, even if you want to make just a 2D game, it may theoretically seem to suffice using the Canvas draw calls and basic Java API. Doing it like this might seem to have certain benefits to using a specialized engine, especially if you're already very familiar with Java.

The problem is, in reality you ***do*** want to use OpenGL (ES 2.0 in this case) even for a simple 2d game. First and foremost, it's a question of performance: drawing textures on quads as opposed to sprites drawn via Canvas draw calls will be literally orders of magnitude faster. Furthermore, Android imposes limitations on how many images you can load via Java & Canvas API, limitations which are not present when loading them as OpenGL textures.

So in this case, you'll benefit a lot more from using an engine to do all this as opposed to doing it by hand. Just the part where it alleviates all the boiler plate code is a big plus. For example: try making something like an OpenGL "text sprite", using only the basic ASCII characters and one single font, by hand, for OpenGL. Then try using the built in functionality for this comes with AndEngine. You have a ton more options, and the learning curve will take you a lot less time than the by-hand-coding alternative.

# Answer
> 6 votes
The benefit is pretty obvious. **It saves you a lot of work**. That's the purpose of the engine. Android will come with the basics, but a game engine will have already implemented a good deal of the tedious work required to create a game. Perhaps you haven't looked into it much, but there's still a lot that a 2D game requires that's not part of the base Android SDK.

As you'll hear from lots of experienced developers, make a game not an engine.

Obviously you know the requirements of you game best, so it's up to you if you want to use an engine or not. You may want to just pick and choose among the various libraries available instead of going with a full blown engine.

# Answer
> 0 votes
I agree with Byte56. However, if you are building a game for the first time, designing it completely by yourself is a great way to start. This will make you clear on what are the various aspects, pitfalls, etc. in designing your game. However, once you are done with it, work on a game engine to speed up your game development cycle.

---
Tags: java, android
---


# Question
Title: How well (or badly) does Minecraft SMP scale?
Has anyone tested and collected some data about how well does Minecraft SMP scale, with an increasing number of players (up to large amounts of players)?

I.e. the bottlenecks are:

1. mostly in the server or in the client or both
2. if the players are all in the same area, or if they are in different areas, or it is irrelevant where they are

# Answer
The main bottleneck is storing and generating chunks on the server.

Around 10 Chunks in each direction are loaded for every player, that means that if a lot of players are in one spot, it's only going to load the chunks once, but if all players spread out, it's going to load these 10 chunks in each direction for every player. It gets even worse if the players are generating new chunks.

We've never had problems with our bandwidth, but I believe that Minecraft is really lavish with it's network resources, so that could be a potential bottleneck as well.

I've been running my own Server for quite a while now (since the first SMP Alpha) and we've upgraded our Server several times too. For us, the main bottleneck was our HDD, the server had huge lags when people generated new terrain. (running around 32 Players at peak times)

To answer your questions:

1. Mostly on the server. The client will leave already loaded chunks loaded as long as enough memory is available. The server however will unload every chunk that is not within a 10 chunk radius of the player.
2. All players on one spot won't need as much performance as when everyone spreads out or generates chunks. Different biomes seem to have different effects too, I've noticed that our server really struggled with generating Snow and Nether Biomes.

Also, you're able to modify the viewdistance in the server.properties. It's set to 10 chunks per default IIRC.
> 4 votes

---
Tags: multiplayer, server, minecraft-modding, scalability
---


title: Accumulating rotations for camera

text:
# Question
Title: Accumulating rotations for camera
It seems there are three ways to store a camera's rotation: in angles, view matrix or quaternion. I was using euler angles since when I used a matrix it had a tendency to accumulate rounding errors quickly that threw off everything and quaternions would have the same problem.

The problem I've run into is how do I accumulate the rotation? When the camera is rotated, it's rotated in local space about its local XYZ axes. How would you use the given angles in a rotation to rotate about these arbitrary axes? Usually this operation is done with a matrix but it doesn't make sense to try to extract the new angles out of it.

Or perhaps I should be just storing the rotation in a matrix or quaternion? But can this be done without errors eventually causing problems?

# Answer
You must maintain each of your three local axes. When you rotate around one, you must update the other two.

```
class gameclass
{
Vector3 forward = Vector3.UnitZ;    //persistent orientation variables
Vector3 left    = -1 * Vector3.UnitX;
Vector3 up      = Vector3.UnitY

Matrix world = Matrix.Identitiy;

InputClass inputclass;           //something to get your input data

void Update()
{

Vector3 pitch = inputclass.getpitch();          //vertical swipe/stick
forward = Vector3.transform(forward, Matrix.CreateFromAxisAngle(left, pitch));
up      = Vector3.transform(up, Matrix.CreateFromAxisAngle(left, pitch));

Vector3 yaw = inputclass.getyaw();              //horizontal swipe/stick
forward = Vector3.transform(forward, Matrix.CreateFromAxisAngle(up, yaw));
left    = Vector3.transform(left, Matrix.CreateFromAxisAngle(up, yaw));

forward.Normalize(); left.Normalize(); top.Normalize();  //avoid rounding errors

world = Matrix.CreateWorld(
    postition                     //this isn't defined in my code
    forward,
    up);
}

}

```
> 2 votes

# Answer
Since you have to have a view matrix to send to the shader, and your camera's rotation already in it, and it's an ortho-normal matrix, why not use it as your 'storage' device?

Assuming whatever framework you are using has methods for transposing matrices, rotations about arbitrary axis, multiplying a vector by a matrix(transforming), & building a matrix from 2 vectors. Here's some xna code but can be thought of as pseudo code.

```
Vector3 camPosition;
Vector3 camTarget = new Vector3(0, 0, -1);//init to whatever you want. does not need to be unit length
Matrix view = Matrix.Identity;

//these items should be updated each frame before updating camera
float pitchChangeFromLastFrame, yawChangeFromLastFrame;//long names just to clarify meaning
float arcPitchChangeFromLastFrame, arcYawChangeFromLastFrame;
Vector3 pointToArcAbout;//usually the camTarget
Vector3 strafe;
public void CameraUpdate()
{
    Matrix camWorld = Matrix.Transpose(view);

    //pitch camera (tilt)
    camTarget = Vector3.Transform(camTarget - camPosition, Matrix.CreateFromAxisAngle(camWorld.Right, pitchChangeFromLastFrame)) + camPosition;

    //yaw camera (pan)
    camTarget = Vector3.Transform(camTarget - camPosition, Matrix.CreateFromAxisAngle(camWorld.Up, yawChangeFromLastFrame)) + camPosition;//often you would use 0,1,0 instead of camWorld.Up

    //strafe camera (track)
    camPosition += strafe;
    camTarget += strafe;

    //arc camera (pitch)
    camPosition = Vector3.Transform(camPosition - pointToArcAbout, Matrix.CreateFromAxisAngle(camWorld.Right, arcPitchChangeFromLastFrame)) + pointToArcAbout;

    //arc camera (yaw)
    camPosition = Vector3.Transform(camPosition - pointToArcAbout, Matrix.CreateFromAxisAngle(camWorld.Up, arcYawChangeFromLastFrame)) + pointToArcAbout;

    //rebuild view matrix
    view = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);//creates an ortho normal matrix each frame from 2 vectors (camTarget - camPosition, & the up vector)
}

```

Essentially this takes 2 points in space (position & target) and rotates them about each other (using local axes) or moves them together (strafe), then builds a brand new ortho normal matrix each frame from them.
> 0 votes

---
Tags: 3d, mathematics, camera, matrix, quaternion
---


# Question
Title: Does iOS support BC4 compressed texture?
I've been designing a new OpenGL image algorithm using BC4 textures at its core. It works well accross Windows and Mac, my main targets up to now.

But today, the customer added a new requirement : it should work on iOS too ! I'm starting to worry : is BC4 texture (named GL\_COMPRESSED\_RED\_RGTC1 in OpenGL) supported on iOS devices (tablets & iphones alike) ?

I've read that iOS is OpenGL ES 2.0 capable. But i'm unable to know which textures are supported under this API (except PowerVR ones, which are not compatible with PC & Macs...)

# Answer
OK, i guess i have to answer my own question. I have not found a single compressed texture format in common between iOS and PC/Mac. Apparently, the only type of compressed textures supported by iOS are PowerVR-based, which are completely proprietary (e.g. not part of OpenGL standard).

So I guess my question is included in this answer : iOS does not support BC4 textures.
> 1 votes

---
Tags: textures, ios, opengl-es, compression
---


# Question
Title: How to draw millions of cubes without idle , model instancing in XNA?
I work for a project in the style of game "Minecraft".

I started using the "Model Instancing" in order to generate a large number of cubes possessing an identical model. So far so good. My problem is that if I increase the size of my matrix to draw from \[300-1-300\] (**90,000 cubic meters**) of \[500-1-500\] (**250,000 cubic meters**) my program slows down tremendously. It goes from 60fps to 20 ...

I do not really understand why. But I use the technique correctly "Hardware Instancing". I also noticed on forums that this technique allows XNA to draw up to 7 million cubic!! Do you have any idea from where my problem ?

Thanks a lots

**Here is my function that draws the model instantiated:**

```
// Draw the 3D map (world) of game
public void drawWorld(GameTime gameTime)
{
    / * Draw all the structures that make up the world with the instancing system * /
    Array.Resize(ref instanceTransforms, smallListInstance.Count);

    for (int i = 0; i < ListInstance.Count; i++)
    {
        instanceTransforms[i] = ListInstance[i].Transform;
    }

    DrawModelHardwareInstancing(myModel, myTexture2D,instancedModelBones,instanceTransforms, arcadia.camera.View, arcadia.camera.Projection);

}
// ### end function drawWorld

```

**Here is my function \[DrawModelHardwareInstancing\]** which draws models with the method **\[Hardware Instancing\]** used in the sample from microsoft.

```
// Function that will draw all the models instantiated in the list
void DrawModelHardwareInstancing(Model model,Texture2D texture, Matrix[] modelBones,
                                 Matrix[] instances, Matrix view, Matrix projection)
{
    Game.GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
    if (instances.Length == 0)
        return;

    // If we have more instances than room in our vertex buffer, grow it to the neccessary size.
    if ((instanceVertexBuffer == null) ||
        (instances.Length > instanceVertexBuffer.VertexCount))
    {
        if (instanceVertexBuffer != null)
            instanceVertexBuffer.Dispose();

        instanceVertexBuffer = new DynamicVertexBuffer(Game.GraphicsDevice, instanceVertexDeclaration,
                                                       instances.Length, BufferUsage.WriteOnly);
    }

    // Transfer the latest instance transform matrices into the instanceVertexBuffer.
    instanceVertexBuffer.SetData(instances, 0, instances.Length, SetDataOptions.Discard);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (ModelMeshPart meshPart in mesh.MeshParts)
        {
            // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer.
            Game.GraphicsDevice.SetVertexBuffers(
                new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0),
                new VertexBufferBinding(instanceVertexBuffer, 0, 1)
            );

            Game.GraphicsDevice.Indices = meshPart.IndexBuffer;

            // Set up the instance rendering effect.
            Effect effect = meshPart.Effect;
            //effect.CurrentTechnique = effect.Techniques["HardwareInstancing"];
            effect.Parameters["World"].SetValue(modelBones[mesh.ParentBone.Index]);
            effect.Parameters["View"].SetValue(view);
            effect.Parameters["Projection"].SetValue(projection);
            effect.Parameters["Texture"].SetValue(texture);

            // Draw all the instance copies in a single call.
            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                                       meshPart.NumVertices, meshPart.StartIndex,
                                                       meshPart.PrimitiveCount, instances.Length);
            }
        }

    }
}
// ### end function DrawModelHardwareInstancing

```

# Answer
> 2 votes
You shouldn't be attempting to instance individual cubes at all.

I developed Techcraft together with two close dev friends. It has all the sample code you will need to learn from, if it helps.

Feel free to download the source code and use as you wish:

http://techcraft.codeplex.com

Good luck! Hopefully we can add your game to the list on the project page.

---
Tags: xna, models, vertex, instancing
---


# Question
Title: Speech recognition and AI in language learning platform
I work for a publishing company that is looking to create an online virtual environment for English Language Learners.

We are keen to create something immersive (virtual 3D world) through which the learners can experience 'real' interactions. Part of this is that we really want them to be able to speak in the environment (and for the game NPCs to be able to respond/register the learner's utterances). Is there tech out there that could help us achieve this? Is there currently anything like this out there?

# Answer
This is really cutting edge stuff you are requesting here. I did a lot of research into the state of AI when writing my master thesis, and found that voice recognition is a long way off yet. That is not to say it isn't possible to do some basic stuff. You can test it out for yourself with windows speech recognition. The speech recognition API for the Kinect (which is really the same) is available for use by developers, and might be worth looking into. http://www.renauddumont.be/en/2012/kinect-sdk-1-0-5-reconnaissance-vocale

This api is probably not going to allow you to have natural conversations however.. If this is what you are looking for, you are in for an even larger challenge. Google is doing a lot of work in the field: http://research.google.com/pubs/NaturalLanguageProcessing.html

There is a lot of research going on in this field, and there are also open source solutions you might want to look into. Keep in mind however, that the main challenge here is mapping recognized language to in-game results. You need a database of viable responses, voice-acting for all these responses, etc.

To summarize: this is a large to massive challenge, depending on your goals. It is cutting edge AI research, which would require a highly technical team to work with the project. It is possible to make something like this, but expensive and/or difficult.
> 4 votes

---
Tags: 3d, unity, ai, education
---


# Question
Title: How does this example make efficient voxel engines using "chunks"?
I'm currently looking in to how voxel engines works, with a view to possibly making one, myself. I see a lot of material, like *"Let's Make a Voxel Engine"*, which talks about how to go about reducing the draw calls. What I can't seem to understand is how it actually saves draw call counts, on the basis of the logic being something like the following:

```
// Without chunks:

foreach voxel in myvoxels
  DrawIfVisible()

// With chunks:

foreach chunk in mychunks
    DrawIfVisible()

    // which then does ...
foreach voxel in myvoxels
    DrawIfVisible()

```

Surely, you save nothing by doing this; you still make a draw call for each visible voxel, and a visible voxel needs a draw call in either scenario. The only real saving I can see is that the logic that evaluates a chunk will be able to determine if a large number of voxels are visible or not, effectively, saving a bit of "is this chunk visible" CPU time. It's the draw calls that interest me; the fewer of those, the faster the application.

In case it makes any difference, I will probably be using XNA with DirectX for my engine, so don't consider my choice of example in the link above as my choice of technology. However, this question is such that I doubt it would matter.

# Answer
> 4 votes
If you're testing each voxel individually for visibility each time, I suppose you won't save much. However, typically you'd want to build a buffer that represents the surface of your voxel world.

You don't just "draw" voxels, you need to build a mesh that represents the voxels. Building that mesh is expensive, so you want to reduce the number of times you need to do that. The first way is by only rebuilding the mesh when voxels change. So you build a buffer containing the vertices that represent your voxels. Then you draw that buffer every frame.

Now that you have a buffer, you need to rebuild it every time something changes. That means throwing the entire thing away and rebuilding it all. But building is expensive, so maybe there's a way we can reduce the amount of waste when something changes? Yes, we can just rebuild the world *around* the voxels that changed. If we only have to update the *chunk* around the changed voxel, we save ourselves a lot of time in rebuilding something we already had.

Now the terrain is chunked into smaller parts, we can just draw the chunks that are visible to us and we can just rebuild the chunks that have voxels change in them. We can do even more now that we have chunks. For example, with chunks that are far away, we can build buffers for those that have reduced polygon count, so they're not so expensive to draw.

All in all, chunks allow us to have more control over what we draw and when. It enables us to implement performance features we wouldn't be able to otherwise.

---
Tags: xna, architecture, voxels
---


title: CCSequence with two CCAction

text:
# Question
Title: CCSequence with two CCAction
I have two CCActions : CCAction \*a; CCAction \*b;

so how to use CCSequence with two CCActions Thanks

# Answer
> 1 votes
```
CCFiniteTimeAction *example = CCSequence::create(a, b);

```

CCSequence

Alternatively you can just run the action on a sprite directly.

---
Tags: cocos2d-x
---


# Question
Title: Is Edge by Mobigames 3D or isometric 2D?
I'm trying to make a similar to http://www.cultofmac.com/edge-for-iphone-controversy-rumbles-on-game-again-pulled-from-app-store/13115, but I'm not sure if it's real-time 3D or just really good 2D. Any thoughts?

# Answer
> 6 votes
Your question is a little vague. Are you specifically asking if Edge uses 2D or 3D graphics? Or looking for thoughts on whether your similar game should be in 2D or 3D?

Edge certainly looks like it's using full 3D graphics, a fixed camera angle, and orthographic projection. The fact that a number of game objects rotate leads me to believe that it's all 3D cubes that can be transformed in various ways. Rather than going through the process of animating a sprite for the necessary cube rotations, 3D graphics would look smoother with less overhead, in my opinion. However, one could very easily make a similar style of game in isometric 2D.

If you're asking how you should do it, what does your past experience point to? Do you have more 2D or 3D work experience and do you want to branch out into what you don't know as well? What engine(s) are you considering? I think, all things being equal, a simple 2D version of that style of game would be quicker to set up than a 3D one.

# Answer
> 3 votes
In my opinion, the thing that adds most to isometric games is the 2D graphics. You are trying to simulate a 3D enviroment with 2D graphics, so it will take some workaround to get the 3D effect you desire (depth sorting, rotating the view). The game you showed doesn't use any 2D assets. So 3D seems like a more logical choice.

# Answer
> 1 votes
There is one big difference between 2d isometric and 3d games. isometric games always have some **specific** camera and object angles.

If you are going to create a game similar to that one, I guess you can use a isometric view since the games feels complete even without rotating the camera, and it's obvious that object in the game also can only be rendered with some specific angles.

in general you can choose both isometric or 3d game, but 3d rendering consumes much more computational power and may cause low fps in handheld devices like iphone. in the other hand managing game scene in a 3d game is much more easier.

# Answer
> 0 votes
They made a 3D version with perspective some time ago: https://play.google.com/store/apps/details?id=net.mobigame.edge.extended&hl=de

So the rendering in the orthographic (isometric) version is made with 2D-techniques and I think the rotating blocks are just many sprites.

---
Tags: 3d, isometric
---


title: How to render a tilemap efficiently?

text:
# Question
Title: How to render a tilemap efficiently?
I'm using this code to load a tiled map, composed of 1000x1000 32x32px tiles:

```
map = new TmxMapLoader().load("levels/xyz.tmx");

camera = new OrthographicCamera();

camera.setToOrtho(false, Constants.WORLD_WINDOW_SIZE.x / 32,
            Constants.WORLD_WINDOW_SIZE.y / 32);

renderer = new OrthogonalTiledMapRenderer(map, 1 / 32f);

renderer.getSpriteBatch().disableBlending();

renderer.setView(camera);

```

And this code for rendering:

```
camera.update();
renderer.setView(camera);
renderer.render();

```

However, I have huge performance issues. How can I optimize this code ? Will splitting the map in multiple submaps help?

Greetings, TM3P

# Answer
> 4 votes
In addition to the techniques discussed in the link above, think about frame layering as well. In my game engine (board is 750 x 450 hexes of 32^2 pixels) I triple buffer the display into map, units, and highlights. On each Paint cycle:

* MapBuffer is repainted only if the view has panned or zoomed;
* UnitBuffer is refreshed from MapBuffer and units repainted only if one or more units has moved;
* HighlightBuffer is refreshed from UnitBuffer and repainted; and
* HighightBuffer is drawn to screen.

---
Tags: java, rendering, tiles, libgdx
---


title: Physics body with custom shape

text:
# Question
Title: Physics body with custom shape
I want to make a **physics body** like this image.

The **red** color ellipse will be the physics body and the curved antenna shapes will not included in the physics body.

I want to know how to call the function to create it. Like:

```
body = PhysicsFactory.createBoxBody(physicsWorld, this, BodyType.DynamicBody, objectFixtureDef);

```

# Answer
> 1 votes
You have to use Physics Editor for this purpose. If you don't know anything about it then get proper information about it.

Following link gives you direct link to download Physics Editor

Physics Editor generate xml file and many other format that you want. You have to add sprite and create vertex that you want available in the body. Then generate a file that contain information about the body that you want to create. So that you have to only parse that information and provide as argument to polygon shape.

---
Tags: andengine
---