title: GPU friendly bezier storage/evaluation?

text:
# Question
Title: GPU friendly bezier storage/evaluation?
Let's say that you want to do bezier curve or surface evaluation on the GPU (fragment shader, geometry shader, compute shader, OpenCL, etc). Does anyone know of any interesting tricks of techniques to do so? Im looking for GPU specific techniques, but I already know the equations for n degree bezier curves, triangles and tetrahedrons. Thanks!

# Answer
Using a tessellation shader, you can efficiently build useful representations of Bezier curves and surfaces all on the hardware. You can do this in conjunction with fully dynamic tessellation levels to implement automatic level-of-detail. It's a very simple concept. I'll illustrate using a Bezier curve tessellation although the principles extend trivially to Bezier surfaces.

---

First of all, you must define the input geometry in *patches*, which are made up of *control points*. This can be seen as a generalization of primitives and vertices. The important thing to note is that control points do not necessarily have to coincide with points on the resulting curve or surface. I will define a cubic Bezier curve as a 4-point patch:

A cubic Bezier surface, then, would be defined as a 16-point patch. Note that only 2 of the control points for our Bezier curve patch will coincide with the actual geometry, and in the same way only 4 of the control points of the Bezier surface patch will.

In terms of draw call submission, the only difference is that, for example, in OpenGL one must specify the number of control points per patch and also draw with the `GL_PATCHES` mode.

```
glPatchParameteri(GL_PATCH_VERTICES, 4);
glDrawArrays(GL_PATCHES, 0, 4);

```

---

The next step is to write the vertex and tessellation control shaders. Despite the name, control points are sent through the vertex shader as if they are vertices, and they may store the same data. In a tessellation pipeline, the vertex shader's job is simplified quite a bit, as it only needs to pass on the control point data, possibly applying per-instance attributes and/or transforming them into view space.

In our simplified case, we will only be passing on the position of each control point. I will use GLSL to implement the example shaders.

```
layout(location = 0) in vec3 aPos;
out vec3 vPos;
void main() {
    vPos = aPos;
}

```

Note that we do not need to set `gl_Position` (yet).

The tessellation control shader is almost as simple, as we will be using hardcoded tessellation levels. The interesting thing about the tessellation control shader is that it may access all of the control points of the current patch, like how the geometry shader may access all of the vertices of the current primitive.

```
layout(vertices = 4) out; // 4 points per patch
in vec3 vPos[];
out vec3 tcPos[];
void main() {
    tcPos[gl_InvocationID] = vPos[gl_InvocationID];
    if(gl_InvocationID == 0) { // levels only need to be set once per patch
        gl_TessLevelOuter[0] = 1; // we're only tessellating one line
        gl_TessLevelOuter[1] = 100; // tessellate the line into 100 segments
    }
}

```

The reason two tessellation levels are needed is because the GPU doesn't tessellate individual lines, it tessellates what it calls *isolines*, which fill up a rectangular area in the tessellation basis space. Since we're only tessellating one line we don't need to worry about how that works.

*Note: The tessellation control shader is actually optional. A shader as simple as this can be replaced by setting hardcoded values for the tessellation levels from the application itself, although that is typically not done in practice as it is not very useful.*

---

The final new step is to write the tessellation evaluation shader, where we finally get into evaluating the Bezier curve (or surface). First, I'll define a few helper functions for evaluating linear, quadratic, and cubic Bezier curves.

```
vec3 bezier2(vec3 a, vec3 b, float t) {
    return mix(a, b, t);
}
vec3 bezier3(vec3 a, vec3 b, vec3 c, float t) {
    return mix(bezier2(a, b, t), bezier2(b, c, t), t);
}
vec3 bezier4(vec3 a, vec3 b, vec3 c, vec3, d, float t) {
    return mix(bezier3(a, b, c, t), bezier3(b, c, d, t), t);
}

```

Now we can get to writing the meat and potatoes of the shader, which ends up being quite simple.

```
layout(isolines) in;
in vec3 tcPos[];
uniform mat4 uMVP;
void main() {
    float t = gl_TessCoord.x;
    vec3 ePos = bezier4(tcPos[0], tcPos[1], tcPos[2], tcPos[3], t);
    gl_Position = uMVP * vec4(ePos, 1);
}

```

The tessellation evaluation shader ends up being yet another shader that can access any control point within the current patch. It is also where we do our vertex transformation and finally output the `gl_Position` to be rasterized. Geometry shaders and fragment shaders are agnostic of whether tessellation has been used, so I won't go over examples for them. Otherwise, the tessellation pipeline is now complete.

The `gl_TessCoord` built-in variable probably demands some explanation. Basically, it provides the coordinates in what I call the "tessellation basis space". This is different for each type of tessellation. With isolines, the `x` component specifies the distance along the line from 0-1 and the `y` component identifies which line it is. With quads, the `x` and `y` components specify where on the quad the vertex is, similar to UV coordinates, again within the 0-1 range for both. With triangles, the `x`, `y`, and `z` components are the *barycentric coordinates* of the vertex. All that means is that if you multiply each component by its corresponding control point and add them together and divide by the sum of the coordinates, you will get the tessellated vertex. A great property of barycentric coordinates is that they work well with homogeneous coordinates; you do not have to then divide by their sum as the `w` component will take care of that.

In the case of evaluating a Bezier (or any other parametric) curve or surface, the components are used as the parameters. In the case of doing displacement mapping, the components are used for sampling the displacement map along with the UV coordinates. Typically these two techniques are used together along with dynamic tessellation levels to provide a very rich automatic geometry LOD system.

---

Hopefully this is pretty self-explanatory in places where I didn't go into detail. If something doesn't make sense, just comment and I will add detail where needed.

*Disclaimer: this code is completely untested but, to the best of my knowledge, should work.*
> 8 votes

---
Tags: gpu, beziers
---


title: loading a texture in Opengl

text:
# Question
Title: loading a texture in Opengl
I am working on a graphics project I want to make a city using opengl with c++ anyway in the last few days I have been trying to load a texture but it didn't work with me in any way I have tried many codes and tried to follow some tutorials but it didn't went ok

here is my load texture function:

```
int LoadTexture(char *filename,int alpha)
{
    int i, j=0; //Index variables
    FILE *l_file; //File pointer
    unsigned char *l_texture; //The pointer to the memory zone in which we will load the texture

    // windows.h gives us these types to work with the Bitmap files
    BITMAPFILEHEADER fileheader;
    BITMAPINFOHEADER infoheader;
    RGBTRIPLE rgb;

    num_texture++; // The counter of the current texture is increased

    if( (l_file = fopen(filename, "rb"))==NULL) return (-1); // Open the file for reading

    fread(&fileheader, sizeof(fileheader), 1, l_file); // Read the fileheader

    fseek(l_file, sizeof(fileheader), SEEK_SET); // Jump the fileheader
    fread(&infoheader, sizeof(infoheader), 1, l_file); // and read the infoheader

    // Now we need to allocate the memory for our image (width * height * color deep)
    l_texture = (byte *) malloc(infoheader.biWidth * infoheader.biHeight * 4);
    // And fill it with zeros
    memset(l_texture, 0, infoheader.biWidth * infoheader.biHeight * 4);

    // At this point we can read every pixel of the image
    for (i=0; i < infoheader.biWidth*infoheader.biHeight; i++)
    {
            // We load an RGB value from the file
            fread(&rgb, sizeof(rgb), 1, l_file);

            // And store it
            l_texture[j+0] = rgb.rgbtRed; // Red component
            l_texture[j+1] = rgb.rgbtGreen; // Green component
            l_texture[j+2] = rgb.rgbtBlue; // Blue component
            l_texture[j+3] = alpha; // Alpha value
            j += 4; // Go to the next position
    }

    fclose(l_file); // Closes the file stream

    glBindTexture(GL_TEXTURE_2D, num_texture); // Bind the ID texture specified by the 2nd parameter

    // The next commands sets the texture parameters
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // If the u,v coordinates overflow the range 0,1 the image is repeated
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // The magnification function ("linear" produces better results)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //The minifying function

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECR );

    // Finally we define the 2d texture
    glTexImage2D(GL_TEXTURE_2D, 0, 4, infoheader.biWidth, infoheader.biHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, l_texture);

    // And create 2d mipmaps for the minifying function
    gluBuild2DMipmaps(GL_TEXTURE_2D, 4, infoheader.biWidth, infoheader.biHeight, GL_RGBA, GL_UNSIGNED_BYTE, l_texture);

    free(l_texture); // Free the memory we used to load the texture

    return (num_texture); // Returns the current texture OpenGL ID
}

```

I call the function in init section

```
textureID = LoadTexture("Building.bmp",255);

```

and in the display section I wrote :

```
glBindTexture(GL_TEXTURE_2D,textureID);
    glBegin(GL_QUADS);
            //front
            glTexCoord2f(1,0) ;         glVertex3f(1,-1,0);
            glTexCoord2f(1,1) ;         glVertex3f(1,1,0);
            glTexCoord2f(0,1) ;         glVertex3f(-1,1,0);
            glTexCoord2f(0,0) ;         glVertex3f(-1,-1,0);
    glEnd();

```

# Answer
With open gl you can't just bind a texture before creating it.

Instead of keeping a counter called `num_textures`. **Each time you want to create a new texture**, retrieve a handle from OpenGL's `glGenTextures` function.

```
int id;
glGenTextures(1, &id);

```

So you would get rid of `num_texture` and all its usages.

And instead of this:

```
glBindTexture(GL_TEXTURE_2D, num_texture); // Bind the ID texture specified by the 2nd parameter

```

You write this:

```
int id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);

```

In other words you must use a handle OpenGL provides you, not just some random number you have decided.

In the future investigate using the `glGetError` function to see what went wrong as attempting to bind a texture that doesn't exist should give you a nice juicy error message.
> 0 votes

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


# Question
Title: What are the legal issues when using free Unity Assets on a commercial game?
In the unity asset store one can find tons of thousands of assets, a lot of them being distributed for free.

When using a free Unity Asset is it implied that you can do anything with it(commercial or not)?

Is there any legal agreement concerning free Unity Assets?

# Answer
> 4 votes
I'm pretty sure a quick Google would have given you the answer

There are a couple relevant points in the FAQ pertaining to licence and use of assets from example projects etc.

Unity stack answer : http://answers.unity3d.com/questions/342714/use-of-asset-store-assests-in-commercial-game.html

