title: Bevel outline algorithm in 2D

text:
# Question
Title: Bevel outline algorithm in 2D
I'm writing a program that creates animated blobs in 2D, to simulate cells. In order to beautify these objects, I'd like to give them a 3D look by adding a bevel-effect. How can this be achieved?

Program as it looks now (the blobs are animated, move, change shape etc):

And this could be a potential desired outcome:

I underscore that I'm not using anything else than GDI+, so I'll have to write the implementation myself. Virtually every graphics program has some kind of beveling filter, but I've looked high and low online to find examples of such code.

Edit:

I was testing a few theories, and this one could work. However, it's not my most optimal solution (even though Gaussian blurs can be made linear using separable kernels) and I have another in the working. Anyway, this could be a first attempt at a fast beveling algorithm:

The result in the picture I created above is the direct outcome of the steps of the algorithm, but I suspect it might run too slow for 25fps.

# Answer
> 4 votes
What shapes are you using? If your shapes are convex (like circles, squares, rounded rectangles), you can just draw versions of different size and clip them to a triangle whose diagonal goes from upper right to lower left.

I.e., zoomed in, light-to-dark:

and dark-to-light:

Then clip that:

And then combine the two bezels:

and finally draw the original shape on top:

Now this example is rough and too coarse, but if each of the three rounded rectangles only is visible as a one pixel outline, this will look like a gradient from light to dark in the upper left, and in the opposite direction in the lower right.

Note that in this example the colors are too different, so you can see the various parts. Basically you should take the inner shape's color (in this case white) and lighten it 3 times for the transition to upper left, and darken it for the transition to lower right. The final effect you're going for (again, zoomed in) is something like:

In theory you could just use *one* larger shape, clip it, and fill it with a gradient, for each half, but it's quite difficult to get the gradients to line up properly for non-square shapes. Also, this doesn't work for concave shapes (like the letter "C"). The trick to a good bezel is a good algorithm for generating that larger version of your shape. But not scaled up. Ideally, you'd just "outset" the shape, which will change its proportions. If you're generating the shapes yourself, as pixels, just draw each pixel as 9 pixels and you have the perfect 1-pixel-outset for the next-larger shape in the algorithm in my answer.

**Update:** Another approach would be to first render your shape into a bitmap, and then loop over the pixels. If you find a pixel that is "on", check its surrounding pixels. If it has empty pixels below it or to its right, darken it. If it has empty pixels to its left or above it, lighten it. That would give a proper 1px bezel that lies *inside* the shape. You could then repeatedly apply this algorithm by mixing the light/dark colors with a percentage of your shape's color, and by looking for pixels you darkened/lightened in the previous iteration instead of transparent pixels. This is probably something that wouldn't be too fast until you manage to implement it e.g. as a shader on the graphics card.

# Answer
> 0 votes
You could get a bevel effect by underlaying the cells with upscaled graduated transparencies of themselves. This can also be used to get a glow effect.

---
Tags: c#, 2d, graphics, algorithm, windows
---


title: Keeping sprites nice and pixelated

text:
# Question
Title: Keeping sprites nice and pixelated
How do I keep the sprites in my game nicely pixelated on screens of all sizes and resolutions? I use nearest-neighbor texture filtering when resizing pixels, but this works well only at really high magnifications, otherwise the pixels get distorted and uneven.

I understand the limits of nearest-neighbor scaling and I wouldn't be asking this except there are so many games that use pixel art without this problem, so I figure there is some trick I don't know about.

# Answer
For one, nearest-neighbor **will** result in pixel perfect scaling only if it's used to upscale in integer multiples. Apart from that, you should not be conducting any scaling operations on your view/projection matrices. If you set your view to match the dimensions of the screen, and your projection matrix to be orthographic with dimensions that match the viewport, your "world" coordinates will be true on-screen pixels. Your viewport can resize to fit different screens, but it shouldn't actually impart a scale factor, you should just show more or less of the game world. Further, you should probably disable AA, and remember that in OpenGL the center of each pixel is located at (.5, .5), not (0, 0).

Take a look at these related questions:

https://stackoverflow.com/questions/10040961/opengl-pixel-perfect-2d-drawing

https://stackoverflow.com/questions/16511374/pixel-perfect-projection-matrix-in-opengl
> 5 votes

# Answer
You need to average the sprite pixels which are visible beneath each screen pixel. The sprite pixels can be sampled "nearest", but to move smoothly in subpixel increments on the display, you need some kind of oversampling.

If you're using OpenGL, you can do this in your shader by averaging 4, or 9 or more sprite samples offset near each fragment (calculated to be within a screen pixel). Alternatively, render your scene at 4 or 9 or more times the screen size, and then reduce with averaging. (This may be available directly on your platform, or implemented as a shader, but run just once at the end instead of per sprite.)

Which one is more performant depends on the scene, number of sprites &c.

-- EDIT: One more approach -- Make your sprites pre-magnified, pixelated but nice and big, and use linear interpolation. That way when a (big) "pixel edge" is under a fragment, you'll get a blend.

All of these methods run risk of washed-out strobing, if sprite pixels are close in size to screen pixels, or if they match but offset fractionally. I think the a good rule would be, if sprite and screen pixels match exactly and are aligned: Looks good. Else, sprites should be scaled at least 2.0+ and fractionally averaged, to guarantee at least one fully-colored screen pixel per sprite pixel.
> 2 votes

# Answer
You'll want to look into pixel-art upscaling filtering algorithms (**http://en.wikipedia.org/wiki/Image\_scaling**). These have been specifically designed to upscale pixel art, having the properties of (1) retaining the original color palette (aka. no blurring) and (2) removing jaggies (aliasing that occurs due to nearest neightbour sampling).

Some names of algorithms are: Eagle, 2XSAI, Super Eagle, Super 2XSAI, Scale2X, Scale3X, HQ2X, HQ3X, HQ4X, 2XBR, 3XBR, 4XBRZ. They are more or less ordered from simple to complex, with 4XBRZ being my favorite in appearance.

They all work with integer magnification factors (2, 3 and 4). The usual approach for obtaining non-integer magnifications is to take the nearest integer larger than the desired magnification factor and downscale the resulting image (using either nearest neightbour or linear interpolation). An alternative is to take the nearest integer smaller than your desired magnification and add borders around the image. The choice between these two approaches comes down to the style of your pixel art and personal preference.

Edit: I ran your image through an implementation of Eagle, Scale2X and Scale3X I made a while ago. Here are the results in order (magnified by x2 so you can better see what the algorithm does to the pixels). Scale3X is the most complex algorithm, and it also looks best in my opinion. There are way more complex algorithms in the list I mentioned above though, so you'll want to experiment with more of them.
> 2 votes

# Answer
You need to apply a low pass filter before the down-sampling (down-scaling) occurs on the low resolution screens.

I have used simple gaussian blur (convolution transform) with good results:

This was done with a blur radius of 1 pixel.
> -1 votes

---
Tags: textures, sprites, camera, viewport
---


# Question
Title: Algorithm that cover one mesh by another mesh
Suppose I have two meshes (Let call me first MeshShirt and second - MeshBody) Meshes are aligned (if i render both MeshShirt "covers" MeshBody). But some parts of the body are not "under" the MeshShirt (because MeshShirt shape differs from MeshBody)

How can i "pull up" parts of MeshShirt which are under MeshBody and hold other parts in their places? Of course i want save shape of MeshShirt if it possible

I think about following algorithm

1. mark all points of MeshShire which under MehsBody by tracing intersection of its normals and MeshBody.

But if MeshShirt "hidden" parts have complex shape normal tracing will not work. So some way to detect bad points is needed
2. move every marked point to the plane of its nearest triangle of MeshBody.

But i afraid that these algoritm may produce significant deformation of MeshShirt. So some shape preserved deformation is needed too.

Sorry for my poor English and fuzzy problem definition

# Answer
> 1 votes
First, find the average, minimum and maximum distance all vertices in the shirt mesh. Let those be *Da*, *Di* and *Dx*, respectively.

Also let *Dai* = *Di*/*Da* and *Dax* = *Dx*/*Da*.

Then, you test each point of your shirt mesh *Ms* to know if it's inside the body mesh *Mb*, possibly using the Jordan Curve Theorem, which is based on raycasting. Store all vertices which are found to be inside the mesh in a list, then for each vertex *Vc*:

* Get the nearest vertex *Vn* of *Mb*, trace a ray from *Vc* to *Vn*, store the contact point *Pc*
* Move *Vc* to *Pc*

After this, you should have a relatively distorted model of your shirt. You then loop again on each *Vc*:

* For each vertex *Vx* connected to *Vc*:
    + Get the distance of *Vc* to *Vx*
        - If it's greater than *Dx*, move *Vx* to a point *Dax* units away from *Vc*
        - If it's smaller than *Di*, move *Vx* to a point *Dai* units away from *Vc*
    + Repeat step 3 for all the vertices connected to *Vx*

---

I assume you know how to find the distance between vertices, and how to get a new vertex from a vertex, direction and distance. If not, it would be great to learn that.

This should work for most meshes, but it's quite expensive, so I don't recommend doing this at runtime. If possible, run it once just and save the final mesh somewhere you can keep using it without recalculating.

This works the best for meshes with relatively close edge lengths, that is, a even distribution of vertices along the surface, though it works OK for other meshes too.

I hope this is clearer than the discussion in the comments.

---
Tags: algorithm, geometry, 3d-meshes
---


# Question
Title: Split up a string and add each as an item in an array
I have an input string and input the following "2, 4, 5, 7, 10" (for example). How can I split it as an object(item) for a list array? so it would be in each item "2", "4", "5", "7", "10"

# Answer
> 0 votes
```
string     str     = "2, 4, 5, 7, 10";
string[]   tokens  = str.Split( new string[] {", "}, StringSplitOptions.None );

```

Use String.Split. You give it certain characters to "split" at and it returns the tokens. This isn't Unity specific, nor is it game development.

But there's your answer. Next time try describing your problem to Google. You'll get your answer a lot quicker that way.

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


title: Reconstruct shader vertices in OpenGL

text:
# Question
Title: Reconstruct shader vertices in OpenGL
I'm not sure if 'reconstruct' is the correct term for this but essentially what I am trying to do is calculate vertex positions (that are already calculated via shader) on the CPU for the purpose of ray tracing. I need to know the locations of the models so I can detect if my ray passes through them. It would be nice if I could retrieve the values from memory after the the shader has calculated them but it doesn't seem possible - or advisable.
What I have so far looks like it should work but when I trace my ray (that does pass directly through the model) none of the vertices fall inside the model.

**Create the ray** (Tested by drawing a line between far/near and it works fine):