> "You can use any asset from the store personally and commercially, you can edit this object by changing materials, editing the Geometry etc
>
> You can NOT re-distribute the file, no matter how much you modify it you can use it but not share or re-sell it.
>
> Most of those conditions are there to prevent illegal activity or cover the author/unity team in the case of lawsuits. As a genuine paying user there is no need to worry about any of it, in the event that you accidentally breach a condition (such as redistribute a bought material on one of your models) unity will likely contact you and ask you to remove that component rather than outright sue."

---
Tags: unity, assets
---


# Question
Title: glutPostRedisplay() is not redrawing after updating model view matrix
I am trying to change the rotation of my object with keyboards, when I move the object in the direction of x, y or z it is okay, it is responding correctly. But when I try to change rotation, it does nothing at all.

```
void keypress(unsigned char key, int x, int y) {
Matrix R;
HomVector a;
switch(key) {
case 'x':
    cam.position.x -= 0.2f;
    break;
case 'X':
    cam.position.x += 0.2f;
    break;
case 'y':
    cam.position.y -= 0.2f;
    break;
case 'Y':
    cam.position.y += 0.2f;
case 'z':
    cam.position.z -= 0.2f;
    break;
case 'Z':
    cam.position.z += 0.2f;
    break;
case 'i':
    cam.rotation.x -=90.0f;
    R = RotationMatrix(-90, X);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'I':
    cam.rotation.x += 90.0f;
    R = RotationMatrix(90, X);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'j':
    cam.rotation.y -= 90.0f;
    R = RotationMatrix(-90, Y);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'J':
    cam.rotation.y += 90.0f;
    R = RotationMatrix(90, Y);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'k':
    cam.rotation.z -= 90.0f;
    R = RotationMatrix(-90, Z);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'K':
    cam.rotation.z += 90.0f;
    R = RotationMatrix(90, Z);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
//case 'Q':
case 'q':
    exit(0);
    break;
}
glutPostRedisplay();

```

}

This is the code, my matrix is changing after multiplication, but does not respond to glutPostRedisplay() function. If there is a problem, I cannot see it, if anyone can help, that would be great!

# Answer
my friend helped me to solve the problem, honestly, i still dont know what the problem was in the previous one, but i changed function as

```
void keypress(unsigned char key, int x, int y) {
Matrix R;
HomVector a;
switch(key) {
...
case 'i':
    cam.rotation.x -=1.0f;
    break;
case 'I':
    cam.rotation.x += 1.0f;
    break;
case 'j':
    cam.rotation.y -= 1.0f;
    break;
case 'J':
    cam.rotation.y += 1.0f;
    break;
...
case 'q':
    exit(0);
    break;
}
glutPostRedisplay();

```

}

After that i changed my display function as, i guess i should make changes in display function for updating display, otherwise i dont get any response.

```
void display(void) {
Mesh *mesh;

glClear(GL_COLOR_BUFFER_BIT);

....

Matrix R = RotationMatrix(cam.rotation.x, X);
V = MatMatMul(V, R);
R = RotationMatrix(cam.rotation.y, Y);
V = MatMatMul(V,R);
R = RotationMatrix(cam.rotation.z, Z);
V = MatMatMul(V,R);

//P is projection transform matrix, V is view transform matrix
PV = MatMatMul(P, V);

glUseProgram(shprg);

// render all meshes in the scene
mesh = meshList;

while (mesh != NULL) {
    renderMesh(mesh);
    mesh = mesh->next;
}

glFlush();

```

}

Thanks for comment, by the way!
> 0 votes

# Answer
I can't post comments yet, but.. You said that you're moving the object, but from your code it seems that you're moving the camera (not the object). I see nothing wrong with the key presses though, the only thing that comes to mind is that if your camera happens to be centered on, say, a Cube, with no lights, rotating 90 degrees won't change the image so you could try a smaller value for the rotation.

You're not changing the matrixes when you press x,y and z (like you do for rotations) so you must be changing the matrixes elsewhere. Are you maybe overwriting the rotation matrix with the position somehow? What do you do with the R, V and PV matrixes in the display function?
> 0 votes

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


# Question
Title: Generate platforms and move them with same speed
I'm building an infinite runner and have to generate pillars on which the player jumps. There's a minimum and maximum value for how much gap can exist between two pillars. In addition to this, i want the pillars to move to the left with increasing velocity. All pillars need to have same velocity. So, i made a pillarHolder object which would have velocity that increases with time. The instantiated pillars would be made children of this pillarHolder. Code is:

```
 if ((Vector3.Distance (go.transform.position,transform.position)<25f)) {

                t=rand.Next(13,35);
                t=t/10;
                //Debug.Log(t);
                tempx+=t;

                pos=new Vector2(tempx,-2.22f);

                go=Instantiate(pillar,pos,Quaternion.identity) as GameObject;
                go.GetComponent<Transform>().parent=holder;
            }
holder.GetComponent<Rigidbody2D> ().velocity=new Vector2(-10f,0);

```

The problem is, the pillarHolder keeps moving in the negative x direction and after a while, the pillars are not positioned properly. The gap between them exceeds the maxGap. I tried to solve the problem by resetting the pillarHolder's position once it went beyond position.x=-20f. But when it's position resets, child objects are reset too.

Any help please?

# Answer
If you're making an endless runner that means the inverse of your players' velocity should be driving the movement of all the other entities in the game - such as the backgrounds (dampened obviously) as well as the various obstacles and terrain for your player to traverse.

As such if you just instantiate a new pillar gameObject (based either on some mechanic such as a timer using predefined obstacle data lists etc) then it should just be driven by something simple like

```
transform.position = Vector2.MoveTowards(playerPos, targetPos, speed * Time.deltaTime);

```

in each Update() call. targetPos can just be a gameObject in your scene indicating a position to the left, just outside of the visible screen space (at which point you can kill/recycle your pillar). If you need objects which have their own speed then alter or add to the 'speed' variable for each required gameObject. For example a projectile being shot by a trap towards the player from right to left might be moving at playerSpeed + bulletSpeed etc.

On the topic of recycling objects : instead of instantiating a new gameObject for each obstacle such as pillars, especially in a tight loop or Update() function, instead investigate object pooling in Unity where you can just keep recycling from a pre-allocated list of gameObjects.

--- EDIT forgot you're using rigidBody ----

After you instantiate each pillar with an initial velocity (moving towards the player from right to left) then it sounds like you could then use an InvokeRepeating or something similar to fire off an increase in speed of each subsequent pillar by just adding force to the current velocity :

```
rididbody2D.AddForce(tranform.right * speed) // 'speed' in meters per second

```
> 1 votes

---
Tags: unity
---


# Question
Title: Pathfinding in multi goal, multi agent environment
I have an environment in which I have multiple agents (a), multiple goals (g) and obstacles (o).

```
.  .  .  a  o  .  .  .
.  .  .  .  o  .  g  .
.  a  .  .  .  .  .  .
.  .  .  .  o  .  .  .
.  o  o  o  o  .  g  .
.  o  .  .  .  .  .  .
.  o  .  .  .  .  o  .
.  .  .  o  o  o  o  a

```

What would an appropriate algorithm for pathfinding in this environment?

The only thing I can think of right now, is to Run a separate version of A\* for each goal separately, but i don't think that's very efficient.

# Answer
I know this question is old, but since no answer has been selected I'm going to post my own and hope it helps someone else.

Depends on the situation of your map whether you can apply a simple A\* algorithm, or use a collaborative A\* algorithm. By the situation I mean: Can two agents occupy the same space at a given time? If the answer is yes, then a simple A\* algorithm for each agent will do the thing. In the case the answer is no, the application of a collaborative path-finding algorithm could be helpful. After doing a little research, I found that this algorithm is a perfect example of how a collaborative algorithm works using A\*, this could help as a starting point to apply a collaborative algorithm that could be later improved to fulfil your needs.
> 3 votes

# Answer
You might want to check out some sort of **All pair shortest path** algorithm, maybe this one can be a good start.
> 1 votes

# Answer
If there are a small number of goals, and a large number of agents then you can do a BFS from each goal.

If there are more goals than agents you can also do it the more usual way round - start the search from the agents.

Either way you end up with the best path from each agent to each goal, without having to run A\* for number\_of\_agents * number\_of\_goals.
> 0 votes

# Answer
I'm going to just answer with the obvious here.

***Use A********

If your environment is going to be that small, it's not going to be a problem. Give your CPU some credit, it's a lot more capable than you think it is.

Don't prematurely optimize. Implement your A\* algorithm and run it on each agent. If you find it's slow, look into why it's slow. Profile it. Is the heuristic slow? Is it inadmissable? Look here for examples of heuristics that could help.

How many times are you generating a path? If you're generating a path from the same source and destination, then think about caching paths in a lookup table so you don't have to go through the path generation process again.
> 0 votes

# Answer
A\* is great if you have a single objective for every agents. If you have several objectives for every agents (for instance if your agents have to go to the closest objective), Dijkstra is better.

Now it depend on what you want to do.
> 0 votes

# Answer
Do you already have each agent `a` assigned to a single goal `g`? If so, I agree with the other answers: A\* would work well, although for such a small map it may not matter which pathfinding algorithm you use. If each agent `a` can go to any of the goals then you could use Dijkstra's algorithm and stop whenever any goal `g` is reached.

If however you want at most one agent `a` to be assigned to each goal `g` then you need to first assign agents to goals. You could use something like Kuhn-Munkres to make the assignment. Here's the Wikipedia description of the assignment problem:

> There are a number of *agents* and a number of *tasks*. Any agent can be assigned to perform any task, incurring some *cost* that may vary depending on the agent-task assignment. It is required to perform all tasks by assigning exactly one agent to each task in such a way that the *total cost* of the assignment is minimized.

You'll need to come up with costs; you could do that either with the same heuristic you use for A\*, or you could calculate the path lengths exactly (perhaps with Dijkstra's or Floyd-Warshall). After you've made the assignment you'll need to find the paths. If you computed the paths in order to get the costs, you'll already have them, but if you used a heuristic, you'll need to use A\* at this point to find the paths.
> 0 votes

---
Tags: path-finding
---


# Question
Title: Game State query -- Are Game states and Game Phases the same thing?
I am currently writing a simple board game app.

I have written some basic states which are more to do with global state of the game.

Currently they are just enums, they don't really do anything nor is there a manager.

Something like this;

```
enum {
GameStateInitialize = 0,
GameStatePlaying = 1,
GameStatePaused = 2,
GameStateEndGameConditionMet = 4
}

```

Most board games I've played have a linear list of "phases", my own digital board game tries to replicate this. During the GameStatePlaying the board game has various phases, sequentially driven; again these are just enums for now.

```
enum {
PhaseBuying,
PhaseProduction,
PhaseSelling,
PhaseTaxes,
PhaseUpdateDemand,
PhaseUpdatePlayerTurnOrder
}

```

During `PhaseTaxes` it will check for whether a game end condition has occurred; if it has it needs to trigger the `GameStateGameEndConditionMet`

Here's the problem I'm having.

Could game-phases, and game-states be combined? I'm really not sure how to make sure that it doesn't do a certain phase if the game end condition has been met?

Should gamePhase and gameState the same?

Thanks

# Answer
No, gameState and gamePhase should not be the same.

Your design is correct. You can have a *state machine* within a state of another state machine. Keeping the concepts separated like you did is the way to go.

The only issue you might encounter is that the wording you use might get confusing.
> 0 votes

---
Tags: state, game-state, board-game
---


# Question
Title: MiniMax strategy - What is the context of the numbers?
I've watched a new videos about the MiniMax concept and invariably the lecturer will say that the computer has 2 parties, Min and Max; Min always takes lower number and Max takes higher number.

The problem I have is this.

I'm finding it hard to understand why Min takes the lower number at all or why Max takes the higher number at all?

What is the reasoning and context for these numbers?

I mean, logically I know that 7 is higher than 3; but that doesn't mean anything by itself.

What is the context of the numbers?

Many thanks

# Answer
> 1 votes
You can think of the numbers as "relative advantage to the Max player"

Max wants to maximize their advantage relative to Min.

Min wants to maximize their advantage relative to Max, which is equivalent to minimizing Max's advantage over them.

Relative advantage could be computed as something like a score gap (if Max has 2 points to Min's 3, that means Max is behind by 1 point, which we could call a relative "advantage" of -1).

Often this is used in games that don't score-as-they-go, so the advantage number used is an estimate of how favourable the current game state is to Max winning. For instance in chess, if Max has Min in check, that's generally a pretty advantageous state (since Max can strongly limit Min's options), even if Max has fewer pieces on board.

In many minimax implementations, the advantage numbers don't have a concrete meaning - they're not scores or win probabilities, but heuristics which empirically tend to align well with good moves.

# Answer
> 1 votes
*Keep in mind that this algorithm is for zero-sum games, where the game state is known by all parties involved.*

The numbers given are those calculated by an **evaluation function** ran on the game state after `x` number of turns; for instance, in Tic Tac Toe, after a certain amount of turns, you know whether you won (+infinity), your opponent won (-infinity) or it's a draw (0), or if to win a game you count points, the number of points for you (positive) and for your opponent (negative).

These numbers are given to leaf nodes of the game state tree (each row of the tree represent a possible move by a player). When running the minmax algorithm, the numbers are copied over the node closer to the root. If we're filling the row of the parent nodes of the leaf nodes, and the leaf nodes represent a move by the player we transfer the MAXIMUM value because the player want's to maximize its score. Then the next row is the opponent's evaluation, since he'll take the best option for him, he'll take the worst for us (he'll try to MINIMIZE our gain).

This is done in turn until the root node is reached, where the best move for now is known, and played.

So the Min and the Max are used for **player/opponent**, turn by turn. The Max advantages the player, while the Min tries to reduce the opponent's score.

---
Tags: algorithm
---


title: Libgdx bouncy effect in a wall

text:
# Question
Title: Libgdx bouncy effect in a wall
I have an element inside the screen and I want to set my phone's bounds as a wall where elements are bouncing. I want it to be physically correct. How to do this?

# Answer
First, you need to know the screen bounds:

```
int screenHeight = getScreenHeight();
int screenWidth = getScreenWidth();

```

Then, you have to initialize the velocity vector for your bouncing square. In this example it'll be \<1,1\>:

```
BouncingSquare bouncingSquare = new BouncingSquare();
bouncingSquare.velocity.x = 1;
bouncingSquare.velocity.y = 1;

```

Also, for simplicity, I recommend you to have a method in the BouncingSquare class that helps you to compute the left, top, right and bottom coordinates of your square:

```
int getLeft()
{
   return this.position.x;
}

int getTop()
{
   return this.position.y;
}

int getRight()
{
   return this.position.x + this.size.width;
}

int getBottom()
{
   return this.position.y + this.size.height;
}

```

In your update method, you have to check if the square is out of the screen bounds and invert the velocity values if necessary:

```
if (bouncingSquare.getLeft() <= 0 || bouncingSquare.getRight() >= screenWidth)
     bouncingSquare.velocity.x *= -1;

if (bouncingSquare.getTop() <= 0 || bouncingSquare.getBottom() >= screenHeight)
     bouncingSquare.velocity.y *= -1;

```

Finally, just update the position:

```
bouncingSquare.position.x += bouncingSquare.velocity.x;
bouncingSquare.position.y += bouncingSquare.velocity.y;

```
> 0 votes

---
Tags: android, libgdx, physics
---


# Question
Title: Can I release the source code of a game created with the personal edition of Unity?
Does the license of Unity Personal allow the publishing of the game's source code? We want to develop a game on a hackathon and publish the code thereafter. Is this possible?

# Answer
> 3 votes
Yes, you can release the scripts you write. The source code is not actually created by Unity (of any edition). It's created by you, you own it.

You can write the source code using whatever editor you like from notepad to Monodevelop. These are just tools to help you write code, using them does not mean the creators of those tools own your source.

However, when you compile that code, you're compiling it with Unity's code. This is where their license comes into play. This is the difference between the paid and free versions of Unity, because you're licensing their code to run your code.

Releasing your own code that makes calls to Unity code is fine. You're not releasing their source code, only your code that makes use of it.

Please note that this assumes you are the one writing the code, and you're not being paid to do so. Further, it assumes you're not in any contracts with an employer that might give them rights to code you write in your free time (this may be the case if you worked on very similar code at work for example).

---
Tags: unity
---


title: Editing the pixels of a rendered image

text:
# Question
Title: Editing the pixels of a rendered image
I want to render a simple OpenGL scene as usual, but then I want to superimpose a small image of my own (such as from a bitmap file) on top of the render, such that this image always shows. For example, this could be thought of as showing a logo in the corner of the screen for a 3D game, where the logo is always displayed on top of the rendered scene.

Please could somebody start me off in the right direction? What should I be looking into? I am rather a novice at OpenGL...

Let us suppose that I have the following code:

```
#include <GL/glut.h>

void renderScene(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,0.0);
        glVertex3f(0.5,0.0,0.0);
        glVertex3f(0.0,0.5,0.0);
    glEnd();

    glutSwapBuffers();
}

int main(int argc, char **argv)
{
    // init GLUT and create Window
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(320,320);
    glutCreateWindow("GLUT Triangles");

    // register callbacks
    glutDisplayFunc(renderScene);

    // enter GLUT event processing cycle
    glutMainLoop();

    return 1;
}

```

This renders a triangle on the screen. How, for example, would I now render a 10-by-10 bitmap from file, at location (100, 100) on the screen? If the viewpoint was static, I could just calculate its 3D location and render it. However, I want the bitmap image to always be displayed in this location, even when the viewpoint changes.

Thanks :)

# Answer
You question is a little unclear, but if you asked how to render, for instance a GUI, I have an answer.

Basically you need to render a textured 2d quad. Note that it should be rendered last.

Heres a video tutorial: https://www.youtube.com/watch?v=vOmJ1lyiJ4A&list=PLRIWtICgwaX0u7Rf9zkZhLoLuZVfUksDP&index=24
> 1 votes

# Answer
You need to use a textured quad with an orthographic projection matrix. Using alpha blending will make the image partially transparent allowing for the image to not appear square.
> 1 votes

# Answer
The title of your question is different from what you're actually asking. I assume you are asking how to render a textured quad like a part of your game's HUD.

Here's what you can do to have an object rendered on top of your other objects:

```
void renderScene(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Set up matrixes in order to draw your scene
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho2d( -1.0, 1.0,
               -1.0, 1.0 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    gluLookAt( 0.0f, 1.0f, 0.0f,
               0.0f, 0.0f, 0.0f,
               0.0f, 1.0f, 0.0f );

    // Render your scene/triangle
    /*(...)*/

    // Set up your matrixes in order to draw your HUD over the scene
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho2d( 0, windowWidth, 0, windowHeight );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    // Disable Depth test so that the HUD will overwrite what was rendered before
    glDisable( GL_DEPTH_TEST );

    // Render your HUD elements
    /*(...)*/
    glPushMatrix();

        glBindTexture( GL_TEXTURE_2D, &someTextureId );

        glTranslate3f( 0, windowHeight - 100, 0 );
        // For example, scale your quad/texture to 100x100 pixels
        glScalef( 100.0f, 100.0f, 0.0f );

        glBegin(GL_QUADS);
            glTexCoord2f( 0.0f, 0.0f );
            glVertex3f( 0.0f, 0.0f, 0.0f );

            glTexCoord2f( 1.0f, 0.0f );
            glVertex3f( 1.0f, 0.0f, 0.0f );

            glTexCoord2f( 1.0f, 1.0f );
            glVertex3f( 1.0f, 1.0f, 0.0f );

            glTexCoord2f( 0.0f, 1.0f );
            glVertex3f( 0.0f, 1.0f, 0.0f );
        glEnd();

        // Remove texture
        glBindTexture( GL_TEXTURE_2D, 0 );

   glPopMatrix();

   glEnable( GL_DEPTH_TEST );

   glutSwapBuffers();
}

```

I've only indented the glPushMatrix and glPopMatrix to make it easier to read, it's not absolutely necessary.

If there's something you don't understand in the code sample feel free to ask.

---

Here's a series of tutorials that I recommend to get you started in OpenGL: http://lazyfoo.net/tutorials/OpenGL/index.php

There's also how to load and use textures.
> 1 votes

---
Tags: opengl, glut
---


# Question
Title: Techniques for drawing lines, with mouse, on 3D objects in WebGL or OpenGL?
Can anyone point me to techniques for drawing lines, with the mouse, on 3D objects in WebGL or OpenGL?

Here's the effect I'm looking for, using WebGL: http://www.spacegoo.com/cadillac/