```
public float[] getPickingVector(float[] modelview,
                                float[] projection,
                                int[] viewport,
                                float winX,
                                float winY) throws Exception {

    float[] mat4Tmp1 = new float[16];
    float[] mat4Tmp2 = new float[16];
    float[] vec4Tmp2 = new float[4];

    FloatUtil.mapWinToObjCoords(winX, winY, 0, modelview, 0,
            projection, 0,
            viewport, 0,
            nearVector, 0,
            mat4Tmp1, mat4Tmp2);

    FloatUtil.mapWinToObjCoords(winX, winY, 1, modelview, 0,
            projection, 0,
            viewport, 0,
            farVector, 0,
            mat4Tmp1, mat4Tmp2);

    // save the results in a vector, far-near
    destVector[0] = farVector[0] - nearVector[0];
    destVector[1] = farVector[1] - nearVector[1];
    destVector[2] = farVector[2] - nearVector[2];

    return destVector;
}

```

**'Reconstruct' the model vertices** by reading back the values of the vertex buffer that are keyed on the index buffer. I have stepped through the loop and the code does read back the vertex buffer values in the correct order:

```
//check by pairs of triangles that create a square.
public boolean findIntersection(Wh w, float[] mvp){

    float[] a = new float[4];
    float[] b = new float[4];
    float[] c = new float[4];

    boolean rslt = false;

    //init boundary vars.
    float[] tmp = {-2000,-2000,-2000};
    float[] tmp2 = {2000,2000,2000};

    //loop thru each triangle.  Arrays a,b and c each represent
    //a vertex of one triangle.  The are 12 in total creating a
    //box.
    for ( int i = 0; i < w.idxBuffer.length; i += 3  ){
         a[0] = w.vertBuffer[ (w.idxBuffer[i + 0] * 3) + 0];
         a[1] = w.vertBuffer[ (w.idxBuffer[i + 0] * 3) + 1];
         a[2] = w.vertBuffer[ (w.idxBuffer[i + 0] * 3) + 2];
         b[0] = w.vertBuffer[ (w.idxBuffer[i + 1] * 3) + 0];
         b[1] = w.vertBuffer[ (w.idxBuffer[i + 1] * 3) + 1];
         b[2] = w.vertBuffer[ (w.idxBuffer[i + 1] * 3) + 2];
         c[0] = w.vertBuffer[ (w.idxBuffer[i + 2] * 3) + 0];
         c[1] = w.vertBuffer[ (w.idxBuffer[i + 2] * 3) + 1];
         c[2] = w.vertBuffer[ (w.idxBuffer[i + 2] * 3) + 2];
         a[3] = 1;
         b[3] = 1;
         c[3] = 1;

         //****Here is where I suspect my problem is **********
         //To rebuild the vertices I multiply the vertex from the
         //vertex buffer by the model/view/projection matrix, mimicking
         //what is done in the shader:
         //      gl_Position = MVP * vec4(VertexPosition,1.0);
         //My hope is that this will provide me with the correct positioning
         //of the model so the ray trace will work.
         FloatUtil.multMatrixVec(mvp, a, am);
         FloatUtil.multMatrixVec(mvp, b, bm);
         FloatUtil.multMatrixVec(mvp, c, cm);

         //The following creates max/min boundaries used to test for
         //a point being inside the box.
         //high x values
         if (tmp[0] < am[0]){tmp[0] = am[0];}
         if (tmp[0] < bm[0]){tmp[0] = bm[0];}
         if (tmp[0] < cm[0]){tmp[0] = cm[0];}

        //high y values
         if (tmp[1] < am[1]){tmp[1] = am[1];}
         if (tmp[1] < bm[1]){tmp[1] = bm[1];}
         if (tmp[1] < cm[1]){tmp[1] = cm[1];}

        //high z values
         if (tmp[2] < am[2]){tmp[2] = am[2];}
         if (tmp[2] < bm[2]){tmp[2] = bm[2];}
         if (tmp[2] < cm[2]){tmp[2] = cm[2];}

         //low x values
         if (tmp2[0] > am[0]){tmp2[0] = am[0];}
         if (tmp2[0] > bm[0]){tmp2[0] = bm[0];}
         if (tmp2[0] > cm[0]){tmp2[0] = cm[0];}

        //low y values
         if (tmp2[1] > am[1]){tmp2[1] = am[1];}
         if (tmp2[1] > bm[1]){tmp2[1] = bm[1];}
         if (tmp2[1] > cm[1]){tmp2[1] = cm[1];}

        //low z values
         if (tmp2[2] > am[2]){tmp2[2] = am[2];}
         if (tmp2[2] > bm[2]){tmp2[2] = bm[2];}
         if (tmp2[2] > cm[2]){tmp2[2] = cm[2];}

    }

    //The following traces the ray until one of the points falls
    //within the boundaries of the box.
    float fract = (nearClippingDistance / (farClippingDistance));

    System.out.println("x:" + tmp[0] + "  " + tmp2[0]);
    System.out.println("y:" + tmp[1] + "  " + tmp2[1]);
    System.out.println("z:" + tmp[2] + "  " + tmp2[2]);
    //boolean init = false;

    float idx = 0;
    float[] mult = new float[3];
    float[] t = new float[3];
    for (idx = fract; idx <= 1; idx += fract) {
        mult[0] = farVector[0] * idx;
        mult[1] = farVector[1] * idx;
        mult[2] = farVector[2] * idx;
        VectorUtil.addVec3(t, nearVector, mult);

        System.out.println("x:" + t[0] + "  y:" + t[1] + "  z:" + t[2]);

        if (((t[0] <= tmp[0]) && (t[0] >= tmp2[0])) &&
            ((t[1] <= tmp[1]) && (t[1] >= tmp2[1])) &&
            ((t[2] <= tmp[2]) && (t[2] >= tmp2[2]))){
            //ray intersects this box.
            rslt = true;

        }
    }

    return rslt;

}

```

I have also tried many open source libraries that provide bounding box detecting / plane intersection / ray tracing but none of them work I think because my vertex values are somehow incorrect. Does anyone see a problem with what I am doing here?

# Answer
> It would be nice if I could retrieve the values from memory after the the shader has calculated them but it doesn't seem possible - or advisable

But, it IS possible, and I would advise it:

https://www.opengl.org/wiki/Transform\_Feedback
> 4 votes

---
Tags: opengl, java, glsl, jogl
---


# Question
Title: How does a general Renderer::drawRect(0, 0, 100, 100) handle VBO's?
Lots of game engines and GUI systems have a general Renderer class with functions like:

```
renderer.drawRect(0, 0, 100, 100);
renderer.drawText(204, 452, "Hello, world!");

```

I understand how this could easily be done in old immediate-mode OpenGL 2.1, but now that VBO's are the norm, could someone explain how these renderers work internally? They surely aren't creating and deleting a VBO quad everytime `drawRect()` is called, right?

Keeping one VBO and updating the vertex data is out of the question, as it would be cool to set a different shader, texture or colour in between the `drawRect()` calls.

Is instancing a (0, 0, 1, 1) rect and then scaling up the way to go?

Any pointers?

# Answer
There are many cleaver ways of drawing 2D geometry with modern shader-centric OpenGL. The method that I usually choose and find the most straightforward is with simple *batching*.

* On startup, create a system-side buffer of 2D vertexes (the batch). This buffer can have a fixed size or can be resizable (like a `std::vector` in C++). Also create a VBO with the same size. Indexed or not, its your choice.
* In a game frame, every `drawRect()` or `drawText()` actually writes the vertexes and material properties to this system-side memory buffer.
* At the end of every frame, map the VBO and upload the batched vertexes to it, or update it using `glBuffer[Sub]Data`.
* Render all your UI/2D stuff with a single draw call and clear the system-side vertex batch for the next frame.

This setup has two main advantages:

1. Reduced number of draw calls, you can draw everything that shares the same material properties with one call.
2. Single update of the GL buffer: You centralize your update to a single place. This will promote CPU cache efficiency and will also require very few GL API calls. There are several ways to optimize this step even further with newer OpenGL versions.
> 4 votes

# Answer
Create a program that takes the relevant parameters as uniforms and pass those.

Then the size and position of a rect can be passed as a single vec4 uniform and you only need to pass a single VBO that is `0,0; 0,1; 1,1; 1,0` (or `0,0; 0,1; 1,1; 0,0; 1,1; 1,0` for non indexed draws)

```
in vec2 input;
varrying texCoords;
uniform vec4 posSize;//xy is the position zw is the size

main(){

    gl_Position = vec4(input*posSize.zw + posSize.xy, 0, 1);
    texCoords = input;
}

```

Then most of the magic will happen in the fragment shader where you will be sampling textures and such based on `texCoords` and your uniforms.
> 2 votes

---
Tags: opengl, vbo
---


title: OpenGL generate hills looking vertices

text:
# Question
Title: OpenGL generate hills looking vertices
I want to generate a terrain which looks like hills. Some sort of sine waves. Should be as simple as possible. But I can not figure out how. I get very scary results, which are nothing worth. I need to have vertices, normals and the indices of the vertices.

```
for(int i=0; i < size; i++) {
for(int j=0;j < size; j++) {
verticesList.add((float) j);
verticesList.add((float)Math.sin(j) * 1.5f);
verticesList.add((float) i);

normalsList.add((float) j);
normalsList.add((float)Math.sin(j) * 1.5f);
normalsList.add((float) i);

indicesList.add((byte)(i+j));

verticesList.add((float) j);
verticesList.add((float)Math.sin(j) * 1.5f);
verticesList.add((float) i+1);

normalsList.add((float) j);
normalsList.add((float)Math.sin(j) * 1.5f);
normalsList.add((float) i+1);

indicesList.add((byte)(i+j + 1));
}
}

```

I know that this is not the way how normals a "calculated".

P.S.: I need something like this:

edit:

How do I compute the normals?

# Answer
> 1 votes
I recall reading this: alternative method (there a few) for terrain assignment; I suggest you review and adopt this approach instead of your initial attempts. This approach differs from with your method in that the example uses an existing greyscale bitmap as the heightfield and reads the image-data to assign the elevation of the 'hills.'

However, this difference is easily replaced with your method for sinusoidal calculation of the heightfield. In the author's code, the block where the imagedata is retrieved and assigned into the terrain matrix looks like this:

> ```
> for (int z = 0; z < MAP_Z; z++)
> {
>     for (int x = 0; x < MAP_X; x++)
>     {
>         terrain[x][z][0] = float(x)*MAP_SCALE;
>         terrain[x][z][1] = (float)imageData[(z*MAP_Z+x)*3];
>         terrain[x][z][2] = -float(z)*MAP_SCALE;
>     }
> }
>
> ```

You should replace the middle assignment expression `terrain[x][z][1] =` with your sine-map instead of the imagedata call so it looks like this:

`terrain[x][z][1] = float(sin(myradians*(z*MAP_Z+x)))*MAP_SCALE;`

```
  and **BEFORE** the loop, assign the variable myradians:

```

`myradians = float(PI*(angle-90.0f)/180.0f);`

so that the sin() function operates correctly in radians.