I can imagine the general idea - projecting a ray onto the surface, then perhaps using normals and UVs, transform the intersections into UV-space and drawing the line on a texture, which gets mapped onto the object.

Would love to find some proper literature on it though.

# Answer
You could start by taking a look at the JavaScript code of that page you've linked to figure out how they did it. I'd guess each line is composed by a lot of tiny rounded dots used as decals. That could explain why the lines look dotted when seen from close. I don't think using decals would be the most efficient technique, but it should be the simplest to implement.

Here are some refs from google, if you want to take a look:

Apart from that, Virtual Texturing techniques can greatly simplify and improve texture painting, but just getting a VT system to work properly is a tremendous amount of work, so I doubt that would be relevant to you...
> 1 votes

---
Tags: opengl-es2, webgl
---


# Question
Title: How do I go about making a text box that allows for highlight-able and copyable text in the new UI?
I'm trying to make a simple chat system for our games lobby, however I am having issues making a text box that allows for text-highlighting. The Text component does not have interactible text, and the Inputfield allows for interaction, but I don't want the text to be editable in any way.

How would I go about doing this?

# Answer
> 1 votes
I haven't tested it, but I would likely implement something where any attempts to change the text simply don't change the text. For example, there's an `onValueChange` event for the `InputField`. Attaching to this event and simply setting the text to its initial value will revert any changes made by the user.

This simple script achieves the desired effect:

```
public class InputFieldLockdown : MonoBehaviour {
    InputField textObject;
    string myText = "This is the text";

    void Start () {
        //Get the inputfield script and set its text value to the initial value
        textObject = this.GetComponentInChildren<InputField>();
        textObject.text = myText;
    }

    public void ValueChanged()
    {
        //When|if the value changes, reset it to its initial value
        textObject.text = myText;
    }
}

```

Attach this script to your InputField object. Next you'll need to associate the event in the Unity editor:

The only downside to this is pressing the backspace key, still causes the input caret to move backwards. This is a fairly minor downside though.

---
Tags: unity, gui, text
---


# Question
Title: Libgdx detect touch on a specific object (while moving)
I have a class (I'll call it with letter "A") and class B.

A is the object (as a character) and B is the rendering class which have the aim to show A.

I am looking for a way to detect when A is pressed, with normal InputProcessor I can't because it detect touch in the entire screen, I only want detect touch over the object. If I check touch position and "A" position it doesn't work because the object is moving and the values aren't so precise

How to solve?

**this didn't solve for me** :Efficient way of detecting a touched object in a game?. Here is explained "what to do" and not "how to do"

# Answer
What you need to do is assign a listener to the Actor (I assume you are using these). This is as simple as (if you are trying to detect clicks):

```
myActor.addListener(new ClickListener() {
    public void clicked(args) {....
});

```

Then put whatever you want to happen in that `clicked` method. Make sure your game's input processor is that Stage! (`Gdx.input.setInputProcessor(myStage)`)
> 1 votes

---
Tags: libgdx, touch, screen
---


title: Direct3d 9 z-buffer fails drastically

text:
# Question
Title: Direct3d 9 z-buffer fails drastically
I have just completed my custom mesh class and my engine is very basic right now, but now I am facing this strange issue. I have posted the pictures bellow, it seems like z-buffer is not working properly. I am using the following for projection matrix

```
D3DXMatrixPerspectiveFovLH((D3DXMATRIX*)&m_proj, toRad( 45.f ), aspect_ratio, 0.f, 100.0f );

```

and this is my clear call

```
void Context::clear( Vec4& color )
{
    if( this->m_is_lost ) return;
    this->m_device->Clear(0, NULL , D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_XRGB(0,0,50), 1.0, 0);
}

```

If I give anything other than 0 for near plane the model barely shows up and if camera is zoomed the geometry seems to be appearing partly and disappearing. I know that my view matrix is ok because if I use 0 near plane the geometry is rendered correctly but then the flickering happens. I used simple HLSL posted bellow. If someone faced the same situation please assist me..

EDIT : I used blender to export mesh to custom format, although unlikely but is there any winding order issue causing this problem??

```
void GameApp::renderScene()
{
LPDIRECT3DDEVICE9 dev = ((LPDIRECT3DDEVICE9)Engine::Context()->ptr());
HRESULT hr = 0;
Matrix u;
bool res;

w = u;
v = m_cam->view_copy();
p = *Engine::DefaultView()->fov();

Matrix wvp = w * v * p;

hr = dev->SetRenderState(D3DRS_DITHERENABLE, TRUE);
hr = dev->SetRenderState( D3DRS_LIGHTING, FALSE );
//dev->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
hr = dev->SetRenderState( D3DRS_ZENABLE, TRUE );
hr = dev->SetRenderState( D3DRS_STENCILENABLE, FALSE );

dev->SetTransform( D3DTS_PROJECTION, (D3DXMATRIX*)&p);

res = this->sh->vs_wvp( wvp );
res = this->sh->tex0( m_tex );
res = this->sh->use();

this->m_mesh->test_draw();

dev->SetPixelShader(NULL);
dev->SetVertexShader(NULL);
 }

```

```
#include "constants.hlsl"

struct VS_INPUT
{
    float3 position  : POSITION0;
    float3 normal    : NORMAL0;
    float2 tex0      : TEXCOORD0;
    float4 color0    : COLOR0;
};

/* vertex shader output */
struct VS_OUTPUT
{
    float4 hposition : POSITION0;
    float4 color0    : COLOR0;
    float2 tex0      : TEXCOORD0;
};

VS_OUTPUT main( VS_INPUT IN )
{
    VS_OUTPUT OUT = (VS_OUTPUT)0;
    OUT.hposition   = mul( float4( IN.position, 1.0 ), gWVP );
    OUT.tex0        = IN.tex0;
    return OUT;
}

```

/\* The pixel shader \*/

```
#include "constants.hlsl"

sampler gTEX0;  /* primary texture */

struct VS_OUTPUT
{
    float4 hposition : POSITION0;
    float4 color0    : COLOR0;
    float2 tex0      : TEXCOORD0;
};

struct PS_OUTPUT
{
    float4 color : COLOR;
};

PS_OUTPUT main( VS_OUTPUT IN )
{
    PS_OUTPUT OUT;
    OUT.color = tex2D( gTEX0, IN.tex0 );
    return OUT;
}

```

# Answer
The near plane parameter shall be strictly larger than zero.

The smaller it is the more precision you burn close to the camera, and with zero, the projection matrix degenerates into unusability.

If your geometry isn't where you want it to be when you use a conformant projection matrix, address that problem instead.
> 3 votes

---
Tags: c++, directx
---


title: How to draw 2d above 3d scene?

text:
# Question
Title: How to draw 2d above 3d scene?
I have an OpenGL(3.3)+GLEW application. I want to draw a black vertical rectangle at the left side of the window for writing some information on it, like fps (I use GLEW function for drawing text).

I have a common pipeline, like this:

```
 m_transformation = PersProjTrans * CameraRotateTrans *
           CameraTranslationTrans * TranslationTrans *
           RotateTrans * ScaleTrans;

```

I know how it works, but I can't figure out how to draw a projection of the rectangle on the window, like 2d.

I would be glad to any advise.

# Answer
> 1 votes
You can use an *Orthographic projection* matrix to transform your vertexes. Then you can simply provide your triangle verts in terms of screen pixels, e.g.: a vertex at (0,0), one at (10, 0) and one at (5, 10).

Here's another reference of OpenGL matrices, with a lot of maths. Make sure to do a search for "OpenGL orthographic projection" and "2D drawing with OpenGL" and you should find a lot of useful information also.

I should also note that to overlay 2D over 3D, you'll have to disable depth testing before drawing the 2D parts. I.e.: `glDisable(GL_DEPTH_TEST);`.

---
Tags: opengl, 2d, 3d, projection, pipeline
---


# Question
Title: How can I keep AI from getting stuck on each other?
I'm currently working on AI and, as stated above, I'm having trouble figuring out how to keep the AI from getting stuck on each other.

More specifically, I'm working on two different behaviors for the AI:

1. The AI form a group of four, determine which one of them is the strongest and bravest (whichever has the highest number), make that one the leader and then snake behind the leader. This doesn't workout because the leader ends up getting stuck on the others as they attempt to walk through him to form a line.
2. The AI moves from one room to another. This doesn't work out because the one changing rooms will get stuck on ones that are doing other things or even on other room changing AI.

The way I've programmed it, AI traveling to a destination will calculate which tile gets it closer to it's goal (they use jump point pathfinding to find their way around) and then they calculate which tile they'll move to the next turn. Other AI check to see if a traveling AI is around them and if there is, they move one space to the side (or at least they're supposed to move.)

Does anyone know a way to keep this from happening?