After that change to the codeproject example, I think you will be able to render a hilly terrain. Then you can make adjustments to the single line to vary the magnitude and offset of the sine-wave.

# Answer
> 0 votes
this looks suspect:

```
indicesList.add((byte)(i+j));

```

I'd expect the index to be something like:

```
indicesList.add((byte)(size*i+j));

```

but if size\*size\>255 then you need to upgrade the indicesList to contain a short or int, otherwise they just won't fit.

---
Tags: opengl, java, terrain
---


title: Formula for Planetary Alignment

text:
# Question
Title: Formula for Planetary Alignment
I am attempting to create a game where there is a universe of two 16-bit addresses ranging from (-32768, -32768) to (32767, 32767), or in hexadecimal, each value can run from $8000 to $FFFF then 0 to $7FFF, although the universe is probably not going to use the whole 4 billion possible addresses.

What I want is for any location, given the two values, to return a value from 0 to around 15 or 20. Where:

* 0 is empty space.
* 1 to 9 are planet technology levels, with a level 1 planet being less developed than 2, which means a level 5 planet can build up to a level 5 hull, warp drive or shield, but to upgrade to level 6 requires going to a level 6 or higher planet, or possibly paying a horribly high price.
* 10 and above are for anomalies, e.g. black holes, suns and other things which have an effect such as random movement or increase in power.

While the most common value will be zero, the universe should have some minimum non-zero locations, e.g. 10% or 20% or some reasonable number of the locations are planets or anomalies.

Note the alignment factors are not random, the value should be calculated so that -60,12 returns the same planetary value any time it's called. I've seen this done in a simple formula amounting to less than 5 lines of code but that was 30 years ago, and I don't have the math to do the calculations myself.

Any help would be appreciated.

# Answer
I would suggest Perlin Noise to do this.

Basically, generate N perlin noise values for each different factor, or, if you prefer 1 perlin noise value that gets hashed to a class (like planet, or emptiness):

```
int x, y; // coordinates
float scale; // The scale of the universe. Adjust this number to affect smoothness.
float value = Perlin(x * scale, y * scale);
float threshold; // The likelihood of an object, between 0 and 1

// If the value is less than a threshold, we have some kind of object
if (value < threshold)
{
   // This hashes to a number between 0 and 10
   int class = (int)(10.0f * (1.0f - threshold) * value);
   return class;
} else return 0; // Otherwise we have emptiness

```

This will give you:

* Consistency. The same result every time you sample an X, Y
* Local smoothness. You can, for instance, make stars appear in clusters.
* Apparent randomness.
> 2 votes

# Answer
What you're describing is procedural generation (of some kind of universe in this example).

This is actually rather trivial to do. Basically you'll just have to calculate everything on basis of your coordinates. This can either be done by simple math or by using the coordinates as the seed for your random number generator.

In your example, you want 20 % of your universe to contain something. So all you have to do is something like this:

```
$not_empty = ($x + $y << 1) % 100 < 20;

```

Now that you've determined that the space is not empty, you're able to do the next step, the technology level/anomaly type you've described:

```
$type = ($x + $y << 1) % $number_of_types;

```

Of course you can do more complicated things than just adding `$x` and `$y` (like calculating some hash). Just keep in mind that the result should be different, even if you change `$x` or `$y` only.

---

If you'd like to use random numbers, you could do something like this:

```
// Init the seed based on the coordinates
srand($x + $y << 1);

$not_empty = rand(0, 100) < 20;

$type = rand(0, $number_of_types);

```

Here's a short example on Ideone.com that will show you "scan results" of a given number of systems. They should always return the same results, no matter how often or where you retrieve them (at least as long as the host running the script is the same).
> 0 votes

# Answer
tl;dr code example with md5 (you can run it here):

```
   function getHashTail($pair)
   {
     $res = hexdec(substr(md5($pair), -4)) % 1024;
     return $res < 100? dechex($res % 16) : ' ';
   }

```

Usage example:

```
<html>
<head>
<title>Hash space</title>
  <style>
    div {
      text-align:center;
      vertical-align:top;
      display:inline-block;
      border: 1px solid black;
      width:32px; height:32px;
    }
  </style>
</head>
<body>
<?php
   function getHashTail($pair)
   {
     $res = hexdec(substr(md5($pair), -4)) % 1024;
     return $res < 100? dechex($res % 16) : ' ';
   }

   // Sample usage
   $seed = "ABCD";
   for ($i = 10; $i; $i--)
   {
     echo "<br>";
     for($j = 10; $j; $j--)
     {
       echo '<div>' . getHashTail("$i $j $seed") . '</div>';
     }
   }
?>
</body>
</html>

```

Explanation:

To get the same results for each pair without storing the results in memory you need to use a random seed or simply put a hash function (like md5 for instace). You can then manipulate the input or output from the hash with a seed to get different results.
> 0 votes

---
Tags: physics, php
---


title: Box2D meters and pixels

text:
# Question
Title: Box2D meters and pixels
I am confused about pixels and meters in Box2D. I know that Box2D work only in mters so I need SCALING FACTOR. How big I need it? For example I want that from my mouse coordinates position X and Y for example(1527, 30) throw an Box2D object how I need to do that? if my scaling factor is `private final static float PPM = 1/100f;` so my

> x = 152,7, y = 3meters

Here is my code

```
private void setBox2DFigures(){
        world = new World(new Vector2(0,-9.81f), true);
        rend = new Box2DDebugRenderer();
        cam = new OrthographicCamera(); // Camera
        body = new BodyDef();
        bodyPhysics = new FixtureDef();

        CircleShape c = new CircleShape();
        body.type = BodyType.DynamicBody;
        c = new CircleShape();
        c.setRadius(20*PPM);
        c.setPosition(new Vector2(Gdx.input.getX()*PPM, Gdx.input.getY()*PPM));
        bodyPhysics.shape = c;
        world.createBody(body).createFixture(bodyPhysics);
}

```

and here in a draw method I want to coin position set to my mouse position

```
public void draw(){
    c.setPosition(new Vector2(Gdx.input.getX()*PPM, Gdx.input.getY()*PPM)); // mouse coordinates * PPM
    rend.render(world, cam.combined);

}

```

But I don't see anything in my screen. Whats wrong? How I need to choose My scaling factor(PPM)?

here's my main

```
public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();

        cfg.title = "Catch Me!";
        cfg.width = 1800; //1800
        cfg.height = 900; //900

        new LwjglApplication(new Game(), cfg);
    }
}

```

# Answer
When using box2D, the camera you use to render your world should not be your resolution size, it should be your resolution divided by PPM. So when you are making your cam, do something like this:

```
public static final int PPM = 16; //This means that for every meter in your box2D world there are 16 pixels on your camera. If you have a body at position 1,1 and you draw an image at the location of this body the image will be drawn 16 pixels over and 16 pixels up

OrthographicCamera camera = new OrthographicCamera(Gdx.graphics.getWidth() / PPM, Gdx.graphics.getHeight() / PPM);

```

Now, when you are setting the position of bodies in your world, you should not use PPM at all. PPM should only be used when you make the camera.

If you wanted to set a body's position to the coordinates of the mouse, you would set it using a vector that has been projected onto the camera. For example:

```
Vector3 mousePos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);

Vector3 worldPos = camera.project(mousePos); //Now your mousePos is in world coordinates instead of screen coordinates

```

Then do:

```
body.transform(worldPos.x, worldPos.y, body.getAngle());***

```

\*** see below for notes on the body

A few things to note:

When you create your body in setBox2DFigures, you should call shape.dispose() as soon as your are finished with it. This means as soon as your body has been created in the world you dispose it. The object you should be working with in the box2D world is NOT the shape, it is the Body object returned from the `world.createBody(...)` method.

So

```
BodyDef bDef = new BodyDef();
bDef.type = BodyType.DynamicBody;
bDef.position.set(initPosX, initPosY);

CircleShape shape = new CircleShape();
shape.setRadius(0.5f);//half a meter radius

FixtureDef fDef = new FixtureDef();
fDef.shape = shape;

Body body = world.createBody(bodyDef);
body.createFixture(fDef);

shape.dispose();//Since you have created the fixture in your body, you are finished with the shape

```

I hope this helps!
> 4 votes

---
Tags: libgdx, box2d
---


# Question
Title: Optimal OpenGL 2D Sprite Batching (Best Practice)
I am working on simple 2D engine using OpenGL (3.3+) for rendering and was wondering what the optimal method of sprite batching would be. I plan to put all sprites into one (or fewer) texture atlases. Unsurprisingly, each sprite consists of 2 triangles and 4 texture coordinates. For simplicity, let's assume only the sprites are not animated for now.

Now to my question, I do not know what would be the optimal way to draw them. As far as I was able to dig up, I have two options:

1. Draw each sprite separately, which would allow me to modify the position/rotation/scale of each sprite within the shader via MVP matrices. This also means that I would not need to update the sprite data buffers (vertex pos. & tex. coords) on GPU.
2. Stuff all sprites' data into a single VBO and draw them all with one `glDrawElements` call (assuming they use the same texture atlas and shader). However, I would then need to update the VBO every frame (or at least the changed parts, which also means that I would have to watch every sprite's state).

Which of these options is better from a practical point of view? Or is there any other method to achieve what I'm trying to do?

# Answer
You aren't limited to having only one MVP per VBO. So you would not in fact need to update the VBO every frame just because you stuff all of your sprites into a single VBO. What I do is store an instance ID with each vertex, which changes only on a per-model basis, and use those instance ID's to index into a uniform array of mat4's, one for each "instance."
> 2 votes

# Answer
"Which of these options is better from a ***practical*** point of view?"

I'll interpret the word "practical" here to be distinct from "theoretically highest performance on a computer"...

At two triangles per sprite, recomputing all the vertices on the host CPU will be not that expensive, & easy to think about.

Or, since all the geometries are the same (two triangles), you may also be able to use glDrawElementsInstanced() which is similar to @Nox's approach.

But really ("practically") start with any technique you like, and if it works even a little, move on. Make sure that somewhere in your code is the high level abstraction, like sprite-\>setPositionAndRotation(x,y,theta) or whatever. Because getting your game up and running is more important. Later on, optimizing this one detail *if* *needed* can be done.

I use a variation of @Nox's answer to move \>10000 50ish triangle objects (each different) around in 3d; actually I use a texture rather than a uniform array, but same idea with "instance Id". But I started with using many draw calls (ok up to around 1000 draws), and then manipulating the vertex positions directly in one big buffer, which was fine until I got up in the many thousands...
> 2 votes

---
Tags: c++, opengl, 2d, sprites, rendering
---


# Question
Title: How to change render states only when necessary?
Earlier, I have been setting render states (shaders, shader resources, etc.) without checking if it is really necessary. Maybe they had been bound earlier and I could use them without setting them again.

So now I am checking for currently set render state before setting it. If there is a mismatch, then I set it. Setting a pixel shader for example:

```
typedef ID3D11DeviceContext*        DeviceContext;
typedef ID3D11PixelShader*          PixelShader;

inline static void BindPS(PixelShader shader, DeviceContext context){
    if(context!=nullptr){
        PixelShader s;
        context->PSGetShader(&s,nullptr,0);
        if(s!=shader)
            context->PSSetShader(shader, nullptr, 0);
        if(s!=nullptr)
            s->Release();
    }
}

```

I wonder if it is a welcome practice to get current render state from the device context context so often, or should I roll my own solution for checking them? Keeping pointers for currently bound states for example and checking with those?

I ask this now, because I only started implementing this for some states (PSSetshader and PSSetShaderresources), and I have a lot more, so I would opt-out early if this method could be problematic.

# Answer
`PSGetShader` (and in general, all state getters in D3D) are not intended to be called at high frequency. You should do dirty state tracking, and you should implement it yourself. Using `PSGetShader` will at a minimum create the additional overhead of the `AddRef` which you don't need for dirty state tracking.
> 1 votes

# Answer
Dispatch a message every time you have to change render state and add a corresponding handler. This way you do not have a check in every frame / game step, but it is rather handled like a click would be, it is recognized when in the message queue and handled correspondingly.
> 0 votes

---
Tags: directx11
---


title: How to prevent constant movement

text:
# Question
Title: How to prevent constant movement
So I have this code for moving a pointer up and down in a menu. The only problem is it moves way too fast to even stop on any of the selections. It does go to each one, but even just a quick tap of the button the pointer moves down 3 selections. If you go up and down a few times it will go to the selection you want, but it's a hassle. So is there a way to maybe disable movement for about half a second?

```
        if(Game.stateEngine.menuState == StateEngine.MenuState.ITEM)
        {
            if(Input.dn && Game.pointer.y < 430)
            {
                Game.pointer.y += 15;
            }
            if(Input.up && Game.pointer.y > 172)
            {
                Game.pointer.y -= 15;
            }
            if(Input.x && Game.stateEngine.menuState != StateEngine.MenuState.MAIN)
            {
                Game.stateEngine.menuState = StateEngine.MenuState.MAIN;
                Menu.firstPass = true;
            }
        }

```

# Answer
> 1 votes
Use a timer (delay, countdown, whatever you want to call it). Each time a menu movement is applied, reset the timer. Do not allow another movement until the timer has expired.

Unlike the event-based approach, this still allows you to hold a key and move through a menu, but only at a limited speed.

An implementation might look like:

```
double m_LastMove = 0;
double const kMoveSpeedSeconds = 0.5;

void MoveUp() {
  double now = GetTime();

  if ((now - m_LastMove) >= kMoveSpeedSeconds)
  {
    m_Item = m_Item - 1;
    m_LastMove = now;
  }
}

```

That allows a fixed slow speed of scrolling through menus and it requires no continuous update loop on account of using absolute times instead of deltas. Your game might prefer 64-bit integers or some other type for absolute times; just don't use a single-precision `float`.

# Answer
> 0 votes
These kinds of problems usually happens when the key state is checked at each frame.
What you want to do is use the OS event that signals a "key press", or "key down". Note that if you do the same for the mouse, the "mouse **UP**" event is the one, contrasting with key input.

Then the repetition will happen after a delay, this is handled by the system input thread, or they keyboard class driver, who knows. Of course you could emulate this behavior as well, by using chornometers that checks the timeline of the repetition state machine, but using system settings is nice.

---
Tags: java
---


# Question
Title: Is there algorithm for boxcasting or thickray casting?
I am not sure what the correct name is called but here is my problem: I have implemented a casting ray function that works as expected. However, because I am using a loose grid structure, (ie, objects that overlap multiple grids are only put into one grid), the ray cast may miss certain objects. What I need, I think is a box casting where I need to get every grid the box hits from its initial position to final position. Does anyone have such algorithm? Or pointing out to a solution to this problem, thanks!

This pic from N tutorials is a nice summary of this problem:

My ray cast implementation only hit the blue cells but as you can see, it may miss certain objects. They are only put into the grid where the x is.

Just to add I will be using this in a heated loop and so I have the additional requirement that this must be done efficiently.

EDIT: this picture illustrates why I think a box casting would work for loose grid: (The box must be bigger than the objects contained in the grid.)

# Answer
As per @Krom Stern's suggestion, this is my solution to this problem.

An incomplete, but working box cast algorithm for uniform grid: http://jsfiddle.net/d5ab67fj/1/. It currently is missing the end point cases and it only increment in X direction, but the algorithm itself is working. It will not miss any cells that the box would hit and it will not include any cells that the box would have missed (save for the end points in the incomplete implementation).

Also, why I choose to use this method rather than a non loose grid:

1) All my objects contained in grid are strictly smaller than grid size. This has important performance advantage because a large object requires many cells to be updated whenever it moves. If you need to support DYNAMIC objects with vastly different sizes, I highly reccomand use multiple uniform grid of various sizes rather than 1 size fit all structure such as quad/octree.

2) All my objects in the said grid are expected to require grid cell updates at every game step; as you can imagine, this is more costly in a non loose grid.

3) I need to call raycast less often than objects requiring updates.

4) Although in a loose grid, you need to hit more cells for raycast/collision tests, every cell contains less objects on average (due to the non overlapping nature). This may or may not make a difference depending on your needs.
> 1 votes

# Answer
Your problem is not the ray cast, but that your grid cell doesn't reflect its actual state or in other words it might contain objects that it doesn't know about. When a certain object intersects a grid cell, the grid cell ***should*** know about it, this way when an object intersect multiple grid cells each grid cell should have a reference to that object, this should be done when the object position is updated.

If you don't want to update the grid cells, one possibility is to check the 1st neighbors for each cell you hit.

I also want to assert that having a thick (or cylindrical) ray cast is not the correct solution for your problem, it will be much more expensive to cast a cylinder or use multiple rays each time than the normal ray cast, the correct way to do it, is to correctly update the grid cells.

Another alternative is to use Octrees this way each grid cell will be strictly bigger than the objects inside of it, and you will have hierarchical stricture. The problem with octrees is that they are much harder to update.
> 4 votes

# Answer
Given that you cast just one ray and that objects can take no more than closest neighbor tiles in any of 8 directions, you just need to expand your resulting list of tiles 1 tile in every direction. Either while you detect the tiles rays goes through, or after you have the whole list - depends on your needs/constraints.
> 0 votes

---
Tags: collision-detection, grid, raycasting
---


title: Why don't more games use vector art?

text:
# Question
Title: Why don't more games use vector art?
It would seem to me that vector art is more efficient in terms of resources/scalability; however, in most cases I have seen artists using bitmap/rasterized art. Is this a limitation put on the artists by the game programmers/designers? As a programmer I think vector art would be more ideal, since it allows for scaling up resolution without having to recreate the art, creating really large graphics or causing graphics to become blurry.

The questions: why aren't more people using SVG/AI to create 2D game art? Would it actually be preferred (and who prefers it)? Are bitmap graphics a standard or a limitation (or maybe neither)?

Background: I am working on an engine, and I had some kinda cool ideas for vector based graphics; however, I don't want to piss off artists in the future.

I guess this is more a question centered around pragmatism and developing games.

# Answer
> 60 votes
Unlike other art forms, vector art requires extremely high precision, making it unsuitable for many art styles. Basic shapes and such are easy using Vector art but it's just a pain to add small details which would be really easy to paint. So its kinda restricted to very simple "symbolic" styles. For everything else painting just works better.

What vector art is suitable for, is icons and design and there you won't find many artists who would use something different.

By the way: Scalability isn't really a problem for raster graphics either, painting in 10x resolution isn't that much of a difference than painting in the resolution it is going to be displayed. Something which is done quite a lot nowadays (often advertised as "HD-Graphics").

# Answer
> 42 votes
Vector graphics are usually more efficient than raster graphics for storage (ie. the filesize is smaller) but considerably less efficient for performance (ie. how much time it takes the computer to draw the image).

In order to display an image the computer must rasterize that image (ie. calculate the pixels in the image). Since raster graphics are by definition already rasterized there is not much calculation the computer must do before dumping the pixels to the back buffer.

However this issue depends on if you are talking about using vector graphics in real time in the game, or if you are talking about the artists drawing in Illustrator and then exporting to raster formats like png.

# Answer
> 17 votes
In fact, there are a number of 2d games that do use what amounts to vector art; Capcom's Ghost Trick:Phantom Detective, for instance, essentially generates its in-engine characters as vector graphics. (To be more precise, I believe they're given as flat-filled polygonal regions, which in this case amounts to the same thing). More broadly, polygonal models in general can be thought of as 'vector' data - they represent the vertices, edges and faces of an object - as opposed to (screen-resolution) 'raster' data, so in some ways most 3d games *are* using vectorized data descriptions.

But I suspect your question is more about 2d art, and there several factors come into play. As Mr. Beast says, small details make vector art quite a bit trickier to construct; imagine something like a grenade belt on a character, where even a bit of clever copy-paste of individual grenades still isn't going to save a whole ton of time on the effort. I think the bigger issue, though, is that vector graphics take some control *away* from the artist; as you note, vector art may look substantially better scaling up, but the real issues are at lower resolutions, where the fiddly details of rasterization can substantially change how an image looks. Imagine a character's eye, for instance; the outer boundary might be an oval no more than ten or twenty pixels across and possibly just a small handful of pixels in height. At those resolutions, how the vector data - be it lines, circular arcs or Bezier curves - is rasterized becomes a critical issue, and unless your artists can work directly in-engine - which essentially means creating an entirely new vector drawing program - then they have a hard time guaranteeing that the appearance of their objects in-game will match the appearance in their tool. What's more, just appearing correct at one resolution is no guarantee whatsoever that they'll appear correct at any other; again, the scaling works well when you're dealing with objects where the details are dozens or hundreds of pixels in size, but as you get down towards smaller-scale features then your scaled rendering runs into exactly the same rasterization details.

That said, vectorized rendering isn't *always* inappropriate, and it can often be a stylistic choice to excellent effect. But it's not a panacea for the issues you raise with raster graphics, and it raises new issues of its own too.

# Answer
> 7 votes
I believe that it's mostly a combination of tradition, tools and technology, and expectations, which all feed back into each other.