# Answer
I've seen some people address this by having AI mark the path they plan to walk on as more expensive for other AI. This has the effect of some avoidance between agents but since it isn't time aware (the future path is more expensive always, not just when the agent will be there in the future) it can make some odd behavior if it is too strong of an effect. Another way people deal with this is to let the AI in this situation either slide past each other instead of getting stuck, let AI push each other around a bit to let them through, or even just allow them to walk through each other (sometimes only when there are no other options). There are other ways to solve it but these are a few ideas. There are entire research papers dedicated to this topic so the right answer depends on your specific needs (:
> 1 votes

# Answer
this is my first time helping on a question and is hard for me to understand others when they dont use a graphic exaple. Apologies in advance.

Considering that your game is turn based and your AI units can only move one tile per turn, and considering that they get stuck so easily, then I have to make some assumptions on how you game works and offer at the same time some solutions to your problem.

Case 1.- Your game maps have small corridors, passages, doors,obstacles,and so forth or AIs are positioned too close, so they can't turn around each other : In this case you have to use the help of a "wait" variable whenever there is no way to move, and keep it until the leader frees more space to move. You can either alternate the other AIs order on the snake formation. If the leader got stuck because it can't pass through the other AIs you can add a "switch position" method to switch position whenever they cant move.

Case 2.- Your maps are big but your AIs get stuck because the AIs still want to pass through each other(or your algorithm is not that complex) or they want to have an specific formation no matter where the leader is pointing at or want to go: In this case you can do what you already stated, make the occupied tiles more expensive, you have to treat them as total obstacles. You can also apply the "switch" and "wait" methods to make it easier.

If your AIs can move through more than one tile per turn then you can just let them pass through each other but dont letting them stay in the same tile and using the wait method whenever they just cant move.
> 0 votes

---
Tags: c#, ai, path-finding
---


# Question
Title: Ortho projection of 3D points with a vector
I have 3D points and I need to make an 2D orthographic projection of them onto a plane that is defined by the origin and a normal `n`. The meaning of this is basically *looking at the points from the top (given the vertical vector)*. How can I do it?

What I'm thinking is:

1. project point P onto the 3D plane: `P - P dot n * n`
2. look at the 3D plane from the "back" in respect to the normal (not sure how to define this)
3. do an ortho projection using max-min coordinates of the points in the plane to define the clipping

I am working with iOS.

# Answer
> 0 votes
If you're working to build a 3D viewport you probably want a projection matrix. Which means in addition to your normal *n* you also need to define an "up" vector in the plane. That is, if the plane represents the screen of the iPhone, you need a vector that shows which direction the top of the iPhone is.

Then, your *n* vector crossesd with your up vector will give you a third vector, orthogonal (at right angles) to the first two. (Also, your *n* vector should be orthogonal to the up vector, but that should happen automatically if the up vector is already in the plane).

Once you have your three vectors, normalize them, and put them as the columns in a 3x3 matrix. If you want the x and y coordinates to be in the plane, with the z coordinate being the distance from the plane, put the crossed vector you calculated as your first column, the up vector as the 2nd column, and *n* as the third.

Then you simply multiply your point P by your matrix M to get a new point P' (that is, P * M = . P'. Or if you want to think of the points as column vectors, do M^T P = P'). P'.x,y will be in the plane, and P'.z will be the distance from the plane, which you can drop if you're projecting on to the plane.

Note that this doesn't do anything around scale or translation of the points, or clipping things to the viewport. If you want all of that you probably want a full fledged Model-World-Camera-View-Projection-Clip transformation pipeline, and it gets more involved. It's an old book but the Cg Tutorial had a good section explaining the basic transformation flow.

---
Tags: ios, geometry
---


# Question
Title: How do I publish to Google Play if I'm under 18?
I've finished my first Unity and want to release it on the Google Play store but can't because I am under 18. The main issue is that Google Wallet requires you to be over 18. How could I work around this?

# Answer
From the Google Wallet ToS:

> By agreeing to the Agreement, You represent the following:
>
> 1. You are 13 to 17 years of age and creating a Google Wallet account for the sole and limited purpose of redeeming Google Play Gift Card value for select items that are eligible for purchase by You on Google Play, subject to applicable laws and upon Google's discretion; or
> 2. You are 18 years old or older and You are capable of entering into a legally-binding agreement.

I would suggest you ask a parent/tutor to create it for you. It might be a bit too much to ask them to manage all your stuff for you, but you could try and convince them to help you for the legal responsibility (c.f. *legally-binding agreement*), and you use the account the way you need to (and don't do stuff that would surprise them :P).
> 4 votes

---
Tags: legal, publishing
---


# Question
Title: Property replication vs RPC notifications
I'm not talking about something such as an object position, which changes very often. I'm talking about some object state that may be changed infrequently, such as a door opening and closing.

Would it be better to send an RPC to saying "The door is opening/closing" or would it be better to replicated a property that tells us the objects state? Obviously this can be done both ways, but what are the advantages/disadvantages of each?

As far as I know any competent implementation will only consider replication for properties that have changed. This means when the property does actually change, it should have the same cost( assuming it must be reliably replicated ) as sending an RPC. The other advantage to doing this would be removing the need for more complex RPC buffering. If a client connects, they get sent the state, no need to buffer/unbuffer things.

All I can see is advantages for replicating over RPCs in this case. However, I always see suggestions to have as few replicating properties as possible.

# Answer
If you're using, for example, Unity's standard networking without an authoritative server, an RPC would be better because syncing something every frame can be VERY expensive because the packet header is some 20-40 bytes of bandwidth overhead in addition to the identification of the object being synced. You end up sending a lot more data than necessary.

This, compounded with the potential of having many doors, leads to a very straightforward decision. Generally, the less objects you need to constantly sync, the better.

Using an RPC does complicate some things, as you've mentioned (i.e. player joining later). Buffered RPC's would be overkill since you only need the last state change - not all of them. Instead, you can just send an RPC to the new player from the Master Client giving the game state. Your game can be semi-authoritative in that you delegate the responsibility of syncing 'everyone else', people who join later or get desynced, to a single client.

Useful Note: RPCs are reliable in Unity networking (not sure about Unreal) so you don't have to worry about your doors getting desynced as long as you send the message and the client is connected. If the client disconnects then comes back to the game, its sync should be handled by the Master Client.
> 2 votes

---
Tags: architecture, networking
---


# Question
Title: Coroutine to move to position passing the movement speed?
I'm using this coroutine to move my player to a new position. The problem is that it takes the duration as an argument instead of the speed of the object. Which makes it hard for me to make sure the object always moves at the same speed.

How can I create a coroutine that takes the source position, target position and movement speed to move my character?

This is my current code:

```
IEnumerator MoveObject(Vector3 source, Vector3 target, float duration)
{
    float startTime = Time.time;
    while(Time.time < startTime + duration)
    {
        player.transform.position = Vector3.Lerp(source, target, (Time.time - startTime) / overTime);
        yield return null;
    }
    player.transform.position = target;
}

```

# Answer
> 8 votes
You can use something like this:

```
 IEnumerator MoveFromTo(Transform objectToMove, Vector3 a, Vector3 b, float speed) {
         float step = (speed / (a - b).magnitude) * Time.fixedDeltaTime;
         float t = 0;
         while (t <= 1.0f) {
             t += step; // Goes from 0 to 1, incrementing by step each time
             objectToMove.position = Vector3.Lerp(a, b, t); // Move objectToMove closer to b
             yield return new WaitForFixedUpdate();         // Leave the routine and return here in the next frame
         }
         objectToMove.position = b;
 }

```

The main thing to note is the step calculation. It first takes the input speed (in m/s) and projects its value on the distance between the source (a) and the target (b). Then it is multiplied by `Time.fixedDeltaTime` (Look at @DMGregory's comments) to get the projected distance.

# Answer
> 1 votes
When talking about 'speed' there are a couple of ways of thinking about it. You can think about it one way, like 'meters per frame' (ie: for each frame, I want the player to move X meters). For that type of functionality, see this:

```
public IEnumerator MoveAtSpeedCoroutine(Vector3 end, float speed){
    //while you are far enough away to move
    while (Vector3.Distance(this.transform.position,end)>speed){
        //MoveTowards the end position by a given distance
        this.transform.position = Vector3.MoveTowards(this.transform.position, end, speed);
        //wait for a frame and repeat
        yield return 0;
    }
    //Since you are really really close, now you can just go to the final position.
    this.transform.position = end;
}

```

The problem with this way is it can look weird if the framerate is not perfectly constant.

The other way (and the best way) would be to keep track of 'meters per second'. This way, if the game lags out for a couple of frames, it should still look just fine (ie: if you want to move X meters over 1 second, and if you get a constant 100 frames per second, each frame the object will be moved X/100th of a meter; Whereas, lets say I get to a really choppy part of my game (heaven forbid) that the game was lagging for the whole second, and only ran one frame in one second, then the object would be moved X/1). In the first way, if I ran the same game on two computers, and the first computer was laggy and the second one wasn't, and I played my game (lets say a racing game), then the laggy computer would always lose and it will always move slower than the non-laggy computer. Whereas with the second way (code below), even if one computer laggs a bunch, they both should keep neck and neck (even though on the non-laggy computer will look a bunch better :D) The code for the second way is as follows:

```
public IEnumerator MoveAtSpeedCoroutine(Vector3 end, float speed){
    while (Vector3.Distance(this.transform.position,end)>speed*Time.deltaTime){
        this.transform.position = Vector3.MoveTowards(this.transform.position, end, speed*Time.deltaTime);
        yield return 0;
    }
    this.transform.position = end;
}

```

Note, the only change is multiplying speed by Time.deltaTime - this converts it from 'meters per frame' to 'meters per second'. Why this works is Time.deltaTime is the amount of time that passed last frame (a percent out of 1 second). If the computer lagged out for a whole second, Time.deltaTime would be 1, and if your game rendered at 200 FPS (5ms total render time) for this frame, then Time.deltaTime would be 0.005. If you multiply your speed by this number, then no matter your framerate is, that speed is the amount of meters the object will move in 1 second.

With that said, you could do this with lerp as well (I don't care for it in this instance myself... but this is an option). You can do it like so:

```
public IEnumerator MoveAtSpeedCoroutine(Vector3 end, float speed){
    Vector3 start = this.transform.position;
    //total time this has been running
    float runningTime = 0;
    //the longest it would take to get to the destination at this speed
    float totalRunningTime = Vector3.Distance(start,end) / speed;
    //for the length of time it takes to get to the end position
    while (runningTime<totalRunningTime){
        //keep track of the time each frame
        runningTime += Time.deltaTime;
        //lerp between start and end, based on the current amount of time that has passed
        // and the total amount of time it would take to get there at this speed.
        this.transform.position = Vector3.Lerp(start, end, runningTime/totalRunningTime);
        yield return 0;
    }
    this.transform.position = end;
}

```

And even more still, one way to look at speed is using physics. So... you got a lot of choices :D

Hope that helps and good luck! :D

ps. Scale...

I would do that as follows:

```
public IEnumerator MoveAtSpeedCoroutine(Vector3 end, float speed){
    //figure out the scale you want to use - here I will just take the average scale
    float scale = (this.transform.localScale.x+this.transform.localScale.y+this.transform.localScale.z)/3;
    //lets now use the scale to make a new speed. The new speed will be based off of the old speed
    //and also the scale.
    float speedAtScale = scale * speed;
    while (Vector3.Distance(this.transform.position,end)>speedAtScale*Time.deltaTime){
        this.transform.position = Vector3.MoveTowards(this.transform.position, end, speedAtScale*Time.deltaTime);
        yield return 0;
    }
    this.transform.position = end;
}

```

# Answer
> 0 votes
Perhaps something like this:

```
[RequireComponent(typeof(Rigidbody))]
public class MovementTowardsTarget : MonoBehaviour
{
    private void Start()
    {
        var target = GameObject.Find("Target");
        StartCoroutine(MoveObject(target, 1.0f));
    }

    private IEnumerator MoveObject(GameObject target, float speed)
    {
        var direction = target.transform.position - transform.position;
        GetComponent<Rigidbody>().velocity = direction * speed;
        yield return null;
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject == GameObject.Find("Target"))
        {
            GetComponent<Rigidbody>().velocity = Vector3.zero;
        }
    }
}

```

If you are looking for something more verbose, you may be able to tweak a script I wrote for 2D games. It would be the MovePositionInLine() method. Source Code here.

Also this script could be exactly what you are looking for. Not sure what you are trying to accomplish, but its worth a look.

# Answer
> 0 votes
You can do this:

```
void moveObjectBySpeed(Vector3 source, Vector3 target, float speed)
{
  pathLength = (target - source).magnitude;
  duration = pathLength / speed;
  moveObject(source, target, duration);
}

IEnumerator moveObject(Vector3 source, Vector3 target, float duration)
{
    float startTime = Time.time;
    while(Time.time < startTime + duration)
    {
        player.transform.position = Vector3.Lerp(source, target, (Time.time - startTime) / overTime);
        yield return null;
    }
    player.transform.position = target;
}

```

# Answer
> -1 votes
Get the velocity to move at based on the object's size and the speed. Move with that velocity. Then keep checking if the object has passed the target.

```
IEnumerator MoveObject (Vector3 source, Vector3 target, float speed)
{
    int Dot1 = (int)Mathf.Sign(Vector3.Dot(source, target)); //Get the original orientation
    int Dot2 = Dot1; //This is the current orientation
    Vector3 velocity = (target - source).normalized * speed * player.Size; //Get the velocity to travel at
    while (Dot1 == Dot2) //If the original orientation and current orientation are the same, we haven't passed the target yet
    {
        player.transform.position += velocity * Time.deltaTime;
        Dot2 = (int)Mathf.Sign(Vector3.Dot(player.transform.position,target)); //Get and set the current orientation
        yield return null;
    }
}

```

---
Tags: unity, movement
---


title: FBX UV Coordinates is strange

text:
# Question
Title: FBX UV Coordinates is strange
i want correct UV Coordinates model likes this model

but Model load and render at my importer result is likes this

My fbx uv coordinates extract code is here

```
     FbxLayerElementUV* layerUVs = pMesh->GetLayer(0)->GetUVs();
                if (NULL != layerUVs)
                {
                    int uvIndex = 0;
                    FbxLayerElement::EReferenceMode referenceMode = layerUVs->GetReferenceMode();
                    FbxLayerElement::EMappingMode mappingMode = layerUVs->GetMappingMode();

                    if (FbxLayerElement::eByPolygonVertex == mappingMode)
                    {
                        int id = pMesh->GetTextureUVIndex(j, k);
                        if (FbxLayerElement::eDirect == referenceMode ||
                            FbxLayerElement::eIndexToDirect == referenceMode)
                            uvIndex = id;
                    }
                    else if (FbxLayerElement::eByControlPoint == mappingMode)
                    {
                        if (FbxLayerElement::eDirect == referenceMode) uvIndex = iControlPointIndex;
                        else if (FbxLayerElement::eIndexToDirect == referenceMode)
                            uvIndex = layerUVs->GetIndexArray().GetAt(iControlPointIndex);
                    }
        FbxVector2 uv = layerUVs->GetDirectArray()[uvIndex];

        vtx.u = (float)uv[0]; vtx.v = (float)uv[1];
        vtx.u = 1 - vtx.u; vtx.v = 1 - vtx.v;

```

What I do, can we solve this problem?? Please Answer to me

# Answer
```
vtx.u = 1 - vtx.u; vtx.v = 1 - vtx.v;

```

Are you sure of this part ? The texture seems to be upside-down on the screen shot. The model looks mirrored as well.
> 1 votes

# Answer
Try

```
vtx.v = 1 - vtx.v;

```

But there is no need to

```
vtx.u = 1 - vtx.u;

```

Reference http://forums.autodesk.com/t5/fbx-sdk/uvw-coordinates-are-importing-upside-down/m-p/4179680#M3489
> 1 votes

---
Tags: fbx
---


# Question
Title: Looping OpenAL sounds with one buffer - or how to do it correctly?
I require to implement a statically played sound class which supports looping of the audio data - and requires this to be changed at runtime (e.g., turning off looping).

Maybe I understand something horribly wrong, but this is how I understood how to implement looping at all, and came to the following solution:

* I have exactly **one** buffer containing all the audio data.
* If looping is enabled, ensure that the source playing the sound has this buffer queued twice, so it replays the sound when the end of the current buffer has been reached:

```
if (Loop && _source.BuffersQueued == 1)
{
    _source.QueueBuffers(_buffer);
}

```
* If a buffer has been processed (e.g. right after the sound audibly loops), it is unqueued and dismissed.

```
if (_source.BuffersProcessed > 0)
{
    _source.UnqueueBuffers(_source.BuffersProcessed); // Unqueue outdated buffers
}

```

Here I ran into the first problem: If the user sets the sound to **not** loop anymore, I cannot unqueue the upcoming buffer (to make it not loop over another time while looping has already been turned off).

This is because I only found methods to unqueue by the **handle** of the buffer, but since I queue the same buffer twice, the handle is always the same to the one currently playing. OpenAL tries to unqueue the currently played buffer then, which obviously fails.

Unqueuing by the **number** of processed buffers also doesn't help, as no buffer has been marked as processed yet.

Do I really need to completely duplicate the buffer with all the audio data, keep it stored twice in memory, just to have two different buffer handles to unqueue the second buffer if looping gets disabled?

# Answer
> 7 votes
There is a simpler way to do looping:

`alSourcei(source, AL_LOOPING, 1);` enables it for a source and
`alSourcei(source, AL_LOOPING, 0);` disables it.

---
Tags: sound, openal
---


title: AABBs in lwjgl 2.9.3

text:
# Question
Title: AABBs in lwjgl 2.9.3
I think I have succeeded in making an aabb out of 6 quads in opengGL but how would i get it to stay with its centre-point at the centre-point of all objects. I know it is easy for one object how would I do it automatically for all objects?

# Answer
# Calculating the AABB in Model Space

The first step is to calculate the **AABB** in **model space**. Model space coordinates are the vertex positions that describe the model locally (often the object is described as standing in the origin of your editing application). You seem to have this step down, but just in case, here are the steps to follow:

1. **Iterate** through all **vertices** of your model and store the **minimum** and **maximum** **x-**, **y-** and **z-coordinates** of their positions.
2. **Generate quads** for each of the planes described by these coordinates. Eg: the x-min plane is made up of vertices: *(x-min, y-min, z-min), (x-min, y-max, z-min), (x-min, y-max, z-max) and (x-min, y-min, z-max)*. Buffer them for rendering.
3. If your model is **animated**, you will need to repeat this process **every frame**, if you want the AABB to smoothly follow the object. If you have a **limited number of poses**, or just a single pose (ie. no animation), you can **precalculate** your **AABB(s)**.

---

# Transforming the AABB Along with the Model

What happens next in your rendering procedure, is to **transform** the model's **model coordinates** to **screen coordinates** (via three transforms: the **model**, **view** and **projection** transforms). These are the actual positions the model occupies on your screen, after being positioned in your game world, viewed through a camera and projected onto the screen. These transformations are typically applied via matrix products in your vertex shader using a **model matrix**, a **view matrix** and a **projection matrix** respectively.

If you want your AABB to "follow" your object, you simply need to **apply the same transformation** to its vertex positions. Specifically, you will want to use the transformation matrices as you used on the model.

One note on this: your **bounding box** will **rotate along with the object** if you apply the model transform to it. In this case, your bounding box is axis aligned with the model. If you want it to align with the world axes, you will need to calculate the min and max x-,y- and z-coordinates after moving to world coordinates. This also means you only need to run it through the view and projection transforms (as the model transform has already been applied). Note that this is way more expensive in terms of processing power, and the bounding box needs to be recalculated for every change in position, rotation, scale or frame of animation (whereas a local AABB should only be recalculated for a change in frame of animation).

---

In summary, you can simply apply the same transformations to your AABB, as those which are applied to your model during rendering. I believe that your current approach is to calculate the AABB directly on the model in it's world coordinates (after applying the model transform). Instead, you may find it easier to simply calculate the AABB locally, with respect to the model in model coordinates, and then "move it into position (and rotation and scaling)" using the same transforms used on your model.

You can find a little more info on the transformations and coordinates spaces here: How can I calculate the orthographic projection needed to encompass an object with arbitrary rotation?
> 0 votes

---
Tags: lwjgl, aabb, casual-games
---


title: 2D Sprites vs UI Image Scripts in Unity

text:
# Question
Title: 2D Sprites vs UI Image Scripts in Unity
I am doing a 2D casual puzzle where the user can drag and drop some pieces into a board. The pieces are 2 or 3 or 4 tiles. Each tile may have text over the sprite.

Target platform: Mobiles and tablets.

I wonder if the right approach is to use 2D sprites or to use UI images for displaying the board, the tiles and the pieces on it.

On one side, doing all the game based on UI elements seem weird. On the other side, if I do it based on sprites, how do I attach texts on the sprite?

Which approach should I pick?

# Answer
> 3 votes
In my experience these are the two most important differences between Sprites and UI Images: 1. Images need to be inside a UI Canvas and they use a RectTransform instead of the regular transform. This means they can use the new anchor/pivot features and their positions will be in pixels instead of units. 2. It's more convenient to handle clicks and other mouse events using EventTrigger

I usually prefer to make a distinction between UI elements and gameplay stuff so in your case I would probably use Sprites for the gameplay elements. Adding text is easy but you need to know how :) You can add a Canvas as child of the sprites, configure it to live in "world space" and then scale it down to fit in the dimensions you want.

There are multiple posts in the Unity forums explaining how to do this but ask if you can't figure it out.

# Answer
> 0 votes
I think it's simple!

Just use TextMesh and draw it over the Sprite. It's in the Component menu at: Mesh \> Text Mesh

# Answer
> 0 votes
Well in UI, you can use more stuff to help you. For example, grid layout which helps you align all the pieces in grid automaticly. Also handling mouse events is way easier with ui elements, eg for drag and drop there are events for that.

There is also option to use UI inside world space..

Ps: im writing this answer on mobile. I can provide more info later on.

---
Tags: unity, sprites, image
---


# Question
Title: Hierarchical "Select GameObject" Dialog or names with prefixes?
I am attempting to connect a series of teleporters with entrances inside a single scene. Once the player touches a teleporter he is moved to another place. I am doing this by simply connecting two game objects as shown in the following screenshot. The particle system in the center of the upper side is used as teleporter, the red line indicates the game object where the player will be transported to.

Sadly, this results in an utter mess when attempting to select a new entrance the teleporter should link to. There is no way to guess which entrance corresponds to which side and dice:

**So the tl;dr of my problem would be this: The name of the object that should be selected is meaningless when isolated. It's the path to the object (or in other terms: the name of some parent) that is relevant.**

I would see three possibilities to solve this, but sadly I haven't gotten around to find out how to do any of them.

1. Switch the "Select GameObject" Dialog to use the same hierarchical view as used in the scene viewer. Is there a hidden option somewhere in Unity that I overlooked?
2. Somehow prefix the names of my entrances programatically. Is there a way to include the path to a certain game object in its name?
3. My whole approach is backwards and I am doing something in a not Unity friendly way. But what would be the "correct" way to do this?

# Answer
You can attach custom script to any gameobject you want to use as destination call it for example TeleportDestination.

In your entry teleport script you can use public property type TeleportDestination, now unity will pops you only objects with TeleportDestination and not all gameobjects.

Note: TeleportDestination needs to be MonoBehaviour. Note 2: you can create a method in TeleportDestination for teleporting and use it with more entry types later on with same teleporting logic.

Ps: i wrote this answer on mobile. I would go deeper otherwise, sorry. Hope it helps
> 1 votes

---
Tags: unity
---


# Question
Title: Windows 8 C# Compile spritefonts for MonoGame without XNA
Hello Stack Exchange community. Recently, I've been attempting to in some way generate sprite-fonts into XNB files for use with MonoGame. The issue is however, as you may be aware, XNA is very incompatible with Windows 8 without a very ridiculous amount of tweaking(even the installer its self has issues). Is it in any way possible to generate XNB files from sprite-fonts to be used with MonoGame, or is MonoGame doomed on the ability to use fonts in a Windows 8 development environment? Also keep in mind, it would 'appear' that the popular method of bitmap font loading also has compatibility issues with Windows 8. If there is no way of doing this with sprite-fonts, can you suggest any alternative libraries for C# that would allow for similar functionality to MonoGame with the ability to draw font effectively on a Windows 8 system? Any help is appreciated, thanks. Keep in mind, I am developing for Windows Desktop, not Metro.

# Answer
I don't think you need XNA any more.

Just double click on Content.mgcb to open the content editor.

Right click on Content -\> Add -\> New item -\> Spritefont description, give it a name, e.g. "testfont"

Load your spritefont in game:

```
var font = Content.Load<SpriteFont>("testfont");

```

Use it!

```
spriteBatch.DrawString(font, "hello", new Vector2(10, 10), Color.AliceBlue);

```
> 1 votes

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


# Question
Title: wrongly scaled on cocos2dx 3.2 when render to multiple fbo (more > 1 deep)?
i have bug that only happen when retina flag disabled.

i try draw multiple render texture to achive some multi post effect: so i have 3 render texture,

fbo 1 for final pos effect
fbo 2 for back buffer w/light
fbo 3 for light mask

i apply this using fbo mechanisms of cocos2dx push the fbo1 to screen
push the fbo2 to fbo1
fbo 3 just for sampler texture for render in fbo2 shader

gameplay actor will be drawn on fbo2, after that fbo2 will be rendered to fbo1 ( we can apply some effect here) then fbo1 drawn to screen, then do some gui layering.

the thing is all gp actor drawn into fbo2 , "seems" become scaled down 3 times, so its like the small game screen on left bottom corner, but the light from fbo3 or gui that directly drawn to screen normal positioned and not scaled .

i really dontknow who is scale my fbo2, but i check the matrix its all correct. but seems lot setviewport in rendertexture.h, idont know how its work actualy, so if any one know how viewport work on fbo,

* no direct open gl acces for my code except attach shader
* if i dont use fbo2 one, ( using fbo1 directly ), the bug doesnt happen
\** this doesnt happen on retina true ( scaled 2x ) , this happen on win32 or mac when i disabled retina ,
\** tracing draw order correcty
\** log below on command:
onbegin fbo1
onbegin fbo2
onbegin fbo3
( i render some sprite to this fbo first ex: alpha gradient mask)
onend fbo3
( i render gp actor here)
onend fbo2
( render attached fbo2 texture with shader carries sampler of attached texture 3)
onend fbo1
( render attached fbo1 texturee)\* may caries some shader
( render gui part )

# Answer
its fixed now,

onbegin always set the viewport.

because onEnd method the viewport restored to the original screen viewport regardless its return to another fbo. so everytime more than \> 1 deep will call viewport with scale of screen, this causing mess because the screen viewport has design ratio. so fix it by ensuring the viewport to original set for each fbo before its.
> 0 votes

---
Tags: opengl, cocos2d-x, viewport, frame-buffer, fbo
---


# Question
Title: problem with SCNTransaction in Scene Kit
I'm trying to move an object over a period of ten seconds from y coordinate 0 to y coordinate 10. the object is created at y coordinate 0. The problem is when the animation starts, the object pops to the end position for like one second or so then pops back down to the starting position and begins the animation properly. Why is the object ending moving to the end location instantly, and how can I prevent this from happening?

```
//create box bottom
func createGrabBox() {
    grabbottom = grabBox.rootNode.childNodeWithName("grabbottom", recursively: true)!
    grabbottom.position.y = 0
    grabbottom.geometry!.firstMaterial!.transparency = 0.5
    grabbottom.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: nil)
    grabbottom.physicsBody!.restitution = 0.0
    grabbottom.physicsBody!.friction = 1.0
    grabbottom.physicsBody!.categoryBitMask = ColliderType.grabBottomCatagory.rawValue
    grabbottom.physicsBody!.collisionBitMask = ColliderType.diceCatagory.rawValue
    scene.rootNode.addChildNode(grabbottom)

    //animation snippet
    SCNTransaction.begin()
    SCNTransaction.setAnimationDuration(10.0)
    SCNTransaction.setCompletionBlock() { }
    grabbottom.position.y = 10
    SCNTransaction.commit()

    //physics field for this object
    let field = SCNPhysicsField.linearGravityField()
    field.strength = 0
    field.direction = SCNVector3(x: 0, y: 0, z: 0)
    field.categoryBitMask = ColliderType.grabBottomCatagory.rawValue
    //only things with categories that match the field's will be affected by it
    let fieldNode = SCNNode()
    fieldNode.physicsField = field
    scene.rootNode.addChildNode(fieldNode)
}

```

# Answer
I found that it is because I was using a dynamic body rather than a kinematic body. I still have a bit of learning in regards to how physics works with scene kit.
> 1 votes

---
Tags: 3d, animation, ios, swift, scenekit
---


# Question
Title: What is an efficient packing algorithm for packing rectangles into a polygon?
I need to put as many rectangle of same size as possible inside a polygon. The algorithm can put rectangles in different orientation(angle). But they cannot overlap. This is image is an example of the end result:

# Answer
> 5 votes
This is called the **Pallet Loading Problem**. Solving it is actually pretty hard, and we don’t know of an exact solution that always works in reasonable time. And sometimes the solution is not intuitive at all, see for instance:

Here is a comprehensive list of existing algorithms (Recursive Five-block Algorithm, L-Algorithm, Recursive Partitioning Algorithm) with full source code. The same authors have a web application that lets you enter your own data and see the result.

# Answer
> 4 votes
In this sample you can find an algorithm to pack small textures into a big texture, that is quite similar to your matter... and maybe a good start to solve it.

http://create.msdn.com/en-US/education/catalog/sample/sprite\_sheet

EDIT:

You can use a tree, where the leafs have empty regions, and the rest of nodes have the rectangles. You can iterate deeply to get a solution.

## Algoritm

At first pass, the node contains the empty region. There are four combinations for adding the rectangle, by the orientation ( Vertical, Horizontal) and the way that region will be divided.

Add the four combinations.

Choose the first child,

Try to add next rectangle, adding every combination as before

If there are no room for the rectangle go back, and test next child of this parent.

Repeat that until there is no more rectangles to add.

---
Tags: algorithm
---


# Question
Title: User extendable content with Contentmanager
I developed a towerdefense game that uses xml-Files for almost everything, (creeps, levels, towers, upgrades). Those Xml-files define properties like textures, sounds and values like hitpoints.

My goal is to give the user the power to add and modify those things, which will be some kind of editor in the future probably. For now it shall be notepad...

So this makes using the ContentManager impossible i guess, since it needs to compile the data into those xnb Files.

I dont have a problem to use XmlSerializer, but how does it work for textures or sounds? Do i need to write my own code for loading the texture into vram etc?

Do i need to reinvent the wheel here and write my own ContentManger or can I make use of an existing feature?

I found a few "similiar" questions but none really gave me an answer.

# Answer
> 1 votes
There are some workarounds to this problem without needing to completely reinvent the wheel. For example, you should be able to load any file from any location using the TitleContainer.OpenStream method.

Then, once you have the stream you can convert it into a Texture2D.FromStream method. Of course, you'll need to do your own research to figure out how to load each of the different content types and some of them may not be supported on all platforms.

Perhaps something like this (untested):

```
using(var stream = TitleContainer.OpenStream("your-file.png"))
{
    return Texture2D.FromStream(GraphicsDevice, stream);
}

```

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


title: Libgdx Actor touch undetected

text:
# Question
Title: Libgdx Actor touch undetected
I am looking for detect touch in an actor. The touch in my game is detected in wrong part of the screen. I want to detect touch only on the red circle, here is the code:

**Static\_values**

```
public class Static_values {

    static public float Width = Gdx.graphics.getWidth();
    static public float Height = Gdx.graphics.getHeight();

}

```

**Circle class:**

```
public class Circle_Obj extends Actor{

    private Vector2 position;
    private float radius;

    private float speedX;
    private float speedY;

    private com.badlogic.gdx.math.Circle circle;
private Texture texture;

    public Circle_Obj(float x, float y, float radius) {

        position = new Vector2(x,y);
        this.radius = radius;

        speedX = 5.5f;
        speedY = 5.5f;

        circle = new com.badlogic.gdx.math.Circle(x,y,radius);
        texture = new Texture(Gdx.files.internal("texture.png"));

        this.setSize(Static_values.Width,Static_values.Height);
        this.setPosition(position.x,position.y);
        this.addListener(new InputListener(){
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log("TOUCHED", " TOUCHED ");
                return true;
            }
        });

    }

    @Override
    public void draw(Batch batch, float parentAlpha) {

        this.setSize(Static_values.Width,Static_values.Height);
        this.setPosition(position.x,position.y);
        batch.draw(texture, position.x, position.y, radius, radius);
}

```

**Screen class :**

```
public class GameScreen implements Screen {

    private Stage stage;
    private Circle_Obj circle_obj;

    public GameScreen() {

        circle_obj = new Circle_Obj(Static_values.Width/3, Static_values.Height/3, Static_values.Width / 100 * 10);

        stage = new Stage();
        stage.addActor(circle_obj);

        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.draw();

    }
/** other methods **/

```

**Colored area = area where touch is detected :**

# Answer
If you want your hit detection to be as accurate as possibly, you need to correctly set your actor's size and position. For your example, this would probably go something like this:

The circle's constructor:

```
public Circle(Texture tex, Vector2 position) {
    this.tex = tex;
    this.setPosition(position.x, position.y);
    this.setSize(tex.getWidth(), tex.getHeight());
    this.addListener(new ClickListener() {
        public void clicked()...
    });
}

```

Then the circle's draw method:

```
public void draw(Batch batch, float parentalpha) {
    batch.draw(tex, this.getX(), this.getY(), this.getWidth(), this.getHeight());
}

```

This way, the actor will be the size of the texture that is being drawn, and even if you have the constructor accept values for height and width, the texture will be adjusted and drawn to fit the actor.

Try using the code I provided (more or less) directly and let me know if you have any trouble.
> 1 votes

---
Tags: java, libgdx, touch
---


title: Nested ipairs for basic hit detection

text:
# Question
Title: Nested ipairs for basic hit detection
I'm developing my first game using *Löve*, the game is a basic Asteroids clone. Everything is going well so far, until I decided to actually add asteroids.

I'm trying to make a basic hit-detection that checks if a bullet is within the boundaries of an asteroid, then deletes both of them.

The issue is that if I do this:

```
for i, v in ipairs(bullet) do
    for i, ast in ipairs(asteroid) do
        i fv.y < 20 + ast.y and v.y > ast.y - 20 and v.x < 20 + ast.x and v.x > ast.x - 20 then
             table.remove(asteroid, i)
             table.remove(bullet, i)
        end
    end
end

```

It deletes the asteroid that was hit, but a random bullet rather than the bullet that hit the asteroid. If I split the code, it only deletes either the asteroid or the bullet, whichever is run first. If I reverse the ipairs, the bullet disappears, but a random asteroid is removed instead of the one that got hit.

Tl;Dr, How do I properly use nested ipairs?

# Answer
The problem is a typical starters error: you chose both loops iteration variable to be the same, so they modify each other.

You should always choose nested loops to use a different iteration variable(usually called i, j, k), otherwise things will get messed up. In other languages completely, but here you got the two objects already and using the keys only to remove, so only the removal part got messed up.

The correct code should be:

```
for i, v in ipairs(bullet) do
    for j, ast in ipairs(asteroid) do -- instead of i you have j here
        i fv.y < 20 + ast.y and v.y > ast.y - 20 and v.x < 20 + ast.x and v.x > ast.x - 20 then
             table.remove(asteroid, j) -- changed here to j as well
             table.remove(bullet, i)
        end
    end
end

```
> 0 votes

---
Tags: collision-detection, lua, love2d
---


# Question
Title: how change branching logic to math equivalent glsl?
im totally newbie and this just for fun

afaik lot of best practice suggest to minimize usage of branching.

can you help me optimize below glsl especially on branch part? ( target 120 )

the bgcolor used for minimum color level, what i want is alpha outcome become 0.1 if the bgColor choosen on the current fragment otherwise it will get the data from uniform.

bgColor n uLightIntensity will same value for all fragment aplied within this shader.

the texcolor will be varies for each fragment ( depend on texture pixel presentation)

```

    varying  vec3 v_fragmentColor;
    varying  vec2 v_texCoord;

    uniform sampler2D u_texture;
    uniform  float u_lightIntensity;
    uniform vec4 u_bgColor;

   void main()
{

    vec4 texColor = texture2D(u_texture,  v_texCoord);

    // TODO POSIBLE OPTIMIZE FOR NON BRANCHING
    if(step( u_bgColor.r, texColor.r) == 0.0)
    {
        texColor.a = 0.1;
    }else
    {
        texColor.a =  u_lightIntensity/10.0;
    }
    texColor.rgb = max(texColor.rgb, u_bgColor.rgb);

    gl_FragColor = texColor;

}

```

# Answer
> 1 votes
replace your whole if-statement with this:

```
float vstep = step( u_bgColor.r, texColor.r);
texColor.a = mix(0.1, u_lightIntensity/10.0, vstep);

```

mix will *select* either the 1st argument of the mix if vstep == 0, or the 2nd otherwise (which is vstep == 1)

---
Tags: glsl, optimization, fragment-shader
---


title: How to map texture to shape in Slick 2D

text:
# Question
Title: How to map texture to shape in Slick 2D
I need to map texture to shape. Texture:

This is a example of shapes I need to map texture to:

Notice that each piece in mesh has exactly 4 point to map texture. Logic is pretty straight forward: Top center edge to top in mesh etc.

I found some methods on Graphics object like texture(...) however these methods cannot handle diamond texture properly..?

I found this method:

```
ShapeRenderer.texture(shape, image, generator)

```

Where generator is:

```
org.newdawn.slick.geom.TexCoordGenerator

```

However I don't understand How It can be used to map the image to the shape.

How to use it? Is there other way?

# Answer
> 2 votes
I didn't found an API for this in Slick library. So I wrote a class which does it for me (groovy code):

```
class Stretched {

    Shape shape
    Image image

    Stretched(Shape shape, Image image) {
        this.shape = shape
        this.image = image
    }

    void render() {

        TextureImpl.bindNone()
        image.getTexture().bind()
        SGL GL = Renderer.get()

        GL.glEnable(SGL.GL_TEXTURE_2D)
        GL.glBegin(SGL.GL_QUADS)

        GL.glTexCoord2f(0.5f, 0f)
        GL.glVertex2f(shape.points[0], shape.points[1])

        GL.glTexCoord2f(1f, 0.5f)
        GL.glVertex2f(shape.points[2], shape.points[3])

        GL.glTexCoord2f(0.5f, 1f)
        GL.glVertex2f(shape.points[4], shape.points[5])

        GL.glTexCoord2f(0f, 0.5f)
        GL.glVertex2f(shape.points[6], shape.points[7])

        GL.glEnd()
        GL.glDisable(SGL.GL_TEXTURE_2D)
    }
}

```

This takes a Shape (polygon w/ 4 vertexes) and map diamond texture to it.

---
Tags: java, slick
---


title: unity how to keep prefabs updated

text:
# Question
Title: unity how to keep prefabs updated
I have a number of prefabs in unity and I regulary update them, is there an easy way make sure unity updates these prefabs so that I don't have to update 20+ identical objects in identical ways acros 10 different scenes?

# Answer
When changing prefabs, you have to hit the "Apply" button to commit the changes. This is the only part you're missing.
> 1 votes

---
Tags: unity, workflow
---


# Question
Title: Performance of programming languages and frameworks
I want to program an online 2D MMORPG with graphics like in this game. Since I develop in javascript and python mainly I chose python for my first games and the game library pygame which is pretty straightforward and awesome. But since many people go for c++, c# etc. I wonder if I still could achieve what I want to with python. Is anybody experienced with performance with python and pygame in cases like this? should I rather go for c++? Should I use a combination of python and C, or maybe even python and c++?

# Answer
As an answer to this question and to most of the comments.

Try making some other games first. Since you are a beginner, creating a multiplayer tic-tac-toe (as Shiro suggested) will be hard enough. Even if you can manage to create that creating an MMO is a massive task that most of us, and definitely the beginners, will underestimate.

For example: how will you track player movement on other clients, if you're going to do PVP how are you going to send messages so that the other player knows he's been hit. What about, connecting and disconnecting to servers. Will you be creating a Peer-to-peer game, will it be a server-client architecture (with a dedicated server). How will you manage lag and hackers? This and many other questions will arise, which you will probably not think of when you start this.

If you want to continue doing this, create a simple chat system using python first. (you can do this with telnet, which is included in the basic installation of python). If you can manage that, create a VERY simple 2-player game. If you can manage that, go on to creating a game where people can connect to a main pc (p2p host or dedicated server) and see if you can make the players move and make the server send that information to all other connected clients.

TL;DR: It's great that you want to try this but slow down, think about it, realise that this is not just "connecting pc's and I'm done".
> 1 votes

---
Tags: c++, performance, python, mmo, pygame
---


# Question
Title: How can I simulate the gravity of a sphere instead of a plane?
How can I simulate the gravity of a sphere instead of a plane?

For a naval warfare game, I wish to implement a surface that simulates a curved plane with horizon. The plane is rendered with water physics, which needs, along with all physical objects, avatars and projectiles, to respond to gravity as a focal point rather than a distributed surface.

# Answer
> 5 votes
It depends on the effect you are looking for.

If you are looking for a constant gravity the answer is:

```
object.AddForce(((Vector) sphere.center - (Vector) object.pos).normalized * gravityForce);

```

If you are looking for a gravity based on the distance between the object and the sphere then you replace gravityForce with this formula:

```
gravityForce =  6.673×10^(−11) * sphere.mass * object.mass / Distance(sphere.center, object.pos);

```

# Answer
> 2 votes
You simply need a reworked Newton's law of universal gravitation.

So F=G(M1\*M2)/R2 translates as code into.

```
// Create force scalar based off of distance.

distanceSquared = (gravityCenter.y - object.y)^2 + (gravityCenter.x - object.x)^2

force = gravitationalConstant*distanceSquared

// Get direction from object to gravity epicenter.

direction = arctangent2(gravityCenter.y - object.y, gravityCenter.x - object.x)

// Transform vector into into coordinate based impulse.

object.xVelocity += force*cosine(direction)
object.yVelocity += force*sine(direction)

```

Then adjust gravitationalConstant to suit.

NOTE: Unless you want to send ships into space, implementing gravity based on distance is completely a waste of cycles as a constant "downwards" force is more processor friendly.

---
Tags: physics
---