* tradition - raster graphics were the easiest way to render detailed images for most of the history of game development and so that way of working took hold among programmers and artists, dating back to a time before artists were even widely involved in games. Existing code revolves around bitmaps, and existing artists learned to work with bitmaps. And it's always expensive to re-train and re-program.
* tools and technology - artists tend to start out with bitmap graphics and photo-editing tools by default, perhaps because it more closely resembles traditional media, but whatever the reason the result has been that good vector editors are less common and less well-known than good bitmap editors. Plus it's only relatively recently that the technology for rendering vectors has been fast enough for games - devs using Flash for games were usually using the bitmap interface until recently, and Canvas/SVG type technologies are also relatively new in terms of efficient support. Plus there isn't really a dominant vector rendering library (that I know of) which people can widely use, compared to alternatives like SDL, XNA, pygame, etc., so programmers don't see this as a very viable route. But it's not programmers necessarily enforcing this on artists - usually artists are far more comfortable with bitmap editing. (Artists are not always graphic designers, after all.)
* expectations - game players have consistently expected more and more realistic-looking games as technology advances. This may have been driven by the players themselves, or by publishers and marketing, or by the hardware manufacturers eager to sell graphics cards, or by pundits who think games are basically interactive films, or some combination of the above. But regardless of who caused this, it is a factor, and so the market generally pushes towards realistic graphics. Vectors are poorly suited to realistic graphics and so it is only relatively recently, where graphics are converging on photorealism and thus losing identity, that there's a resurgence in stylised graphics and an interest in different presentation styles such as vector art.

The interesting thing about these points is that you can see that things are changing. Maybe the use of vector graphics will pick up in the near future. Modern graphics hardware is well-suited to vector graphics, so the issue is really just about creating a good technology chain to get art into the game and onto the screen.

# Answer
> 5 votes
Imho it's the difference in approach... it's more about building your art rather than drawing it. I prefer vector art for it's ease of changing, reusing, scaling and the cartoony feel I can create with ease. Most 'trained' artist prefer a drawing and painting approach while a lot of graphic artist like to use vectors.

Check out my blog: http://2dgameartforprogrammers.blogspot.com.au/

It's helpful to start at the beginning and read the earlier tutorials first. :)

# Answer
> 2 votes
I read an article called Icon Design: Bitmap vs Vector a while back which shows the clarity of detail that gets lost when scaling a vector image. It's not that any loss occurs, it's that it can be finely tuned as a bitmap.

Take a look at this example of a printer icon (the circled image is the master in each case):

The sweet spot is to scale using vector then adjust with raster. So I guess what I'm saying is that they could be using vector but the end result is raster.

# Answer
> 2 votes
It's primarily a technical issue that most companies won't use pure vector art in their games. I know many artists who make their creations in Flash or Illustrator, only to pump out a rasterized image that gets slapped on a polygon sprite. It's just a technical hurdle that most large companies aren't too keen on trying to figure out.

Below is an example of an animatable character, made in AI, with about 13 moving parts. It would be great to be able to use this, but we had to painstakingly place each piece inside of their own separate image. The only benefit was that we had these assets ready to be scaled for any marketing art.

Another reason it may not be more popular is that the EPS format has different standards that AI. So all the bells and whistles artists like to put into their images get stomped out when converted as EPS.

Ultimately, I don't know what it takes to implement vector art into a game, but I know for a fact that most engineers I've worked with opted to just spit out a png instead of deal with it.

# Answer
> 1 votes
I can't speak for everyone, but from my personal experience, vector art programs (read: Inkscape, the only one I've tried) are harder to use and aren't quite as intuitive as bitmap graphics programs. Everybody understands the paintbrush and the bucket. Curves are harder.

---
Tags: 2d, architecture, animation, art
---


# Question
Title: How to make Volume Heat Distortion effect in OpenGL?
I'm working on adding volume effects to an existent, open-source game engine. At the moment, the engine only supports two dimensional "thruster" bitmaps with a planar heat distortion drawn over the bitmap.

Is it possible to make a Volume filling Heat Distortion? If so, what would be the general idea behind it?

# Answer
> 1 votes
I think you have two options. (1) You could go for a view-space effect where you render everything first and then apply the heat-distortion as a post-processing effect to the 2D rendered scene. (2) Alternatively you could apply the effect in world space through vertex displacements in the vertex shader stage.

(1) View-space distortion could make use of the depth buffer to estimate the depth of objects, as jzx mentions. The advantage of this approach would be simplicity, as you are just operating on a part of the final 2D projected scene - i.e. a zone of pixels. The disadvantage you only have information of the nearest polygon for every pixel. This means distorting a foreground object can never reveal objects located behind it. This effect might therefore look give the impression of a fake, flat effect.

(2) By working in world-space, you can apply distortions to the vertices of all objects. The advantages are: 1. distorted objects can reveal objects behind them, 2. distorting of vertices is very efficient compared to distorting individual pixels (as the rasterization process, in hardware, will take care of all fragments inbetween the vertices) - unless you have a scene with (extremely) many overlapping objects, 3. you can use a 3D function to drive the intensity of the distortion throughout space, which seems very elegant as compared to using a bounding volume. 4. the effect is applied in 3D, meaning distant objects will natrally have less distortion than near ones, solving the problem of the "fake, flat distortion effect".

In summary, you can go for 2 broad approaches: distortion in view-space and distortion in world-space. I would use the latter for better visual results, more elegancy and likely more performance.

---
Tags: opengl
---


# Question
Title: AI algorithm for avoiding bullets in a shoot-em-up game
I am working on a shoot-up-game in XNA, it is going to be my final project in school. I was thinking of utilizing the minimax algorithm for AI agents for making tactics. However, I realized that the most important issue in such a game is to avoid bullets(fired by the player). An AI agent making tactics but no good at avoiding bullets would be useless in a shoot-em-up game I guess.

So, I need your help about what algorithm to utilize. It's not going to be a bullet storm like game, but it's fast(thanks to XNA). I have read about using threat maps and also pathfinding algorithms but couldn't figure out which one is ideal in such a game. I mean it needs to be simple enough for a fast paced gameplay, but it should also help AI agents act intelligently.

# Answer
You could just keep it simple. Create a frustum (smaller than view frustum) to calculate a sort of target area for the player. If the enemy is in that frustum, they should stay in cover (for a period of time, not forever). Then make sure you're A.I. always try to spread out.

If they are always trying to use some tactics then you should be able to find out where you want them to be and create a path for them to that point. So they will always be trying to follow their path to that point. If you use the frustum to tell them to take cover then it could look effective. They move a bit along the path, then their in sight so they instantly take cover.

It should be smart enough to look compelling, but dump enough to give the player plenty of time to shoot them. Also, if their popping up when your not looking, it means it will drive the player to look around a lot, which will add to the sense of vertigo in your fast paced shooter.

The main problem, I think, will be keeping a track of the nearest bit of effective cover to get them to run to when their being aimed at.
> 3 votes

# Answer
I don't think you've got your answer since you're asking about dodging bullets (and not general avoidance ai behaviour).

There are many simple ways to deal with that, each one is appropriate for a different scenario.

1- trace a ray from all bullets towards their respective progrades and with the ray magnitude (distance) relative to their velocity PLUS (or TIMES) the inverse of a 'response time' factor. If the ray hits an enemy, you get they outta the way. (MEDIUM SPEED BULLETS)

2- trace a ray(/triangleish/coneish shape if there's spread) from the weapon when the player shoots. If there's an enemy there, move him outta the way. (HIGH SPEED BULLETS)

3- if the bullets are really slow, you could simply loop all of them for each enemy and determine their positions in the future, and add to that the velocity vector of the current enemy being looped, consider a reasonable response time and threshold, if the positions are similar, then don't move the enemy there OR move the enemy outta there. (LOW SPEED BULLETS)

P.S.: I'm assuming you're using a physics engine (box2d, etc) for the 1st and 2nd items.

if the bullets doesn't have 'speed', but are simply raytraces (instantly hits anything), then there's no way other than using the direction the player is facing to somehow determine that (see OriginalDaemon's answer).
> 1 votes

# Answer
You should use a combination of Steering Behaviours and speed fluctuation if you want your AI to be able to dodge bullets. It will not be perfect so maybet it will be the right tool.
> 0 votes

---
Tags: algorithm, xna-4.0, ai, shoot-em-up
---


# Question
Title: Trouble With Quaternions and orbital camera:
**UPDATED:** I have been trying to implement a Orbital Camera of sorts in a engine I am currently doing in Unity3D, the issue being I can't seem to do the correct rotation no matter what.

This is what it is needed:

Rotate on Y and X axis via the mouse, but the Y and X axis are not Vector.up or Vector.right they are given by the current Slope of the Target I am orbiting around.

I don't get how I can make it idependent of the character rotation, but at the same time dependent

This sorta works, but some loops have issues, check the video below for a taste of whats wrong

```
var forward = Vector3.forward; //Vector3.Cross(ViewTarget.transform.up, transform.right);
        //Apply the rotation
        var rot = Quaternion.AngleAxis(CurrentHorizontalLook, ViewTarget.transform.up);
        var rot2 = Quaternion.AngleAxis(CurrentVerticalLook, transform.right) ;
        Debug.DrawRay(ViewTarget.transform.position, Vector3.right * 5, Color.yellow, 0, false);
        Debug.DrawRay(ViewTarget.transform.position, ViewTarget.transform.up * 5, Color.blue, 0, false);
        var offset = forward * 5;
        transform.rotation =  rot * rot2;
        transform.position = ViewTarget.transform.position + EyeHeight + transform.rotation*-offset;
        transform.LookAt(ViewTarget.transform.position, ViewTarget.transform.up);

```

EDIT : Maybe this image will help.

Black is the Up Vector, Red is the rotation on X Axis, Green is rotation on Y Axis. The trick here is it being idependent of the right and forward of the Target object , only the Up vector used to align the camera.

Edit: I have "something" that is somewhat related to what I want, but still missing one thing.

I got the camera to rotate correctly on the target Y axis, but it doesn't align to the ground plane at all.

Convention : Y = UP Z = Forward X = Right

```
var rot = Quaternion.AngleAxis(CurrentHorizontalLook, ViewTarget.transform.up);
        transform.rotation = rot ;
        var rot2 = Quaternion.AngleAxis(CurrentVerticalLook, transform.right) ;

  transform.rotation =  rot * rot2;

    var offset = forward * 5;

```

This is what I have , the issue now being that if the character is on a 90 degree wall the camera should be moving around the character on the same plane as the wall, but in my case it looks in a top down manner. If instead of WorldForward I used TargetForward it moves in the correct plane, but then when the character changes direction the camera shifts too.

I think a better explanation of what I want is this : I want the camera to rotate on the X,Z Plane of the character, and I want to be able to tilt it up or down in the Y,Z Plane. If you check the video I posted when Sonic goes in loop I want the camera to do sorta the same thing.

Youtube Showing current Camera issue

# Answer
> 1 votes
Assuming your camera have a independent forward vector that always points from position of camera to the character;

Suppose if you want to rotate the camera N radians in the local Y axis (character up) and maintains the same distance to target after the rotation:

```
quat = axisAngle(target.up, radian);
camera.forward = rotateByQuat(camera.forward, quat);
camera.side = normalized(cross(target.up, camera.forward));
camera.position = target.position - camera.forward * distanceToTarget.

```

Its easy to see that this does what you want regardless of the orientation of ground your character is standing on:

Whats missing from here is what to do when your character up change, ie, when he walks against a slope or wall. What you need to do here, is whenever the target up change, you need to set the camera up equal to character up again. But based on the difference between the new camera up and previous camera up, update the camera forward so that it is pointing to the character again (and of course, implicitly the position of camera since it is calculated from camera forward)

---
Tags: c#, unity, rotation, quaternion
---


# Question
Title: Directx: HLSL Texture based height map. (Shader 5.0)
I'm trying to implement a GPU based height map the simplest (and fastest) way that I know how. I passed a (.png, `D3DX11CreateShaderResourceViewFromFile()`) texture into the shader, and I'm attempting to sample it for the current pixel value. Seeing a `float4`, I'm currently assigning a color value from a channel to offset the `y` value.

```
Texture2D colorMap : register(t0);
SamplerState colorSampler : register(s0);

...

VOut VShader(float4 position : POSITION, float2 Texture : TEXCOORD0, float3 Normal : NORMAL)
{
    VOut output;

    float4 colors = colorMap.SampleLevel(colorSampler, float4(position.x*0.001, position.z*0.001, 0,0 ),0);
    position.y = colors.x*128;

    output.position = mul(position, WVP);
    output.texture0 = Texture;
    output.normal = Normal;

    return output;
}

```

The texture is imported correctly, and I've inserted another texture and was able to successfully blend the texture with another texture (through multiplication of values), so I know that the float4 struct contains values of a sort capable of having arithmetic performed on it.

In the Vertex function, attempting to extract the values yields nothing on a grid:

The concept seemed simple enough on paper...

# Answer
> 1 votes
As described here, the texture wasn't bound to the Vertex shader.

Without this (@Mooseboys) The texture data was not presented to the Vertex Shader, causing NULL or zero values. Binding the texture resolved the problem.

---
Tags: c++, directx11, hlsl, heightmap
---


title: Positioning of AABB / Rectangles

text:
# Question
Title: Positioning of AABB / Rectangles
I am wondering what is the best way to position rectangles, the ways I have thought of are:

1. Have an x and y at upper left, then have a width and height
2. Have an x and y at upper left, and an x and y at lower right
3. Have an x and y at center, and have width and height ("radii" of the rectangle)

I guess that the third way might make the most sense since it's the closest to how I would do a circle (position and radius) but I do not know if it is the best way to do it.

I would prefer to stay away from the second way, as I would want only one part for position

Is there a preferred way to do this?

# Answer
> 1 votes
You want method 1 or 3 probably. 2 is generally not preferred because you need to update 2 points whenever the rect moves as oppose to 1 point in method 1 or 3.

---
Tags: 2d, aabb
---


title: Getting normal map of an image

text:
# Question
Title: Getting normal map of an image
I'm trying to achieve the results in this tutorial: Link

So far, I was be able to do that;

with these;

```
    public PixelMap GetNormalMap(double strength)
    {
        var newMap = new PixelMap(Width, Height);

        for (int i = 1; i < Width - 1; i++)
        {
            for (int j = 1; j < Height - 1; j++)
            {
                /*
                    [ a b c ]
                    [ d x e ]
                    [ f g h ]
                */
                var a = this[i - 1, j - 1].Intensity;
                var b = this[i, j - 1].Intensity;
                var c = this[i + 1, j - 1].Intensity;
                var d = this[i - 1, j].Intensity;
                var e = this[i + 1, j].Intensity;
                var f = this[i - 1, j + 1].Intensity;
                var g = this[i, j + 1].Intensity;
                var h = this[i + 1, j + 1].Intensity;

                // sobel filter
                double dX = (c + 2.0 * e + h) - (a + 2.0 * d + f);
                double dY = (a + 2.0 * b + c) - (f + 2.0 * g + h);
                double dZ = 1.0 / strength;

                var v = new Vector3D(dX, dY, dZ);
                v.Normalize();

                newMap[i, j] = new Pixel(Pixel.Map(v.X), Pixel.Map(v.Y), Pixel.Map(v.Z), this[i, j].A);
            }
        }

        return newMap;
    }

    public double Intensity
    {
        get { return (R + G + B) / (3.0 * 255); }
    }

    public static byte Map(double value)
    {
        return (byte)((value + 1.0) * (255 / 2.0));
    }

```

The first issue is that the normal map colors are different on my image. Also, I was not be able to understand how the get the image in D (can be found in the middle of the linked article). I can upload all the code if the functions above are not enough.

Normal map after alpha map;

# Answer
> 1 votes
That is not really an accurate normal map, by the way. You are just sort of assuming that the regions of the image where the luminance varies correspond with surface contours. That is frequently the case, but not necessarily - particularly in a subject this filthy, there will be a lot of dirty areas that appear to a sobel filter as contours rather than just dark dirt stains.

Generating a normal map using a sobel filter usually involves a heightmap image (in the article you linked, you will notice that the silhouettes in figure A are a single color and that the resulting normal map only varies where that color transitions from white to black).

I ***think*** you might get more desirable results (the kind seen in the article you linked to) if you use the alpha channel instead of the "intensity" of the color image. You might also do a blur (figure B) before feeding it through the Sobel filter to achieve the same sort of results as figure C.

---
Tags: 2d, graphics, image, graphic-effects, image-processing
---


title: Placeing stones/tiles on a board game

text:
# Question
Title: Placeing stones/tiles on a board game
I am a beginner at libGdx.

I am building a board game (the Fanorama game). I would like to use a pic as the board and place the pieces on the board on top of the board sprite. Is there a nice way to pre-determine what (x,y) co-ordinate locations on the board sprite are valid for placing a piece. Later on, when the game is being played I would like to move the pieces from location to location.

Right now, the only way I can think of is to calculate each piece location pixel co-ordinates and hard-code it in an array. I am not sure if there is a better way to do this and a best practice way for me to learn. I am also concerned if this will be affected when the user resized the screen or uses a different sized device (mobile).

How to solve this problem?

# Answer
> 1 votes
Assuming the board view is from directly above, for simple rectangular boards, you can do pretty well by interpolating from the four corners of the active playing area.

# Answer
> 0 votes
Why not have a 2 dimensional array, of the size of your grid, then draw your pieces depending on how many pixels you have as the dimensions of each grid.

For example:

```
public static final WORLD_WIDTH = 6;
public static final WORLD_HEIGHT = 6;

public static final GRID_WIDTH = 16;
public static final GRID_HEIGHT = 16;

GridPoint[][] grid = new GridPoint[WORLD_HEIGHT][WORLD_WIDTH]; //Grid Point is an object that would store information about each gridPoint. For example, it might store the piece that is on that gridPoint, whether a piece can be moved to things gridPoint etc.

```

instantiate grid objects:

```
for(int y = 0; y < grid.length; y++){
    for(int x = 0; x < grid[y].length; x++){
        grid[y][x] = new GridPoint(...parameters about the grid point, piece type maybe);
    }
}

```

in your render method:

```
for(int y = 0; y < grid.length; y++){
    for(int x = 0; x < grid[y].length; x++){
        grid[y][x].draw(batch, x * GRID_SIZE, y * GRID_SIZE);
    }
}

```

You might also want to consider making each GridPoint an actor/widget then you would be able to use libGDX's DragAndDrop function.

---
Tags: java, libgdx
---


# Question
Title: Java 2d Gaming, best practice to update random falling objects
I'm new to game development. I do have basic knowledge in Java and also have moderately good experience in OOP from other languages.

I started developing this simple 2D game as my first project.

The game is simple, I have a character, I can move only right and left with constant speed.

I want to add obstacle objects that fall from the sky (top) that I have to dodge. I created the main class (StartingClass) that contains the game loop. receives input from the user's keyboard and moves the character accordingly.

I created a Character class which describes the character position, and reflect its position with painting its image.

Everything is well. However, I'm now trying to add the falling objects. My delima is how to implement them.

I started by creating a new class (FallingObject). In the instructor I create its width, height, falling speed.. etc (randomly). The issue I'm having is to determine how to update this object's position. I would have created an update method for the object and call it every time in the game loop to update its position. But my problem is I will have multiple objects falling simultaneously, each with different speed. So these are the solutions that came to my mind:

* Visible/Active falling objects will be stored in an array list *

1) on every game loop, iterate over the falling objects and update them individually, which doesn't sound that friendly to me.

2) In the falling object instructor, when finished assigning the random values, call a synchronized "startFalling" method on the object, so it keeps falling until it hits the ground.

3) My FallingObject class would implement the runnable interface, and run the function described above through thread. But still... thread for each falling object? I'm not liking that idea.

So I would like to know if I'm somewhat in the right direction in my way of thinking to solve this issue, and which of the above suggestions you think is best, or if there's way better solutions (which I believe is true) that I'm unable to see due to my limited experience in game development design / java.

Thank you very much for your help and support! Cheers Shady

# Answer
> 1 votes
I think you are over thinking this. Just have each object has its own update method that takes a delta time; then do

```
 obj.vy += 0.01 * dt; //gravity
 obj.y += obj.vy * dt;

```

And call this for every object in each game step and your done!

---
Tags: java, 2d, animation
---


# Question
Title: Better way to position objects in a Matrix/Grid shape
I am working on space a invader game and I'm trying to build levels such that in each of them, the aliens are positioned in a different shape. I have a rectangle shape, circle shape, and a grid-like shape.

I need help to find a better algorithm to position the aliens in the grid shape.

example of the grid shape:

X X X X X X X

X X X X X X X

X X X X X X X

the "algorithm" I made doesn't feel smart enough and I want some guiding.

Here is my code:

```
//3 Line Formation
     private void setMonsterLinesFormation()
     {
         int spaceX = monsters[0].AreaRect.Width + 10;
         int spaceY = monsters[0].AreaRect.Height + 10;

         int newLinePoint = 7;

         monsters[0].Location = new Point(0, 50);
         Point lastMonsterLoc = monsters[0].Location;

         for (int i = 0; i < monsters.Count; i++)
         {
             Monster currentMonster = monsters[i];
             currentMonster.Location = new Point(
                 x: lastMonsterLoc.X + spaceX,
                 y: lastMonsterLoc.Y);

             if (i == newLinePoint)
             {
                 currentMonster.Location = new Point(monsters[0].Location.X, spaceY * 2);
             }

             if (i == newLinePoint * 2)
             {
                 currentMonster.Location = new Point(monsters[0].Location.X, spaceY * 3);
             }

             lastMonsterLoc = currentMonster.Location;
         }
     }

```

how should I improve this code? (if it helps, I will not use more than 30 aliens at a time, here I am using 21)

# Answer
> 3 votes
Maybe so?

```
 int dimensionX = monsters[0].AreaRect.Width;
 int dimensionY = monsters[0].AreaRect.Height;
 int monstersPerLine = 7;

 int padding = 10;
 int currentX = 0;
 int currentY = 0;
 int monsterIndex = 0;

 for(Monster monster : monsters) {
     if(monsterIndex % monstersPerLine == 0) {
          currentX = 0;
          currentY = currentY + dimensionY + padding;
     }
     monster.Location.x = currentX;
     monster.Location.Y = currentY;

     currentX += dimensionX + padding;
    monsterIndex++;
 }

```

# Answer
> 0 votes
Are you looking to place objects in a grid? If so, just use a double for loop?

```
for (int i = 0; i < desiredWidth ; i+= monster.width + paddingX){
    for (int j ... ){
        monster.x = i;
        monster.y = j;
    }
}

```

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


title: minecraft mapping from tibia OTBM file

text:
# Question
Title: minecraft mapping from tibia OTBM file
I am new to minecraft modding but i program for a living and it looks quite simple to get around. I have this fantasy and a quick internet search shows im not the only one. For those of you who do not know tibia is an MMORPG first released in 1997. It is a 2d tile based game and i would like to see it in 3D. since it is a tile based game it fits nicely with the minecraft architecture. Tibia is a close sourced game but there is TibiaOT which is developed by the community and the map file format is OTBM (open tibia binary map). This is a set of 15 2D grids where each grid represents a floor or the height of the grid, the file comes with two more files with monster spawns and default item locations like chests.

There is a tibia texture pack for minecraft called "Tibian texture pack", so we got the materials covered.

all in all we have the following: a native tibia map and a minecraft texture pack

people have been building tibia maps manually for years now, it seems stupid because we have a binary file for the real map. what we need is a way to map the OTBM file to a minecraft map. i am looking for tools and any other tips a on how to digest the files into a minecraft map file. an explanation of minecraft map file format would also be very helpful.

# Answer
your Answer from Arqade

> MCEdit is a tool for editing minecraft save file, I can write a filter for it that manipulates the MC saves. I can also read the OTBC file using the OT c++ modules and formatting them into XML then translating the XML into MCedit readable data and then injecting them into a minecraft save through a MCedit filter script.
> 0 votes

---
Tags: textures, minecraft-modding, modding, file-format, porting
---


# Question
Title: Bounding Box not rotating based on draw rotation (Java)
In the process of developing a 2D game and am having some issues with translating coordinates on rotation. The object being rotated is a sword that is attached to the player. The player currently points towards a Point (mouse pointer). I am having no problems drawing the rotation, but am a bit confused on how to update the local coordinates so that the bounding box will follow also, around the player.

The weapon (coordinates) is just stuck on the left side of the player(invisible), but the drawing of the weapon is rotating around the player. The bounding box is working fine, but who wants invisible collision detection. It basically just isn't following the draw rotation.

Here is my basic draw implementation for rotating this weapon around the player.

WEAPON CLASS:

```
/**
* Updates child weapon
*/
public void Update(Point mp)
{
    this.boundingBox = new BoundingBox(startX,startY,width,height);
}

/**
 * Draws weapon to player
 */
public void DrawTo(Graphics2D g2d,Player p)
{
   AffineTransform backup = g2d.getTransform();
   AffineTransform trans = new AffineTransform();
   trans.rotate(Math.toRadians(getRotation()), p.getCenterX(), p.getCenterY() );
   g2d.transform( trans );
   g2d.drawImage(this.getImg(), startX, startY,null);
   g2d.setTransform( backup );
}

```

GAME LOOP:

```
/**
 * Player collision with weapons
 */
for(int l = 0; l < weaponManager.getDroppedWeapons().size(); l++)
{
    Weapon w  = this.weaponManager.getDroppedWeapons().get(l);

    if(player.Collision(w))
    {
        //If player already has a weapon, update that weapons position, add others to list that are picked up later
        if(player.getWeaponEquipStatus() == true)
        {
            //Sets the picked up weapon to the left side of the player
            player.getCurrentWeapon().setX(player.getX()-player.getCurrentWeapon().getWidth());
            player.getCurrentWeapon().setY(player.getY()+((player.getHeight()-player.getCurrentWeapon().getHeight())/2));
        }
        else if(player.getWeaponEquipStatus() == false)
        {
            player.setCurrentWeapon(w);
            w.isPickedUp = true;
        }
    }
}

```

I am aware of the AfflineTransform's getTranslateX and Y() methods. I have tried assigning these returned values to my x and y weapon values in the update method, but that is definitely not the solution.

Main issue: weapon coordinates aren't rotating, but the drawing is successful.

If anyone has any advice on where to start, based on my problem, it would be greatly appreciated.

# Answer
> 1 votes
It looks like you are using a matrix to rotate the image when it is drawn. This does not change the position values you have stored in your class, but it does affect how the image is drawn. If you want to know where the 4 corners of the image are drawn you will have to keep track of them yourself. Same is true of the bounding box. If the bounding box is to rotate along with the image, you will need to transform the 4 corners of the bounding box just like you are transforming the image when you draw it.

This brings up another issue. If you are rotating your bounding box, then you need to use a collision detection method that can properly handle non-axis aligned bounding boxes. An example would be separate axis theorem (SAT).

---
Tags: java, 2d, collision-detection, coordinates
---


# Question
Title: Is this equivalent to D3DXVec3TransformNormal?
I was porting some code from DirectX to OpenGL. I have the following code:

```
glm::mat4 rotation(1.0f);
rotation = glm::rotate(rotation, degrees, m_up);
m_look  *= rotation;

```

where `rotation` is a `mat4` and `m_look` is a `vec3`. I wanted to know if the last line here,

```
m_look  *= rotation;

```

has the same effect as

```
D3DXVec3TransformNormal( &m_look, &m_look, &rotation );

```

in DirectX? If not, then what would be the correct alternative?

# Answer
I got my answer:

The mat4 simply applies a rotation to the vec3, and that rotation information is stored only in the 3x3 part of that mat4, so i can safely cast the mat4 to a mat3 and multiply with the vec3 to get things going, something like

```
m_look = mat3(rotation)*m_look;

```

That would give me what i wanted. I can then normalize my vec3.
> 0 votes

---
Tags: opengl, directx, porting
---


# Question
Title: Help Understanding libgdx create animations example game
I am trying to understand the example game, cuboc. GitHub is https://github.com/libgdx/libgdx-demo-cuboc. I have generated my texture atlas but I do not understand the code that uses this texture atlas. Here's the code (you can see on github too here:

```
package com.badlogic.cubocy;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.SpriteCache;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20;
import com.badlogic.gdx.math.Vector3;

public class MapRenderer {
...
    private void createAnimations () {
        this.tile = new TextureRegion(new Texture(Gdx.files.internal("data/tile.png")), 0, 0, 20, 20);
        Texture bobTexture = new Texture(Gdx.files.internal("data/bob.png"));
        TextureRegion[] split = new TextureRegion(bobTexture).split(20, 20)[0];
        TextureRegion[] mirror = new TextureRegion(bobTexture).split(20, 20)[0];
        for (TextureRegion region : mirror)
            region.flip(true, false);
        spikes = split[5];
        bobRight = new Animation(0.1f, split[0], split[1]);
        bobLeft = new Animation(0.1f, mirror[0], mirror[1]);
        bobJumpRight = new Animation(0.1f, split[2], split[3]);
        bobJumpLeft = new Animation(0.1f, mirror[2], mirror[3]);
        bobIdleRight = new Animation(0.5f, split[0], split[4]);
        bobIdleLeft = new Animation(0.5f, mirror[0], mirror[4]);
        bobDead = new Animation(0.2f, split[0]);
        split = new TextureRegion(bobTexture).split(20, 20)[1];
        cube = split[0];
        cubeFixed = new Animation(1, split[1], split[2], split[3], split[4], split[5]);
        split = new TextureRegion(bobTexture).split(20, 20)[2];
        cubeControlled = split[0];
        spawn = new Animation(0.1f, split[4], split[3], split[2], split[1]);
        dying = new Animation(0.1f, split[1], split[2], split[3], split[4]);
        dispenser = split[5];
        split = new TextureRegion(bobTexture).split(20, 20)[3];
        rocket = new Animation(0.1f, split[0], split[1], split[2], split[3]);
        rocketPad = split[4];
        split = new TextureRegion(bobTexture).split(20, 20)[4];
        rocketExplosion = new Animation(0.1f, split[0], split[1], split[2], split[3], split[4], split[4]);
        split = new TextureRegion(bobTexture).split(20, 20)[5];
        endDoor = split[2];
        movingSpikes = split[0];
        laser = split[1];
    }

```

What I do not understand is what is `split` used for? Like, what is going on here:

```
split = new TextureRegion(bobTexture).split(20, 20)[1];

```

And sometimes it looks like `split` is a method that takes two `int`'s, `20` and `20`? Why 20? Othertimes `split` is used as an `Array` like in ...

```
rocketExplosion = new Animation(0.1f, split[0], split[1], split[2], split[3], split[4], split[4]);

```

... and I just can't follow what's going on here. Thanks!

# Answer
> 2 votes
From the documentation:

> public TextureRegion\[\]\[\] split(int tileWidth, int tileHeight)
>
> Helper function to create tiles out of this TextureRegion starting from the top left corner going to the right and ending at the bottom right corner. Only complete tiles will be returned so if the region's width or height are not a multiple of the tile width and height not all of the region will be used. This will not work on texture regions returned form a TextureAtlas that either have whitespace removed or where flipped before the region is split.
>
> Parameters:
>
> * tileWidth - a tile's width in pixels
> * tileHeight - a tile's height in pixels
>
> Returns:
>
> a 2D array of TextureRegions indexed by \[row\]\[column\].

Looks like the texture is actually a texture atlas, or tile map. The split method takes one texture and splits it into texture tiles. The image has tiles that are 20 by 20 pixels, passing `20,20` into `split` splits the image into tiles that are 20 pixels by 20 pixels.

So something like

```
TextureRegion(bobTexture).split(20, 20)[1];

```

would return the second row of tiles in the sprite sheet.

# Answer
> 1 votes
this is easy way to create animations, you can add all animation images to one image and than use them separately , for example each image is 20x20 pixel and your animation contains 3 images so the big image will be 60x20 , and if you split it by 20 x20 pixel you can get all the images , and then put those images in animation . Another example. your character have two animations walk right and left, walking left animation contains 2images and walking right animation again 2, so your bug image can contain 4 images (30x30) the big image can be 120x30 or 60x60 , and by splitting this 30x30 you can get animation images separately and walking left can be 0,1 index in the array and right 2,3 .

---
Tags: libgdx, animation
---


title: Vertical Text - Bitmap Font Libgdx

text:
# Question
Title: Vertical Text - Bitmap Font Libgdx
How can I achieve this kind of rotation or vertical text using Bitmap Font?

I already used Matrix but didn't get the result same as above.

# Answer
> 2 votes
You can draw each letter in a new line using `\n`

```
drawMultiLine(Batch batch, java.lang.CharSequence str, float x, float y)

```

Draws a string, which may contain newlines (`\n`), at the specified position.

---
Tags: libgdx
---


# Question
Title: LibGDX: Making an object move correctly based on real time
Below is an image of my gameworld. As we can see, the player starts at position 0. each cell represents 1 game world unit. My goal is to get the player to move 1 unit (the red cell) in 1 second in 'real world' time using the LIBGDX framework.

LibGDX uses something called 'continuous rendering' by default, which means its 'main loop' runs as fast as the underlying OS is able to. The range could be anywhere from 0-80 frames per second. I am capping the FPS to 60 with the below 'main' loop (In LIbGDX the main loop is called render)

```
@Override
public void render(float deltaTime) {

    /*
     * Get the time it took to render the last frame and make sure our delta
     * time is never larger than 0.0166666666666667 (60 FPS). This will
     * ensure that on fast OS the game at only 60 FPS.
     */
    float dt = Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f);

    // **********************UPDATE*********************

    player.update(dt);

    // ************************RENDER********************

    // clear the screen and set it to cornflower blue
    Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f, 0xed / 255.0f,
            0xff / 255.0f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    worldRenderer.render();

}

```

Below is the code for my player object's update method. As we can see it is operating solely on the delta time for now. In a perfect world of 60 FPS, this would work perfectly but unfortunatly FPS dips will always happen (especially on mobile platforms). **How can I add a calculation on top of the delta time to move the player 1 unit in real time regardless of framerate?**

```
@Override
public void update(float deltaTime) {

    // handle user input **always should come first**
    if (Gdx.input.isKeyPressed(Keys.SPACE)) {
        position.x += deltaTime;
    }

}

```

Below shows what is happening with my current code, if we had a perfect 60 FPS the position should = 1, but as we can see it does not because the FPS varies slightly from frame to frame.

# Answer
The deltaTime is the time it takes for the system to render one frame, thus if you are using deltaTime correctly, your character should move the same amount regardless of the frame rate. For example, if you are moving your character by the raw deltaTime value (+= delta):

If you have 1 update in 1 second, delta will be 1f, and you character will move by 1. If you have 60 updates in 1 second, delta will be 1/60f, and in 1 second your character will move 60 * (1/60f) which is still 1.

The error you show in the 2nd image is perfectly understandable, but I really think that it is so minimal you don't need to worry. You're talking about 1 100th of error.

Another thing to mention, Math.min code you have isn't helping you out very much. You are essentially restricting the whole point of the deltaTime value. If it takes libGDX less than 1/60 of a second to render a frame, that will be reflected in the delta value. For example: If you have two ticks that take 1/120 of a second (this is an extreme and will never happen), by setting your deltaTime to 1/60, you are making libGDX think that 2/60 seconds went by, when really 2/120 seconds went by. So you really shouldn't be restricting your deltaTime value.
> 1 votes

# Answer
You'll have to measure elapsed time independently of the game loop.

```
long startTime, time;
startTime = System.currentTimeMillis();
while(true) // game loop
{
time = System.currentTimeMilles();
if((time - startTime) > 1000) doSomething();
}

```
> 0 votes

# Answer
this is physic. S=Vt , here if t =1 second and s =1unit so it will move by 1 unit/second speed , libGDX render method is called 60 times in 1 second so you can move your character by 1/60 unit each time when render is called and the player will continue to move by 1 unit/second speed
> 0 votes

---
Tags: libgdx
---


title: Smooth path/direct movement

text:
# Question
Title: Smooth path/direct movement
I have a tile based isometric map and an A\* algorithm that returns a path. I am looking to smooth this path efficiently but with good aesthetics. Basically i am using my grid for building the map and pathfinding but i want the player, enemies and certain types of objects to be detached from this grid.

I can think of a line of sight implementation where i start at the first tile of the path, from there check each further tile if i have a clear path straight to it. And repeat from there.

# Answer
You could look at Theta\* \- it's invented for exactly that purpose.

Pretty much like A\*, except when adding a node it tests if the new node can be reached directly from the active node's parent, and if so from that node's parent, and so on. It produces very-nearly-perfect paths in most conditions.

Image is the output of my very, vey buggy C++ implementation.
> 5 votes

# Answer
I have implemented A\* pathfinding on a hexagonal grid in C# that nicely smooths paths like so in the HexGridUtilitiesForGames project (under the MIT License):

Key portions of the code are reproduced here.

```
void ExpandNeighbour(IDirectedPath path, NeighbourHex neighbour) {
  if ( ! OpenSet.Contains(neighbour.Hex.Coords)) {
    var cost = StepCost(neighbour.Hex, neighbour.HexsideExit);
    if (cost > 0) {
      var newPath = path.AddStep(neighbour, cost);
      var key     = Estimate(Heuristic, VectorGoal, Source.Coords,
                             neighbour.Hex.Coords, newPath.TotalCost);

      TraceFindPathEnqueue(neighbour.Hex.Coords, key>>16, (int)(key & 0xFFFFu));

      Queue.Enqueue(key, newPath);
    }
  }
}

static int Estimate(Func<int,int> heuristic, IntVector2D vectorGoal, HexCoords start,
        HexCoords hex, int totalCost) {
  var estimate   = heuristic(start.Range(hex)) + totalCost;
  var preference = Preference(vectorGoal, start.Canon - hex.Canon);
  return (estimate << 16) + preference;
}

static int Preference(IntVector2D vectorGoal, IntVector2D vectorHex) {
  return (0xFFFF & Math.Abs(vectorGoal ^ vectorHex ));
}

/// <summary>Z component of the 'Vector'- or Cross-Product of two IntVector2Ds</summary>
/// <returns>A pseudo-scalar (it reverses sign on exchange of its arguments).</returns>
public static int operator ^ (IntVector2D v1, IntVector2D v2) {
  return v1.X*v2.Y - v1.Y*v2.X;
}

```

The `^` operator above on the `IntVector2D` objects is overloaded to perform a 2D cross-product (as shown), which measures the *orthogonality* of the two vector factors. The A\* heuristic is shifted 16 bits right and the absolute value of the cross product is added to the heuristic value, causing paths which are more visually direct to be favored.
> 2 votes

# Answer
What you're looking for might be more of a steering technique than a path finding technique.

There is a simple steering technique that you can use when there are no dynamic obstacles. Since you already use A\* you have the skeleton of a path (regions connected by straight lines). By having your agent move directly towards the furtherst point on the path it can see the path is automatically smoothened and shortened.

This approach creates smooth paths since each frame the agent will be able to look a tiny bit further, which will lead to tiny adjustments to its rotation.

This approach creates short paths since each frame it will move a bit closer on a straight line to the furthest visible point. There is no shorter path between two points than a straight line.

Of course when you add dynamic obstacles such as other agents path following becomes a lot more difficult but as a basis this is a very nice way to do it. You might want to look up papers which mention velocity obstacles and force and velocity based steering.
> 1 votes

---
Tags: algorithm, path-finding, tilemap, isometric
---


# Question
Title: Unable to instantiate objects Straight in unity
I am creating a match card game in unity and I want to place cards in straight direction that is one below another and so on... But with my formula It's showing cards one after another.Please tell me whats wrong with my code. Following is my code -

```
    void SpawnCards(){
    int cardsinrow = 4;
    int cardsincolumn = cardslist.Count/cardsinrow;
    if(cardslist.Count % cardsinrow > 0)
        cardsincolumn += 1;
    float spacebetweencards = .2f;

    for(int i=0; i<cardslist.Count; i++){
        GameObject mc = Instantiate(memorycard, new Vector3((i%cardsinrow+(i%cardsinrow*spacebetweencards))-(cardsinrow/2f)+spacebetweencards, 0, (i/cardsinrow+(i/cardsinrow*spacebetweencards))-(cardsincolumn/2f)+spacebetweencards), memorycard.transform.rotation) as GameObject;
        mc.GetComponentInChildren<MemoryCard>().SetMemorycard(cardslist[i].texture, cardslist[i].number);
    }
}

```

# Answer
> 1 votes
I don't know if this helps you but this is a nested for loop that places a prefab object at an x and y location. The `cardAmountX` can be changed to whatever amount you want and it basically sets the number of columns you will have. The `cardAmountY` can also be change to whatever amount you want and it sets the number of rows you want.

Just be aware that these objects will be placed every unity unit and will not accommodate the size of your card prefab object. That will require a little tweaking but should not be too hard for you to figure out... if you can't figure it out then post a comment and I will add it.

Is this what you are looking for or have I misinterpreted everything you have said?

```
//The card prefab you have created goes into this Transform variable named prefab.
public Transform prefab;
//The amount of columns of cards you want it your game
public int cardAmountX = 1;
//The amount of rows of cards you want in your game
public int cardAmountY = 5;

void Start ()
{
    //Call the spawn cards method
    SpawnCards ();
}

void SpawnCards ()
{
    //Use a nested for loop to achieve your goal of columns x rows of cards
    for (int x = 0; x < cardAmountX; x++)
    {
        for (int y = 0; y < cardAmountY; y++)
        {
            //Instantiate your card prefab variable and set its position to the x and y
            Instantiate (prefab, new Vector3 (x, y, 0), Quaternion.identity);
        }
    }
}

```

---
Tags: unity, gameobject
---


title: Change unity physics engine speed

text:
# Question
Title: Change unity physics engine speed
Is there a simple way to change the **speed\*** of unity's physics engine like in the game SuperHot?

Any script language is ok but javascript is preferred.

\*I am not sure if **speed** is the correct term.

# Answer
You can use Time.TimeScale for slow motion effect.
> 6 votes

---
Tags: unity, physics, unityscript
---


# Question
Title: If fixed timesteps are unreliable across web platforms, what can I use in my game loop?
As I have found out in my previous question, `window.setInterval` is not the best choice for a cross-platform game loop. What is my alternative for a game loop in Javascript that will (attempt to) run at the same speed on all devices?

# Answer
You shouldn't use equal intervals for game loop. Instead of this use `time_delta` (current\_time - last\_update\_time). Send `time_delta` to game object's update method and update position and other parameters depending on time\_delta. For example, simple object moving with const velocity will be:

```
function update(time_delta) {
    position = position + velocity * time_delta;
}

```

In this case, you don't need to set fixed frame per second and allow game to update state as fast as possible.
> 2 votes

---
Tags: javascript
---


title: Do I have to use vertexArray in opengl

text:
# Question
Title: Do I have to use vertexArray in opengl
```
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);

```

As you can see from the above code, some tutorials use this before using opengl. But a tutorial that I am following, directly uses `glGenBuffers` method and it works just fine. Hence I am totally confused what `glGenVertexArrays`. It is sad that it defines how buffer is used, but noone says in what way. Can you help me understand ?

# Answer
> 3 votes
If you use OpenGL 3.2, it's required.

---
Tags: opengl, vertex-arrays
---