title: Error in Finding Nearest Hexagonal Tile

text:
# Question
Title: Error in Finding Nearest Hexagonal Tile
Using Openfl for a game using hexagonal tiles

Working out the problem of walkability in a game, and I've run into an issue with my Hexagonal tiles. I think it is an odd rounding error of sorts. When heading down on the left side of tile, for a moment the nearest returns the coordinates of the tile on the right side. So the coordinates I get from the bellow nearest causes the "no walk" area for each unwalkable (water in this case) tile to be the area in red on this image.

```
public function nearest(pos:Point):Point
{
  var real_x:Float = pos.x + character.xOffset;
  var real_y:Float = pos.y + character.yOffset;
  var pos_y:Float = ((real_y + yOffset) / tileHeight)+1;
  var pos_x:Float = ((real_x  + xOffset - ( pos_y%2 * tileWidth/2) ) / tileWidth);
  return new Point(Math.round(pos_x),Std.int(pos_y));
}

```

For reference, this is how my map is laid out, later the map data will be read in from a file and not hard coded into the application.

```
public function createMap()
{
  map.push([0,0,0,0,0,0,0,3,0,0]);
  map.push([ 0,0,0,0,0,0,3,0,0,0]);
  map.push([0,0,0,0,0,0,3,0,0,0]);
  map.push([ 0,0,0,0,0,3,0,0,0,0]);
  map.push([0,0,0,0,0,3,0,0,0,0]);
  map.push([ 0,0,0,0,3,0,1,1,0,0]);
  map.push([0,0,0,0,3,0,1,2,1,0]);
  map.push([ 0,0,0,3,0,0,1,1,0,0]);
  map.push([0,0,0,3,0,0,0,0,0,0]);
  map.push([ 0,0,3,0,0,0,0,0,0,0]);

  walkMap.push([true,true,true,true,true,true,true,false,true,true]);
  walkMap.push([true,true,true,true,true,true,false,true,true,true]);
  walkMap.push([true,true,true,true,true,true,false,true,true,true]);
  walkMap.push([true,true,true,true,true,false,true,true,true,true]);
  walkMap.push([true,true,true,true,true,false,true,true,true,true]);
  walkMap.push([true,true,true,true,false,true,true,true,true,true]);
  walkMap.push([true,true,true,true,false,true,true,true,true,true]);
  walkMap.push([true,true,true,false,true,true,true,true,true,true]);
  walkMap.push([true,true,true,false,true,true,true,true,true,true]);
  walkMap.push([true,true,false,true,true,true,true,true,true,true]);

  tileData = [];
  for (row in 0...map.length)
  {
    for (cell in 0...map[row].length)
    {
      tileData = tileData.concat(
        [
          (tileWidth * cell + ((row%2) * (tileWidth/2))) - xOffset,
          (tileHeight * row) - yOffset,
          map[row][cell]
        ]
      );
    }
  }
}

```

What is causing the issue, where is my math off that I'm getting this odd effect?

**Update:**

The tile mapping from the above code should look like (realizing that I haven't taken the corners into account yet):

But instead look like:

They are not diagonal at all (like DMGregory suggests in his answer), the the top of them where the corners live is shifted by 1/2 a tile width, and I don't see why.

I could force the the tops to the right half a tile after (and that might be what I end up doing), but the code above *should* work, and I don't see where it is off by half a tile.

The bit DMGregory is doing at the bottom of his answer is what I was starting to work on to try and solve the corner problem (except the corners are at the top, not the bottom), when I realized what the shifting bug that's really going on really is.

# Answer
> 3 votes
Here are the areas your nearest function associates with each tile:

(assuming float % int is performed as a floating point modulo in your environment. If not, you can get broken/offset tiles instead, as visualized in the third image above)

As a unit travels down and to the left, they briefly touch the stretched/offset corner of the tile below and to the right, causing the issue that you describe.

If you floor the value of pos\_y used in calculating pos\_x (adjusting offsets as needed) you'll get something like this instead:

```
var pos_x:Float = ((real_x  + xOffset - (Std.int(pos_y)%2 * tileWidth/2) ) / tileWidth);

```

This is closer to correct (the tile adjacencies are right, although top & bottom borders are the wrong shapes), and may be close enough for your needs.

If you need to be more accurate yet, take a look at the two white lines in the image above. Every point in the red rectangle above those two lines is correctly-categorized - it's only the two triangles at the bottom that are mismatched. (I deliberately shifted the tiles vertically to line them up this way)

So we can apply a minor correction to these points:

(Here, I'm assuming tileX & tileY are the outputs of your old nearest function, ie. integer tile row & column indices, so a tile's right neighbour is at tileX+1. pos\_x & pos\_y are the values before they've been rounded/floored)

```
// Get the fractional offset of the point from the bottom center of the tile:
fracX = pos_x - tileX;  // Range -0.5...0.5
fracY = pos_y - tileY;  // Range 0...1

// Identify points inside the miscategorized triangles
if(abs(fracX) * 2 > fracY * 3)
{
   // Because of offset coordinates,
   // which side needs its x corrected depends on whether we're in an even or odd row:
   if(fracX > 0) // Bottom-right corner
   {
      tileX += tileY % 2 - 1;
   }
   else  // Bottom-left corner
   {
      tileX += tileY % 2;
   }

   // Assign row to the one below
   tileY -= 1;
}

```

(I'm making some assumptions about which way your axes point & your data is laid out, so you may need to make minor tweaks)

Getting something that looks like this:

You can see the area in those two bottom triangles still gets caught by the rectangle for the tile above, but this correction ensures they get assigned to the right tile (here visualized with colour)

This is a little bit hacky for my taste, but it's probably the smallest change that will correct your nearest() function.

If you're up for more refactoring, I think the strategies described at the link provided by @madneon in the comments above will give you a more elegant and robust solution. This will require working in axial rather than offset coordinates as you are now, but this makes a lot of the tile math more consistent, with fewer special cases.

# Answer
> 0 votes
I'm not totally sure I understand your question. You are having trouble converting a position into a hexagon coordinate? If so I did some research on turning a vector position into a hexagon coordinate that might help you out.

But first of all I highly recommend this website for general hexagon coordinate information:

http://www.redblobgames.com/grids/hexagons/

and this is the website I used to do the coordinate conversation calculations.

http://playtechs.blogspot.co.uk/2007/04/hex-grids.html

The coordinate systems we use are different but you should be able to quickly modify it to suit your needs. I simply made a struct Hex that uses a coordinate system described in the redblobgames link and then used the second link with my coordinate system to design my Nearest function. You can follow along with my math and the second link to easily create yours.

**System : (R : rows, Q: columns)**

```
   +R
  /HH\+Q
-Q\HH/
   -R

```

Some calculations I made using that blog post an example:

**R Matrix Solutions :**

```
[edge/2, radius]  = [1, 0]

[-edge, 0] = [0, 1]

A = 0,    B = 1/radius,    C = -1/edge,    D = 1/diameter

```

**Q Matrix Solutions :**

```
[edge/2, -radius] = [1, 0]

[edge/2, radius] = [0, 1]

 A = 1/edge,    B = -1/diameter,    C = 1/edge,    D = 1/diameter

```

**Formulae**

```
l = Floor(z / radius);
m = Floor(z / diameter - x / edge);
R = Floor((l + m + 2) / 3);

n = Floor(x / edge - z / diameter);
o = Floor(x / edge + z / diameter);
Q = Floor((n + o + 2) / 3);

```

**C# Code**

```
/// <summary> Return the Hex whose center is closest to the Vector3 position </summary>
public static Hex NearestHex(Vector3 pos) {
    double t1 = pos.x / edge;
    double t2 = pos.z / diameter;

    double r = Math.Floor( (Math.Floor(pos.z / radius) + Math.Floor(t2 - t1) + 2 ) / 3);
    double q = Math.Floor( (Math.Floor(t1 - t2) + Math.Floor(t1 + t2) + 2 ) / 3);

    return new Hex((int)q, (int)r, (int)(pos.y / height));
}

```

# Answer
> 0 votes
If I understand your question correctly, you are trying to find the center of the hex cell to which an arbitrary point belongs. Your question made me think of **Voronoi diagrams**... I have a gut feeling that they might be relevant here, though other solutions might have a better performance. (This solution might be wrong too, but I feel like it could be relevant.)

# Voronoi Diagrams

A **Voronoi diagram** is a pattern of **cells**, with each cell containing one predefined **point**. Each cell holds all positions ("pixels" if you will) for which the cell's point is the **nearest neighbour**. In other words, a all positions get assigned to the nearest predefined point. In even other words, the borders of the cells represent positions that are equidistant to at least two points. The image below is an example of an **arbitrary Voronoi diagram** (taken from http://wikid.eu/):

Depending on how your points are positioned, you'll end up with a different Voronoi diagram. If you align your points as "*horizontal lines, with all odd lines being offset by 50% of the horizontal distance between points*" you'll end up with a **hex pattern** as in your example. You can adjust the vertical spacing between lines of points to "flatten" your hexes as in your post. The image below shows the layout of the points visually (image edited from http://www.designcoding.net/):

---

# Solution 1: Closest Hex Center by Comparing Center Points

The clue of this, is that your hex grid is a Voronoi pattern. This means: to figure out **which hex** (Voronoi cell) a point belongs to, you only need to **consider the distance of the point to the hex center** (Voronoi cell center). A brute force solution would be to iterate through all your hex-centers (ie. horizontal lines of points, with odd rows shifted by 50% of the tile width) and just find the one with the closest distance to your point.

---

# Solution 2: Closest Hex Center by Comparing Four Points

To speed up this brute force solution, you could note that there is no need to check all **hex centers**. Instead, you only need to **check four**:

1. From the row of points above, take the closest point that is smaller or equal in x-coordinate
2. From the row of points above, take the closest point that is strictly larger in x-coordinate
3. From the row of points below, take the closest point that is smaller or equal in x-coordinate
4. From the row of points below, take the closest point that is strictly larger in x-coordinate

These points are shown in the image below:

Now, as in solution 1, just calculate the distances to all these hex center points. The closest point indicates the center of the nearest hex cell.

---

# Solution 3: Closest Hex Center by Comparing Two Points

To save a minuscule amount of processing time, you could note that only **two points** need to be **checked**. Instead of taking two points of the row above, and two points of the row below, only take one point of each row. Choose the point that is closest in x-coordinate. After all, when calculating the distance to these points, only their x-distance is different (*dist = sqrt(pow(x\_dist,2) + pow(y\_dist,2));* ). Note that this trick doesn't work to compare points of different rows, as their x-coordinates are not aligned (due to the shift of odd rows).

The image below illustrates this. You'd do roughly the following steps:

1. Find the two nearest points in the row above (steps 1 and 2 in solution 2)
2. Discard the one with the largest x-distance to your point (brown lines in the image)
3. Find the two nearest points in the row below (steps 3 and 4 in solution 2)
4. Discard the one with the largest x-distance to your point (brown lines in the image)
5. Calculate the distance to these two points, and use the one that is closest (as in solution 1)

Basically, what is happening is that your check the "vertical boundaries" of your hex cells in steps 1 through 4. In step 5, you check one "diagonal boundary" to figure out what cell the points belongs to.

---

In short, you can find the cell to which a point belongs by calculating the distance to the center of all hex cells (as your hex pattern is similar to a Voronoi diagram). You can further optimize this by noting that you don't need to compare to all hex centers. In fact, you only need to compare to two.

**Note:** I did not check this solution myself, I'm just writing this based on some quick Google searching and gut feeling. Specifically, it is possible that you won't be able to make the Voronoi hex pattern match your hex pattern exactly (especially the slope of the diagonal borders). It could be a good approximation though.

---
Tags: collision-detection, tiles, tilemap, haxe
---


# Question
Title: How to only render fragments with Z from 0 to 1 in OpenGL?
I have been using OpenGL for a year now, but I just recently found out that OpenGL only clips vertices when the absolute value of the x,y or z coordinate is less than the absolute value of w coordinate. Previously I had assumed that the z coordinate would have to be 0 \< z \< w to be rendered. Is there any way to clip vertices with z less than 0, without a performance hit?

I am using OpenGL 4.4

# Answer
I believe that OpenGL's standard clipping volume is *\[-1, 1\] x \[-1, 1\] x \[-1, 1\]*. You want to clip at *\[-1, 1\] x \[-1, 1\] x \[0, 1\]*. You can achieve this by transforming the z-coordinate after all transformations have been applied to the vertex position (model, view and projection transforms). In other words, you want to operate on the screen coordinates of the vertex.

---

# On Homogeneous Coordinates

I'll quickly go over the ***w* coordinate** you are mentioning, so you understand what is happening. The w-coordinate is used to represent a **3D point** in a **4D homogeneous representation**. This representation is used to make matrix math more simple. Specifically, it lets you use a 4x4 matrix to perform translations, something which you can not do with a 3x3 matrix and 3D point representations.

As you are using a 4D representation for a 3D point, many combinations of 4 coordinates will describe the same 3D point. The actual position of your point can be obtained by dividing all components of the 4D representation by *w*. So for example, point \[x,y,z,w\] is located at the following 3D coordinates: \[x/w, y/w, z/w\].

This explains why you observed clipping at *z \> w*. As in fact, the z-coordinate becomes *z/w*. Knowing that clipping occurs at z-coordinate \> 1, you'll find that this is at:

```
    z-coordinate > 1
<=> z/w > 1
<=> z > w

```

---

# Solution: Clipping Between Z-Values 0 and 1

If you want to **clip in range \[0, 1\]** instead of the default \[-1, 1\], you simply need to **remap the z-coordinate** to this range. You'll want to do this after all vertex transformations have been applied in your **vertex shader**, so that you are working with **screen coordinates**. These are the coordinates where clipping is applied.

To remap, simply do:

```
z_new = (z_old * 2) - 1;

```

This will make sure, vertices which originally had z-coordinate 0, get mapped to -1. Coordinates with an original z-coordinate of 1 stay at 1. Everything in between is a linear interpolation of the two.

As you are just doing a small additional calculation per vertex in your vertex shader, you won't notice a hit in performance.
> 3 votes

---
Tags: opengl, glsl, clipping, frustum-culling
---


# Question
Title: "Hold to jump higher" suddenly outputs a much higher jump
I'm programming my first game in Unity and I'd like to make a very controllable jump.

The idea is to apply an upward force while the player is still pressing the jump button, and then after some time ignore jump input. Kinda like how Mario and Mega Man jump.

Problem is, somehow, my character occasionaly jumps much higher than it normally does.

I set three variables on the inspector:

* jumpImpulse: the initial speed after pressing the jump button;
* riseAcc: the acceleration applied to the character while holding the jump button;
* maxJumpHoldTime: the longest possible time one might hold the button while still rising.

```
if ((onGround || onPlatform) && Input.GetButtonDown("Jump")){ //GetButtonDown prevents holding jump and keeping jumping

    rb.AddForce(Vector2(0,(jumpImpulse/rb.mass)), ForceMode2D.Impulse); //force that starts the jump itself.
                                //  /rb.mass makes F=ma into F=ma/m ==> F = a, so "Force" is actually acceleration.
                                //  This is to better control mass and jump mechanics.
    jumping = true;

    //DEBUG
    debugJumped = true;
}

if (jumping && Input.GetButton("Jump")){

    rb.AddForce(Vector2(0,(riseAcc/rb.mass)), ForceMode2D.Force); //first acceleration

    jumpHoldTime += Time.deltaTime;

    if (jumpHoldTime >= maxJumpHoldTime) {
        jumping = false;
    }

} else {

    jumping = false;
    jumpHoldTime = 0;

}

//Made this so I know how high the character jumps.
if (debugJumped && (!onGround) && rb.velocity.y <= 0){
    Debug.Log ("Jump height is: " + transform.position.y);
    debugJumped = false;
}

```

In the console, the jump height is listed normally as 2.376213, but sometimes it appears as 5.008272. It appeared once as 2.377432. Also, this variation seems to appear more frequently when I'm also moving the character left or right.

And I'm not sure if this is related, but there are many times when I press the jump button and the character simply doesn't jump.

Also, I put everything here under the FixedUpdate function.

# Answer
In my experience handling input in fixed update is a bad idea.

All your input handling should be in Update() and physics work in FixedUpdate().

I'm not quite sure if this will completely fix your issue but it sounds like the cause of:

> And I'm not sure if this is related, but there are many times when I press the jump button and the character simply doesn't jump.

Once you apply this fix let me know if you are still getting moments of increased jump height.
> 0 votes

# Answer
This problem I believe comes down to controlling the player velocity. Check what the object's velocity is before and after applying force and apply other forces accordingly. This way other forces that may or may not be acting on your character wont stop it from completing consistent jump arcs
> 0 votes

# Answer
It seems like you want to apply a steady upward force to the character while the button is held down. This force should be equal to whatever downward forces (like gravity) are acting on it so the character's velocity will remain unchanged.

If the upward force you apply every time Update is called is greater in magnitude than the downward forces are, your character will *accelerate* upward. This means each time Update is called, your speed will be greater and greater. This could get out of hand quickly, and may be the source of your problem.

Also, it seems like you are using transform.position.y to measure the height of the jump. This will give you the character's altitude in the world, not how far off the ground she has jumped. For example, if the character was on a platform that was 5 units off the ground, and you can jump 2 units high, transform.position.y will be 7 at the apex of the jump.
> 0 votes

---
Tags: unity, jumping
---


# Question
Title: Directional light and finding relevant shadow casters
Right now when culling the models to render for the directional light shadow map pass I just do a view frustrum culling using the main camera. At some angles, the objects will be outside the view but still obviously should cast shadows.

My question is, how do you cull/gather all the relevant shadow casters for a directional light?

# Answer
There is an advanced technology based on compute shaders that will analyze the depth buffer of the main camera, and return the min depth, and max depth, with 1 pixel precision (reduce operation). This information can be used to create a very precise frustum for the shadow camera. Elements outside the view that casts shadows are only in the frustum that goes from the viewed zone to the light. (oblique in the direction of the lighting).

One issue with this is that you don't know the min/max before rendering the world, and you need the shadow map to render the world. So to palliate to that, you can simply use a min/max pair that is one frame late. And to mitigate potential little artefacts if the player moves too fast, you can inflate the volume slightly by some epsilon.
> 3 votes

# Answer
I don't do a frustum cull with the main camera, but the shadow camera alone.

I calculate the AABB (axis aligned bounding box) of the shadow camera, then do the culling with that. A directional shadow camera is a box in itself (orthographic projection matrix projects to a side of the box). After the box is rotated (for different light direction), the AABB can still be computed easily (but it will be a little bigger than originally, so it is a bit wasteful).
I compute it like this: Rotate every corner of the bounding box, then find the new min and max corner from the bunch of new coordinates. An AABB is essentially just a pair of min and max points.

You can check AABB-AABB intersections after that which should be quite fast.
> 1 votes

---
Tags: directx11, shadows, shadow-mapping
---


# Question
Title: Does the order in which RPCs are called match the order they are invoked locally?
For example:

```
void A()
{
    Debug.Log( "A was called." );
}
void B()
{
    Debug.Log( "B was called." );
}
void C()
{
    NetworkView view = GetComponent<NetworkView>();
    if( view != null )
    {
        view.RPC( "A", specificNetworkPlayer );
        view.RPC( "B", specificNetworkPlayer );
    }
}

```

Is A guaranteed to be called before B on the "specificNetworkPlayer"'s machine? If not, what is the order, if any?

# Answer
From the documentation:

> RPC calls are always guaranteed to be executed in the same order as they are sent

So, yes, it's guaranteed to execute `A` then `B` as your code defines it.
> 3 votes

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


title: Marching Cubes Chunks

text:
# Question
Title: Marching Cubes Chunks
I'm doing some voxel based game, where I want to have voxel planets. I decided to use the marching cubes algorithm, and I successfully created a planet (even with noise) with the following density function:

"x*x+y*y+z\*z -r - someNoiseFunction()" no problem there...

But as it comes to implementing chunks to my voxel planet, I run into some problems. I tried various things to "cut" my planet into parts but I wasn't successful. I tried copying the density values from the level array to some other chunk arrays, but somehow if I do that, the result is not what I was expecting. being more preceisly, the result was no mesh to a complete other mesh.

Now another idea came to my mind. With 3 FOR loops I could iterate through every voxel in the level array and check if it IS IN THE CHUNK, and check if it IS IN THE SPHERE. IF IT IS the density value it positive, if it IS NOT the density value is negative. so I could iterate through every chunk and in the end I have some chunks, which form my planet if I put them together... but before I spend another day coding some code which is maybe nonsense I might ask you guys what do you think about this idea, or are there better solutions for getting a sphere chunked with marching cubes?

# Answer
no matter what you do you'll have to run through the triple for loop to set up the float values to input into the marching cubes. normally you would use some form of noise to create 2d/3d maps. in your case I would do something like define a size, and then change all blocks to positive if their absolute x,y,z values added together equal less than the size\*1.43. I do that in 2d to tell my voxel chunks which should render around the player, otherwise the corner are way farther out than the center of the edges.

give each section a worldPoX, worldPosY, worldPosZ and then within it an x,y,z. use the worldPos values along with the chunkSize to determine where its personal cubes are.
> 0 votes

---
Tags: unity, voxels, sphere, marching-cubes
---


# Question
Title: Basic multiplayer matchmaking implementation
I am currently writing a matchmaking server application for a 5vs5 UDK game.

Here is the scenario on which I built my code:

1. The player starts the game and authenticate
2. The player clicks an huge "Play" button and asks the server for an open lobby
3. The server searches for a lobby and adds the player to the lobby found, and sends back lobby informations to the player so it can react accordingly (lobby id, players in lobby). Note that if no lobby is found (all lobbies are full, or there's no lobby at all) then a new one is created.
4. The player (now in a lobby) selects a character and hits a "Ready" button.
5. Once all players are ready, the server searches for an opposing team
6. Once an opposing team is found, the server sends match infos (udk server ip and port) to all of the concerned players

I have written my matchmaking server with the C# Web Api template. This RESTful webservice can at the moment take care of steps 1, 2 and 3 as they are transactions between the frontend (player in UDK game) and the backend (the C# matchmaking server). The player asks for something, the server replies with JSON data. I have done so because having many HTTP requests seemed less foolish than having all authenticated players on a constantly alive TCP connection.

However, for the next steps (**particularly the steps concerning what happens inside the lobby**), I am undecise on what approach I should take. How can the server notify the players of new events (disconnections, new player, character chosen by a player, player ready...)? Should the players poll the server on a (very) regular basis for new events? Or would it be better to have a pool of threads to keep a TCP connection alive with the players in order to broadcast new events? Or something else? (UDP?). I'm kinda lost.

This is my first post so I hope it's not poorly phrased. Thanks.

# Answer
There are a lot of things that you need to consider. First of all, where are you hosting your servers? UDP works great if your hosting your own hardware, but if you're using something like AWS then you'll end up spending a lot of time trying to get a good reliable solution. UDP traffic can not be load balanced using the default load balancer, so you'll have to expose individual instances to the users. The same goes for Azure and Google services.

Also, if you're targeting mobile, then forget about UDP. Mobile data carriers have sporadic support for UDP. Sometimes it will work, other times it will not. I am aware that you can check if a user is on their cell network or using Wifi, but limiting the users to only play while they are wifi in order to use UDP is not a good solution in my opinion.

The best way I've found to support in-game events is either through sporadic polling over TCP from the client or long polling and TCP keep-alive sessions.

Sporadic polling is better if your requests are lightweight and atomic in nature. however if you need to guarantee order then go with a long polling keep-alive connection.

Keep in mind that you have a limit to how many sockets/threads you can create per box. Sockets are limited to something like 16 million(16,777,214 to be exact), but threads are much worse. With threads, it's possible to get a few hundred going, but that is not advisable. Threads require a chuck of contiguous memory in order to allocate the stack, so you will quickly run into the upper bounds of memory once you start to create/shutdown threads per connection.

Lightweight polling with atomic checking is by far your best choice if the server uses thread pooling and automatically handles keep-alive connection pooling.

Oh, and by atomic operations, I mean the following definition: Atomicity is a guarantee of isolation from concurrent processes(from Wikipedia). How you implement server-side atomic operations is another subject altogether, but for a quick reference, take a look at how CouchDB handles conflict resolution.
> 1 votes

# Answer
I would use the same method of communication that you will be using once the game begins. You're only delaying the inevitable by using these other methods. I don't know what you'll be using during the game, but now is the time to find out.
> 0 votes

# Answer
For a multiplayer game I'm creating I use a simple port system. Specific ports are used for specific traffic. So in my game I use ports 20551, 20552, 20553, 20554 etc, and each one serves a different purpose.

For example, port 20551 waits to receive update packets from a player containing their current position, rotation, etc. It takes this and distributes it to all other players so everyone in the session is synchronised.

In your game you could have a port for joining/leaving on your server. Send JSON data to this port containing whether it is a join/leave as well as information. If it is a leave request you will need to send the player's ID who just left so he can be removed from the session and you're not continually sending his data (such as position) to the other players after he is gone. Similarly with a join request you have to send down information about the joined players so the other players can be updated with the new data.

I recommend looking into the UdpClient class. You will probably also find you need to run methods asynchronously as the `UdpClient.Receive()` method used to wait for receiving data will hang your thread and freeze the application until it receives something.

I'll try and grab some source code for you tomorrow.
> 0 votes

---
Tags: c#, multiplayer, udk, matchmaking
---


title: Accessing a newly Instantiated Object

text:
# Question
Title: Accessing a newly Instantiated Object
I currently am creating a script that allows the player character to attack by shooting orbs at foes.

I have the current code to do that (not final code, for testing purposes):

```
if(Input.GetButton("Fire1"))
    {
        print("firing");
        GameObject newOrb = (GameObject) Instantiate(MagicOrb, this.transform.position, Quaternion.identity);
        BasicAttackOrb orbControl = newOrb.GetComponent<BasicAttackOrb>();
        if (MoveHandler.facingRight)
            orbControl.SetDirection(BasicAttackOrb.RIGHT);
        else if (!MoveHandler.facingRight)
            orbControl.SetDirection(BasicAttackOrb.LEFT);

    }

```

So I create the new orb projectile, instantiate it, and then attempt to set the direction.

In the orb script:

```
public class BasicAttackOrb : MonoBehaviour
{
    public const int LEFT = -1;
    public const int RIGHT = 1;

    public float orbSpeed = 15.0f;

    public int direction;

    // Use this for initialization
    void Start ()
    {
        direction = 0;

    }

    // Update is called once per frame
    void Update ()
    {
        if (direction == LEFT)
            this.transform.Translate(-1.0f * orbSpeed * Time.deltaTime, 0.0f, 0.0f);
        else if (direction == RIGHT)
            this.transform.Translate(1.0f * orbSpeed * Time.deltaTime, 0.0f, 0.0f);

    }

    public void SetDirection(int dir)
    {
        direction = dir;
    }
}

```

So, if the direction is RIGHT (aka 1) it flies right. If it's LEFT (aka -1) it flies left.

However, the orb direction stays at 0, and is never set. This indicates to me that the initial code above in the `Input.GetButton("Fire1")` block is incorrect.

Am I accessing the GameObject incorrectly? I feel like it's just a slight coding error with objects but for the life of me I can't find it.

# Answer
> 2 votes
After some more testing, it appears the problem was the Start() method.

Apparently, for whatever reason, the code was being executed as follows:

orbControl instantiated -\> SetDirection() -\> Start()

Thus, because of this, direction remained 0.

So, I changed Start() to Awake(), and all's well.

It appears to me after more research that this is the main difference between Start() and Awake(), and that generally one should look to use Awake() for initialization.

# Answer
> 0 votes
Drop in a couple breakpoints and see if either of the MoveHandler condition blocks are actually visited in the following code :

```
if(MoveHandler.facingRight)
    -> orbControl.SetDirection(BasicAttackOrb.RIGHT);
else if (!MoveHandler.facingRight)
    -> orbControl.SetDirection(BasicAttackOrb.LEFT);

```

Since those lines are responsible for changing the direction variable, they seem like the likely culprits.

Alternatively change the 'else if' to 'else' to ensure it hits at least one statement.

---
Tags: c#, unity, 2d, gameobject
---


# Question
Title: Saving virtual goods balance in Android Game
I'm looking for a good way to store virtual goods and virtual currency balance in an Android game. Since these are "consumable" or "unmanaged" goods the balance is not backed up by Google and so there is a need for a solution that is:

* Can't be hacked easily
* Can easily be extended with additional goods and currencies
* Survives application shut down and device boot

# Answer
> 5 votes
Here's a slightly different take on the matter: Of the users who would bother to crack your game's data format or decompile it and change it, how many do you think are actually willing to pay for these things? In other words, if these users were to try and fail to cheat your game, do you think they would then give up and pay you money for the items?

Furthermore, are these people going to influence other users elsewhere?

If this is a game where users interact with each other (e.g. a MMO), and these paid items give users an advantage over other users, then the items, purchases, and player interactions need to be tracked on your server, so that your server can verify all interactions involving items, that the items were paid for and not yet used. The client side cannot be trusted; there's no way to definitively prevent hacking.

If this is not the case (e.g. Temple Run), why waste your effort trying to stop users who probably wouldn't pay you anyway, and who aren't affecting other paying users?

---

As for your other two sub-questions, just store them however you want to store your data. You already found the different ways to store data, as you posted in your answer, so read through them, figure out which ones will satisfy your requirements, and then pick whichever one you think would be best and go with it. All of them survive shutdown and reboot (thus the concept of "storage", versus just an in-memory variable), and the ability to extend them is up to you to engineer.

# Answer
> 2 votes
Here is the full list recommended by Android Developer Site: http://developer.android.com/guide/topics/data/data-storage.html

1. Shared Preferences - Store private primitive data in key-value pairs.
2. Internal Storage - Store private data on the device memory.
3. External Storage - Store public data on the shared external storage.
4. SQLite Databases - Store structured data in a private database.
5. Network Connection - Store data on the web with your own network server.

I was looking for an Internal storage so #3 and #5 are out of the question. I found that SQLite DB beats storing on a file since it can be encrypted in a much better way and it is built for the purpose of quick storage and retrieval.

# Answer
> 2 votes
How much work vs reward do you want? Even if your code is obfuscated and complex it is probably easy to hack the build to force it to think there is loads of money.

You can register all your purchases against a database controlled by you and manage it and don't allow anyone to make any purchases offline.

If you store it on the device, just store it in the internal memory and unless people have rooted phones it should be pretty secure for most cases.

The goal shouldn't be 100% security here, just good enough deterrent in order to ensure most users make purchases.

# Answer
> 0 votes
The most security aproach is to store the players balance in a DB on a server side , and process the information about the payments in the servers side, you can use A SSL conection so your data will be safe

In terms of work , you can simply add a md5 or SHA-512 with a secret key in both sides(client and server) but they still can get your secret key and hack you

If you want to do more work, App can ask a token to the server to make the pay transaction to ensure the petition was done by the app and use it as a secret key

btw there is no safe way, there is always a black hole

---
Tags: android, monetization, economy
---


title: OpenGL ES 2.0 basic camera issues

text:
# Question
Title: OpenGL ES 2.0 basic camera issues
I am having issues with the camera, I cant find how to invert the AXIS

Now

* A point is 0,0,0
* B point is 1,0,0
* C point is 0,0,1

What I want is

* A point 0,0,0
* B point 0,0,1
* C point 1,0,0

I cant find the way to do this, so if you can explain also why is this happening it will be great! (if you need more code ask for it)

Code:

```
final float eyeX = 2.0f;
    final float eyeY = 10f;
    final float eyeZ = 6.0f;

    final float lookX = 1.0f;
    final float lookY = 0.0f;
    final float lookZ = 6.0f;

    final float upX = 1.0f;
    final float upY = 0.0f;
    final float upZ = 0.0f;

    Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

```

ViewPort

```
    GLES20.glViewport(0, 0, width, height);

    final float ratio = (float) width / height;
    final float left = -ratio;
    final float right = ratio;
    final float bottom = -1.0f;
    final float top = 1.0f;
    final float near = 1.0f;
    final float far = 25.0f;
    Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);

```

# Answer
> 1 votes
I think you want `eyeY = -10`, `upX = 0`, and `upZ = 1`. The other values can stay.

Your given and desired points suggest you want to rotate the camera position and its up vector about an axis parallel to `(1, 0, 1)` by angle `PI`. Doing that would yield the values I listed above.

> Can you explain why this is happening?

It looks like you are getting exactly what you specified. If you want a different result, change the values.

---
Tags: android, camera, opengl-es2
---


# Question
Title: Is it possible to completely avoid copying image data when uploading textures to the GPU on iOS?
I am not a game developer, but I have been doing iOS software engineering for many years. I have a particular interest in graphics and animation, but the finer details are still a little foreign to me.

Here is the scenario I am working with:

I have an extremely memory-contrained iOS environment (i.e., no more than 16-20MB of active memory usage) where I am trying to display many high-resolution sprite frames in rapid succession to show an animation. Each frame might be up to 1210x1210 pixels, and I can have up to 200 frames in a single animation.

Obviously, these constraints mean I have to completely optimize my memory usage. There's no way I can even consider having more than one frame of an animation inflated and being used by my application's memory at any given point. Yet I need images to be loaded super fast.

I had considered trying to pack a bunch of frames together into a PVRTC2 or PVRTC4 image file. The quality and disk-space usage of PVRTC files is superior to other formats, considering they're only using 2 or 4bpp.

I attempted to use SpriteKit to read the texture atlas I created and display the image frames. This "worked" in that it did what I wanted, but the memory usage was insane, around 600-700MB. Apparently, SpriteKit is always going to make copies of texture data for its own use, which is unfortunate.

My question is if it's possible to completely bypass copying image data by my application before sending it to the GPU for rendering. My understanding was that the whole point of PVR image formats was to be an exact representation on disk of the uncompressed image data that the GPU can use directly, without the need for copying the image into its own format. (As far as I know, PVR **is** the format the GPU needs to render the texture.)

Indirectly, I was able to mostly achieve what I wanted using a framework I helped develop for iOS called Fast Image Cache. Basically, it creates image tables on disk that are fully uncompressed and are page-aligned in advance such that Core Animation can use the image data directly without doing a single `memcpy`. Fast Image Cache uses mapped memory to further avoid any copies whatsoever. In essence, data goes directly from disk to being rendered on display without any copies being made. (At least, no copies that are made within the context of your application, which could be held against your memory usage limits.)

The problem with FIC is that it is a very naive image table. It doesn't do any sort of texture packing. For my testing, I loaded each frame of the animation as a separate image inside FIC. There was a ton of disk IO overhead going on. In addition, FIC only supports 32bpp (with or without alpha) and 16bpp bitmap formats, which means the image tables are huge.

**Is there a way for me to achieve something similar to FIC using OpenGL and PVRTC images?** If I need to build out my own simple texture atlas support to map regions of PVRTC images to individual animation frames, I'll do that, though it'd be nice if something else besides SpriteKit could do this for me.

The crucial point is being able to quickly load fairly large image data to be rendered without impacting my app's memory footprint.

# Answer
> 1 votes
So the short answer to my own question is, "Yes."

The long answer is...

Using Metal—and, I assume, OpenGL ES—you can create no-copy data buffers from memory-mapped files on disk. From there, you can create textures from those buffers. There are constraints, however, in that the texture data must be an uncompressed pixel format, can only have one mipmap level, etc. This makes sense, since if Metal is going to trust you to provide the texture data entirely without it touching the bytes, it must be in a "color-renderable" format right away.

The problem with this is that uncompressed textures aren't appropriate for me, as my disk usage would be enormous. However, I learned that PVRTC textures are decompressed on-the-fly as needed by Metal. So while I can't avoid **any** memory usage with PVRTC, after the initial texture load operation, the memory footprint is rather low.

---
Tags: textures, ios, opengl-es, memory-efficiency, texture-atlas
---


# Question
Title: Resetting a level in unity when exiting to main menu
I have a pause screen in my game having two buttons : `resume game` and `exit to main menu` The main menu have only 1 button wish is `play`, when i click on `exit to main menu` the main menu level is loaded,if then i click `Play` My game level scene is not restarting but continuing everything,having all it's pre created prefabs and all its game object.

How should I fix this particular bug and restarting the game when `exit to main menu` is clicked

Exit to Menu Button :

```
void OnMouseDown() {
    PauseGame.isPause=false;
    Application.LoadLevel("MainMenu");
}

```

Play button :

```
void OnMouseDown() {
    spriteRenderer.sprite = s2;
    Application.LoadLevel("Game");
}

```

I have three Prefabs:

Turret :

```
using UnityEngine;
using System.Collections;
public class Turret : MonoBehaviour {
// Use this for initialization
double LastBallTime=0.0;
double LastTurretMovingTime=0.0;
public double spawnballTime=1.5;
public double StartTurretMovingTime=35.0;
public double BallCount=2;
public bool IsRed=false;
public GameObject BallPrefab;
public GameObject RedBallPrefab;
Vector2 v ;

void Start () {
}

// Update is called once per frame
void Update () {
    if (Time.time > LastBallTime + spawnballTime) {
        LastBallTime=Time.time;
        int rand= Random.Range(1,6);
        if(rand>=1 && rand<=4)
            Instantiate(BallPrefab, transform.position, transform.rotation) ;
        else{
            Instantiate(RedBallPrefab, transform.position, transform.rotation) ;

        }

    }
    if (Time.time > LastTurretMovingTime + StartTurretMovingTime) {
        LastTurretMovingTime=Time.time;
        int x = Random.Range (-2,3);
        int y = Random.Range (-3,3);
        v = new Vector3 (x, y,0);
        gameObject.transform.position=v;

    }
}
void OnBecameInvisible ()
 {
    Destroy(gameObject);
 }
}

```

BALL :

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Ball : MonoBehaviour {
// Use this for initialization
public static double Killed=0;
public Text ScoreTextPrefab;
 GameObject ParentCanvas;

void Start () {
    ParentCanvas = GameObject.Find ("Canvas");
}
void OnMouseDown() {
    if (!PauseGame.isPause) {
        Text t = Instantiate (ScoreTextPrefab, transform.position, transform.rotation) as Text;
        t.transform.SetParent (ParentCanvas.transform, false);
        if (gameObject.name.Contains ("RedBall")) {
                t.text = "O o P s";
                RedKilled++;
        } else {
                Killed++;
        }
        Object.Destroy (gameObject);
    }

}
// Update is called once per frame
void Update () {

}

void OnBecameInvisible ()
{
    Destroy(gameObject);
 }
}

```

TurretBall manager wish is assigned for the main camera of the game scene :

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TurretBallManager : MonoBehaviour {

// Use this for initialization

public GameObject TurretPrefab;
public double turretSpawnTime=35;
public double LastTurretTime=0;
public double MaxTurret=10;
int currentTurretCount=1;
public Text Killedtxt;
Vector2 v;

void Start () {
    v = new Vector2(0,2);
    Instantiate (TurretPrefab, v, Quaternion.identity);

}
void CreateTurret()
{
    if (Time.time > LastTurretTime + turretSpawnTime) {
        LastTurretTime=Time.time;
        currentTurretCount++;
        if(currentTurretCount>1)
            v.x=TurretPrefab.transform.position.x-currentTurretCount/2;
        if(currentTurretCount<=MaxTurret){
            Instantiate(TurretPrefab,v,Quaternion.identity);
        }

    }
}
// Update is called once per frame
void Update () {
    Killedtxt.text = "Kill : " + Ball.Killed;
    CreateTurret ();
  }
}

```

# Answer
**Loading a level from Application.LoadLevel should rest everything unless:**

* You have set that script to DontDestroyOnLoad
* You have set some variables to be static

If it is any of those too, I would recommend manually editing the code so both should not interfere when loading from another level. In the case of the static variable, this can be done easily by setting it in the Awake Function

However, if you would simply like it to work, without editing the script in the game, there is a way. It is not the best way, but it should work fine. This does NOT work if some Game Objects are set to not Destroy on Load. They will still stay persistent. Edit the Play button script:

**OLD SCRIPT**

```
using UnityEngine;
using System.Collections;

public class Play : MonoBehaviour
    {
    void OnMouseDown()
        {
        spriteRenderer.sprite = s2;
        Application.LoadLevel("Game");
        }
    }

```

**NEW SCRIPT**

**OLD SCRIPT**

```
using UnityEngine;
using System.Collections;

public class Play : MonoBehaviour
    {
    void OnMouseDown()
        {
        spriteRenderer.sprite = s2;
        DontDestroyOnLoad(transform.gameObject);
        Application.LoadLevel("Game");
        Application.LoadLevel(Application.loadedLevel)
        Destroy(transform.gameObject);
        }
    }

```
> 2 votes

# Answer
if you do happen to have a static variable, just initialize it again in either Awake() or Start (); then whenever you need to restart your level just call Application.loadedLevel

I was able to get it to work like this:

```
public static int aNumber;

void Awake ()
{
  int aNumberInitial = 5;
  aNumber = aNumberInitial;
}

void restartLevel () // Call this method to restart
{
  Application.loadLevel(Application.loadedLevel);
}

```
> 0 votes

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


# Question
Title: What would cause my script generated buttons and text to show in Unity and not on my phone?
I am using Unity 5 and the built in GUI tools. My static GUI shows up just fine which makes me think it's not a text/font issue or some such. Again, it all looks good in the Unity editor when I hit Play.

I have tried the different canvas options as far as what space to work in and how to scale. I have messed with the build options. I have tried turning batching off. I have tried building for Android 4 through 5. (Ice Cream, Jelly Bean, etc) I have tried turning dynamic text on and off. I have ensured the Buttons and text are made to be children of the canvas. I have only uploaded the game onto my Galaxy Note 4. I moved my background texture out of screen space in case it somehow covered the buttons on Android.

https://www.youtube.com/watch?v=Hk1UjXwOR08

# Answer
Bug reported:

Unity does not appear to generate UI elements upon Start. User input, or possibly some arbitrary amount of time in necessary until the application/game will generate the UI elements.

I made my app wait to generate the buttons until I hit a button and it worked as intended.

I suspect generating the UI from the Update() func would work properly. I would just need to add a bool check for initialization statements
> 2 votes

---
Tags: unity, android, gui, unityscript
---


# Question
Title: Sphere to plane collision never rearching resting contact
I have been trying to have a sphere to plane eventually lead to the sphere coming to a resting contact, but my sphere will end up always bouncing forever. It will bounce correctly for the first few times, but eventually it will just be in a constant state of a very small bounce. I have tried to exhaust every article I can find but I don't see where I am going wrong here. Does anyone see the issue? I have attempted to put as much information into this post so I apologize if it is a bit long.

I first attempt to see if there is resting contact, collision, no collision or if the sphere and plane will collide

```
Vector3 forces = (sphereTotalForces + sphereVelocity);
float denom = Vec3Dot(&plane->GetNormal(), &forces);

if(sphereVelocity.GetMagnitude() > 0 && dist <= sphereRadius + .0013f) {
    crCollisionResult.enCollisionState = RESTING_CONTACT;
    crCollisionResult.vCollisionNormal = plane->GetNormal();
    return crCollisionResult;
}
else if(fabs(dist) + 0.001f <= sphere->GetRadius()) {
    crCollisionResult.enCollisionState = COLLISION_HAS;
    return crCollisionResult;
}
else if(denom * dist > 0.0f) {
    crCollisionResult.enCollisionState = COLLISION_NO;
    return crCollisionResult;
}

```

where

```
sphereRadius  = 1
denom = -9.98206139
dist = 2.34482479

```

Since none of those are true I will then attempt to calculate when the collision will happen

```
    F32 fIntersectionTime = (sphere->GetRadius() - dist) / denom;
    F32 r;
    if(dist > 0.0f)
        r = sphere->GetRadius();
    else
        r = -sphere->GetRadius();

    Vector3 collision = spherePosition + fIntersectionTime * rigidBodySphere->GetVelocity() - r * plane->GetNormal();
    crCollisionResult.fCollisionTime = fIntersectionTime;
    crCollisionResult.vCollisionNormal = plane->GetNormal();
    crCollisionResult.vAdjustedPosition = collision;

```

The intersection time will be calculated to be 0.00334050134 , which is less than the fElapsedTime of 0.00703109941. As a result, I will update my sphere using the intersection time as the delta (so fElapsedTime here will be 0.00334050134)

```
    mAcceleration = mTotalForces / mMass;
    mVelocity += mAcceleration * fElapsedTime;
    Vector3 translation = (mVelocity * fElapsedTime);

    mTransform->Translate(translation.x, translation.y, translation.z);

    mTotalForces = Vector3(0.0f, 0.0f, 0.0f);

```

where

```
mTotalForces = (0, -10, 0)
mMass = 22

```

After I update there sphere with its new position, I will then calculate the new velocity of it being reflected

```
        Vector3 vSurfaceNormalized;
        Vec3Normalize(&vSurfaceNormalized, &crCollisionResult.vCollisionNormal);

        Vector3 vIncomingVelocity = pSphere->GetVelocity();
        F32 fIDotN = Vec3Dot(&vIncomingVelocity, &vSurfaceNormalized);

        Vector3 vReflectedVelocity = vIncomingVelocity - ((1.0f+pSphere->GetCoefficientOfRestitution()) * vSurfaceNormalized * fIDotN);
        pSphere->SetVelocity(vReflectedVelocity);

```

where

```
pSphere->mCoefficientOfRestitution = .85
vIncomingVelocity = (0, -5.30, 0)
mNormal = (0, 1, 0)
fIDotN = -5.30350208
vReflectedVelocity = (0, 4.50797653)

```

# Answer
> 1 votes
Instead of checking the distance for a resting contact, check for velocity. If 2 objects are moving slowly and hit each other, they should be put to rest. If not, they should do what they would do if they weren't resting.

So...

```
if (CollisionDetection())
{
    if (sphereVelocity.GetMagnitude() <= .1f)
    {
        //NoGravity();
        //NoForces();
        //NoVelocity();
        return;
    }
    //CollisionStuff ();
}

```

This will allow the ball to naturally bounce and keep losing velocity from the incomplete restitution, until it eventually loses enough velocity to rest upon contact. Make sure you have incomplete restitution so your ball loses some velocity with every bounce.

Here's the collision detection between circle and line:

```
//This collision detection uses SAT
bool CollisionDetection()
{
    ///Get the axis to project on
    Vector2 Axis = Line.PointB - Line.PointA;
    //Make it perpendicular for the separating axis
    Axis = new Vector2 (-Axis.y, Axis.x);
    Axis.Normalize ();

    //CP as in Circle Projection
    float CP = Vector2.Dot(Circle.Position, Axis);
    //Circles are oriented the same way on all axes so just +- the radius
    float CP_Min = CP - Circle.Radius;
    float CP_Max = CP + Circle.Radius;

    //LP as in Line Projection
    float LP_A = Vector2.Dot (Line.PointA, Axis);
    float LP_B = Vector2.Dot (Line.PointB, Axis);
    float LP_Min;
    float LP_Max;
    //Get the minimum projection
    if (LP_A < LP_B)
    {
        LP_Min = LP_A;
        LP_Max = LP_B;
    }
    else {
        LP_Min = LP_B;
        LP_Max = LP_A;
    }

    //Checking for collision, now that our entities are axis-aligned
    //We can do a simple bounds check
    if (CP_Min <= LP_Max)
        if (CP_Max >= LP_Min)
            return true;
    return false;
}

```

Basically, you get the projection of the bounds of each entity on the line's axis (the min and max) then use these axis-aligned points to determine whether or not there is a collision. I recommend reading this sample for a better understanding of this collision detection method called SAT.

# Answer
> 1 votes
Like both answers said, there are 2 "secrets", one is you need to stop applying gravity when bounces are determined to be over (which is a bit of an extension over Leftium answers, he just said "resting" which is not enough because you rest as soon as you touch by this definition).
Secondly, check for speed, obviously. This later condition is in relation to energy. Speed is your simple measure of energy (cinetic), which is what really is congruated to the notion of rest. What is rest if simply a stable energy level.

To extend and finish the last blurry part in the phrase "bounces are determined to be over", this is a criterion that you can measure by looking at the bounce velocity (projection of speed on the normal of the contact plane). If it is small then you can consider that bouncing again is un-necessary, because your object is not infinitely hard, if will have elasticity and stop to bounce in reality. Thus a threshold makes sense.

Now please consider this project:
http://sourceforge.net/projects/carnage-engine/

and this piece of code is of interest to you:
`demo/demo.cpp`

method `Simulate` line `332`.

```
ce::Vector2f force(0);
ce::Vector2f accel = force / mass;
if (inAir)
    accel.y = 380;  // gravity acceleration
// newton integration
speed += accel * dt;
if (sqrt(speed.LengthSq()) > 800.f)  // speed limit; cross it, you'll have a ticket.
    speed = Normalize(speed) * 800.f;
if (!inAir)
{
    // regular slowdown when on the ground.
    speed -= speed * 0.9 * dt;
}

pos += speed * dt;  // integration
ce::Vector2i prevpos = spm.GetRect(ball).pos;  // remember the free position before moving
spm.Move(ball, pos);
// check for collision with world objects: (static objects, i.e. the level)
if (collmgr->ShapeIntersectWorld(ce::MkCircleShape(spm.GetRect(ball))))
{
    // we must find the true collision position
    ce::Vector2i freePos = collmgr->FindFreePosition(prevpos, ce::MkCircleShape(spm.GetRect(ball)));
    spm.Move(ball, freePos);
    // the free directions is a stupid but efficient technique to know
    // where you can go now. It tests your shape with 1 pixel offset on 4 directions.
    ce::CollisionManager::Directions freedirs =
        collmgr->DiscoverFreeDirections(ce::MkCircleShape(spm.GetRect(ball)));
    if ( (!freedirs.left && speed.x < 0)
         || (!freedirs.right && speed.x > 0)  )
    {
        speed.x = -speed.x*0.2;  // can't travel on X because i'm blocked. so bounce back
    }
    if ( (!freedirs.up && speed.y < 0)
         ||  (!freedirs.down && speed.y > 0) )
    {
        if (fabs(speed.y) > 100)
            speed.y = -speed.y * 0.5;  // bounce ! :)
        else
            speed.y = 0;  // freeze pos to avoind bouncing infinitesimal jumps.
    }
    if (inAir && !freedirs.down)  // was in the air, but our bottom collided.
    {
        inAir = false;  // we are touching ground.
    }
    pos = spm.GetRect(ball).pos; // don't let the internal float pos get crazy (it doesn't know yet that we collided, so we must reset it to the actual pos (an integer, because we work in pixels))
}
else  // we are free for this movement. (not sure at 100% actually, because if framerate is SUPER low, we could pass through thin objects)
{
    if (!inAir)
    {
        ce::CollisionManager::Directions freedirs =
            collmgr->DiscoverFreeDirections(ce::MkCircleShape(spm.GetRect(ball)));
        if (freedirs.down)
        {
            inAir = true;  // nothing under us, thus we are flying.
        }
    }
}
// at this position, we should always be free:
BOOST_ASSERT(!collmgr->ShapeIntersectWorld(ce::MkCircleShape(spm.GetRect(ball))));

```

As you can see, there are all your elements in this code, notably the contact epsilon, which for me is 1 pixel, for you 0.0013. either way it should work.
Then there is the speed check to stop bouncing, which is what JPthek9 was proposing, in my case its 100, I got it experimentally.
I also have energy dumpers as you can see, a fluid one, which you can consider as being air drag.
And the bounce losses, laterally 80% is lost on each vertical walls. Vertically 50%, this is more fun this way. You can make something more physically realist in your case.

And the Leftium's point, is the "inAir" boolean flag, this code gives you a concrete way to determine it.
After reading you will notice that "inAir" is not equivalent to "contact". Because in my case, you can be inAir while bouncing against a vertical wall. Which doesn't allow vertical bouncing, just horizontal bouncing. In your case, the criterion could be a projection of the normal with the vertical normal. (just take the `.y` and compare with `0.98` or smth) Remember that a sphere cannot rest on slopes. (that is, if you want to simulate that. my simulator doesn't.)

# Answer
> 0 votes
**Stop applying (the gravity) force after reaching `RESTING_CONTACT.`**

My guess is your sphere *is* reaching resting contact, but gravity (or other forces) causes it to continue moving as soon as the next update happens.

**Explanation:**

Generally, once an object reaches resting contact, it should not respond to forces until there is a force large enough to "push" it out of the resting state. This is an approximation because in real life, objects in resting contact do not really stop moving: they are constantly vibrating and colliding with each other at a microscopic level. So play with the the magnitude of this threshold force until it looks realistic. This threshold force is the "stickiness" of the objects at resting contact with each other.

---

Also, JPtheK9 is correct. You should only enter the resting contact state if the object velocities are low. Imagine if the sphere were moving at the maximum speed possible and it happened to be `sphereRadius` units away when you calculate the updates. Should it go to into the resting contact state?

---
Tags: collision-detection, physics, architecture, movement
---


# Question
Title: How to run a method after a scene2d being rendered in libGDX
I want to make a screenshot with

```
ScreenUtils.getFrameBufferPixmap(x, y, w, h);

```

I call this function in Actions.run(new Runnable{...}) in scene2d.ui, and the problem is that actions are called at very beginning of a new frame, so nothing is rendered yet.

How to call this method properly, e.g.

```
Scene.inTheEnd(run(ScreenUtils.getFrameBufferPixmap(x, y, w, h);));

```

?

# Answer
A `Stage` has the 2 methods `act()` and `draw()`.
The `act()` method calls `act()` for all it's `Actor`s. The `Actor`s `act()` method updates all it's `Action`s, so your screenshot is taken while the `Stage` is acting.
The `draw()` method calls `draw()` for all (visible) `Actor`s and is usually called after the `act()` method.
The screenshot should be taken after the `draw()` method. Usually `act()` and `draw()` should be called inside the `render` of your `Screen` or `ApplicationListener` and there you should also take the screenshot:

```
public void render (float delta) {
    this.stage.act(delta);
    this.stage.draw();
    Pixmap screenshot = ScreenUtils.getFrameBufferPixmap(x, y, w, h);
    // do something with the screenshot
}

```
> 1 votes

---
Tags: libgdx, scene2d
---


title: Design Pattern for "Default Object"

text:
# Question
Title: Design Pattern for "Default Object"
I'm making a first person dungeon crawler like Eye of the Beholder.

During execution, I have a Map object. It contains Cell objects. Anc each Cell contains, at most, four Wall objects.

The Wall object has data for it's texture, and special elements like a door, a switch, etc. But most walls will end up being empty, boring walls.

My idea is to make this "boring wall" a single instance, that is referenced by all the cells that need it. Is there any design pattern or recipe in how to work with this? Or do you have any ideas?

I would like the entity's usability to be the same as the remaining entities (although I realise the default instance must be immutable).

I don't know if it helps, but I'm working with Lua.

Thanks in advance.

# Answer
http://en.wikipedia.org/wiki/Flyweight\_pattern

is the pattern name if I'm reading your question correctly.
> 1 votes

---
Tags: design-patterns, gameobject, objects
---


# Question
Title: How can I make RPC function calls in Unity?
I am making a multiplayer game. I am sending score via the server and client but I want to be sure that can I call an RPC function of a script from any other script.

For example, say `Table_Manager` as a script which contains a `get_score` function and I want to call it from a `game_stat` script like `Table_Manager.networkview.rpc("Table_Manager", rpcmode.all, 25);` The `get_score` method would look something like:

```
[RPC]
public void get_score(int new_score)
{
   // ...
}

```

How can I accomplish that?

# Answer
> 2 votes
Yes you can :

```
Table_Manager TM = your_game_object.GetComponent<Table_Manager>();
NetworkView nv = TM.GetComponent<NetworkView>();

nv.RPC("get_score",RPCMode.All,25);

```

# Answer
> 1 votes
You can add the following attribute at the beginning of your script class:

```
[RequireComponent (typeof (NetworkView))]

```

This will ensure that whenever your script is added to a GameObject, a NetworkView component will also be added to that GameObject. Or you can just manually add the NetworkView component yourself. If you're only using it for RPC, you can set the Observed to none and change the State Synchronization to Off.

Once you're sure a NetworkView is attached to the same GameObject as your script, you can either use the built in shortcut of `this.networkview` (which will automatically retrieve the NetworkView attached to the same GameObject), or you can use `this.GetComponent<NetworkView>()` to get the NetworkView component attached to the current GameObject.

Either way, you'll be retrieving the same NetworkView, and utilizing it for its RPC functionality.

Your desired strategy of calling the method: `Table_Manager.networkview.rpc("Table_Manager",RPCMode.All,25);` will not work. In this case you'd be treating `Table_Manager` like a static class. In which case, you wouldn't have access to instance variables like `networkview`. You can however make some kind of GameManager object in your scene. Attach your `Table_Manager` script to it, then create a static function like the following:

```
static void GetScore() {
    GameObject.Find("GameManger").GetComponent<Table_Manager>().
         networkview.RPC("Table_Manager",RPCMode.All,25);
}

```

I'm not really sure what `GetScore` is supposed to do, or why it's trying to call a `Table_Manager` method on all the clients, but the above is how you'd write that.

# Answer
> 0 votes
Be aware that a RPC function has to be unique within a scene. I wrote an blogpost explaining this in detail: http://parttimeindie.com/2015/05/08/understanding-and-using-rpcs-in-unity/

To Summarize the blogpost:

A RPC Method Signature has to be Unique inside a Scene, you can not have multiple instances of one script or Two Scripts with a Method with the same Name or a "random" instance will get called.

The Solution i use passes the networkviewid which is observing the script as well as the other input parameters. The receiver searches all networkviews for the one with the networkviewId passed and then looks inside the networkview.observed and calls the method there. This way you can have multiple instances of one script or methods with the same signature in different scripts. Hope this is somewhat clear, please take a look at the blogpost if you want to have it in more detail.

P.s.: Sry that i did not wrote more in my first post i did not know the rules, shame on me ;)

Regards Niki

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


# Question
Title: Unity 5: Accessing a C# variable from Javascript
I've set up a SQLite database with Unity. Into this I would like to add the current CPU Utilisation. The SQLite scripts are in Javascript and the method for finding the CPU utilisation is in a C# script, I have tried changing the javascript to C# but I am not that skilled. Ive tried several methods, each giving me errors:

(http://www.41post.com/1935/programming/unity3d-js-cs-or-cs-js-access)

```
private var csScript : ClientValues;

function Awake()
{
csScript = this.GetComponent("ClientValues");
}

```

using this method gives me the error "The name 'ClientValues' does not denote a valid type ('not found')"

and if I use (http://answers.unity3d.com/questions/272122/can-i-pass-a-value-from-a-c-script-into-a-java-scr.html)

```
var curValue : int;
var gObject2 : GameObject;

function Update()
{
var cSharpScript = gObject2.GetComponent("Clientvalues");
curValue = cSharpScript.myValue;
}

```

I get the error: 'myValue' is not a member of 'UnityEngine.Component'

Is this something to do with me using Unity 5? What can I do to have the Javascript access the C# value?

# Answer
You have to cast it to ClientValues type.

```
var cSharpScript = (ClientValues)gObject2.GetComponent("Clientvalues");

```

or

```
var cSharpScript = gObject2.GetComponent("Clientvalues") as ClientValues;

```

First one causes runtime error if cast fails and the second one returns null if it fails. Important difference. But both should do the trick.
> 1 votes

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


title: How to stop deltaTime while debugging

text:
# Question
Title: How to stop deltaTime while debugging
Framework: LibGDX

IDE: Android Studio

Game based on Kilobolt tutorial

While debugging, the frame delta time i get using `Gdx.graphics.getDeltaTime()`continues to increment so when i stop debugging and return to application, everything is fast (it is related to runTime, so delta time too)

runTime is calculated in GameScreen class, which increments it with deltaTime and then passes it to GameWorld and GameRenderer methods calls.

How can i stop it while debugging?

# Answer
The delta time is the time since the last frame. Ofc, when you are debbuging, a frame takes verry long, as you are stepping through the code. Therefore the delta time can become huge.
But keep in mind, that the delta time can become bigger then expected, even without debuging.
Slow devices, f.e., can result in bigger delta times. So instead of "stopping" delta time, when debuging (i don't guess that thats even possible), you should limit it generally.

Also you might consider using an accumulator:

```
private float accumulator = 0;

public void render(float deltaTime) {
    // fixed time step
    // max frame time to avoid spiral of death (on slow devices)
    float frameTime = Math.min(deltaTime, 0.25f);
    accumulator += frameTime;
    while (accumulator >= Constants.TIME_STEP) {
       update(Constants.TIME_STEP);
       accumulator -= Constants.TIME_STEP;
    }
}

```

That means, that if delta is big, you take many little steps, instead of one big, and render the results then. This results in a more accuraate logic.
The limitation of the delta time is still needed, as on slow devices, a huge delta would result in many update-calls, which result in even bigger delta times and so on.
> 1 votes

# Answer
Just add a limit on the number of updates you can do between drawing, i.e. limit the accumulator.

If it will never catch up for more than a second for example, you'll never run into this issue.

Also keep in mind that this is essentially needed to avoid situations where you're never able to catch up again, which might cause your app I get stuck (time per update being longer than the time between updates).
> 0 votes

---
Tags: libgdx, debugging
---


# Question
Title: Java libgdx get clicked square without iter
I would like to detect which square is clicked without iterating over all elements!

i don't want to do this anymore for all elements.

```
 if( x >= this.getAnchorX()-HalfWidth  && x <= this.getAnchorX()+HalfWidth  && y <= this.getAnchorY()+HalfHeight && y >= this.getAnchorY()-HalfHeight )
        return true;
    else return false;

```

# Answer
Given that top left is at 0, and each tile is square with length 10:

```
int squareClickedX = clickPosX / 10
int squareClickedY = clickPosY / 10

```

So, if clicked on x23, y12

```
int squareClickedX = 23 / 10
int squareClickedY = 12 / 10

```

results

```
int squareClickedX = 2
int squareClickedY = 1

```

Means that you clicked

Was this any good? This is quite common way to handle this kind of stuff.
> 1 votes

---
Tags: opengl, java, 2d, libgdx, algorithm
---


# Question
Title: Determine whether a shape formed from a series of other shapes is 'unbroken'
I have a grid of tiles in a game and each tile can have a certain simple shape on it.

I want to be able to determine whether the combined shape from any given arrangement of these tiles results in an 'unbroken' or 'broken' larger shape.

For example; this is an example of an 'unbroken' shape...

And this is an example of an 'broken' shape...

I'll be able to write the necessary code once I figure out the logic of this problem, but so far I've been struggling.

I've tried data tables associated to each tile that describe it's edges, for example :

```
var edges = {
    top : false,
    right : true,
    bottom : true,
    left : false
}

```

And from this I can determine whether each tile is 'connected' to it's neighbours. But this doesn't help for all situations.

EDIT 1: Multiple clusters of isolated 'unbroken' shapes would be considered a 'broken' shape...

EDIT 2:

Also, an 'unbroken' shape can be achieved if a shape tile's edge is not connected to every neighbouring tile, it can be just one connection. For example I would consider this to be 'unbroken' ...

Anyone got any ideas on this?

# Answer
This is a basic connected components problem, and can be solved with a single invocation of breadth-first or depth-first search, or any flood-fill algorithm.

```
bool IsOneSolidShape(TileCollection tiles)
{
    // Clear visited flags on all tiles.
    // (This can also be implemented as a temporary set/map or parallel array,
    // if you prefer not to clutter your Tile type with book-keeping data)
    foreach(var tile in tiles)
        tile.IsVisited = false;

    // Prepare a container to hold tiles whose neighbours we haven't searched yet.
    // With a stack, this is depth-first search. A queue gives breadth-first.
    var pending = new stack<Tile>();

    // Seed the search with some start tile - this choice is arbitrary.
    var startTile = tiles.GetSomeNonEmptyTile();
    startTile.IsVisited = true;
    pending.Push(startTile);
    int numVisited = 1;

    // Search for as long as we have unexplored tiles in our stack:
    while(pending.Count > 0)
    {
         var tile = pending.Pop();
         foreach(var neighbour in tile.GetNeighbours())
         {
             // Skip over tiles we've already reached.
             if(neighbour.IsVisited)
                continue;

             // Check for a valid connection between this tile and this neighbour.
             if(tile.IsConnectedTo(neighbour))
             {
                // This tile is connected.
                // Mark it visited so we don't double-count it later.
                neighbour.IsVisited = true;

                // Add it to our reached set.
                numVisited++;

                // Keep note of it so we can search its neighbours.
                pending.Push(neighbour);
             }
         }
    }

    // If we have reached every non-empty tile,
    // then they are all in one connected shape.
    return numVisited == tiles.GetNonEmptyTileCount();
}

```

The code above only tells you if you have exactly one group.

If you want to count how many groups there are, you can do it by wrapping the outer while loop in a while(numVisited \< tiles.GetNonEmptyTileCount()), each time seeding the inner while loop with a new unvisited tile and incrementing your group count.

Note that `tile.IsConnecedTo(neighbour)` should return true if and only if *both* `tile` and `neighbour` connect along their shared edge. (ie. if `tile` connects to the shared edge, but `neighbour` doesn't, it should return false)

**Edit: here's a recursive version:**

```
bool IsOneSolidShape(TileCollection tiles)
{
    // Clear visited flags on all tiles.
    // (This can also be implemented as a temporary set/map or parallel array,
    // if you prefer not to clutter your Tile type with book-keeping data)
    foreach(var tile in tiles)
        tile.IsVisited = false;

    // Seed the search with some start tile - this choice is arbitrary.
    var startTile = tiles.GetSomeNonEmptyTile();

    // Recursively search all tiles reachable from startTile.
    int numVisited = CountConnected(startTile);

    // If we have reached every non-empty tile,
    // then they are all in one connected shape.
    return numVisited == tiles.GetNonEmptyTileCount();
}

int CountConnected(Tile tile)
{
   // Initialize connected set to include "myself."
   tile.IsVisited = true;
   int connected = 1;

   // Check for connections to neighbours.
   foreach(Tile neighbour in tile.GetNeighbours())
   {
      // Skip tiles we've already visited, to avoid double-counting.
      if(neighbour.isVisited)
         continue;

      // Recursively search any neighbour we're connected to)
      if(tile.IsConnectedTo(neighbour))
         connected += CountConnected(neighbour);
   }

   return connected;
}

```
> 8 votes

# Answer
Record the vertexes as lines on the edges where a shapes points lie. These will be used to match up to points/lines on the other tiles each time a tile changes.

For example:

Above the blue lines on the top two tiles, A and B, have been calculated/saved for each edge of the tile according the shape it contains (note even though they are on different sides respectively you can extract the line for comparison using simple integer values ranging from 0 -\> X.)

In the broken example the lines do not match so you could say the image is broken. Store the data as extra information in the tile to then use for comparison. If you have a set number of edge types (full edge, half edge, etc) then you could even create an enumerator for sides A,B,C and D on each tile and compare appropriately.

In our example our edges can be compared from values 0 -\> 10.

```
var exampleTileA = {
    top : undefined,
    right : {0,10},
    bottom : {0,10},
    left : undefined
}

var exampleTileB = {
    top : undefined,
    right : undefined,
    bottom : {0,10},
    left : {0,10}
}

var exampleTileC = {
    top : {5,10},
    right : {5,10},
    bottom : {0,5},
    left : {0,5}
}

function compareLeftRight(leftTile, rightTile){
    return leftTile.right === rightTile.left;
}

console.log(compareLeftRight(exampleTileA, exampleTileB));
console.log(compareLeftRight(exampleTileA, exampleTileC));

//// Output
//  true
//  false

```

To approach the clusters of unbroken shapes you can simply iterate through each tile and check if it is connected to any of the previously iterated tiles:

```
var tiles = [tileA, tileB, ...];
var tempTiles = tiles;

// Loop through each tile and remove it from the temp
// tile array if it is connected to any of the previous tiles
for (var tile in tiles) {
     var currentIndex = tiles.indexOf(tile);

     for(var i = 0; currentIndex > i; i++) {
         if ( tileA.connectedTo(tile)) {
             // remove from temp tiles
             var index = tempTiles.indexOf(tile);
             if (index > -1) {
                 tempTiles.splice(index, 1);
             }
         }
     }
}

if (tempTiles.length > 0) {
    // Some tile was not connected to the group
    console.log("There are " + tempTiles.length + " tiles not connected to the group");
}

```
> 3 votes

# Answer
It sounds like all you are looking for is to see if there are ANY broken edges in your tiles and get a true or false back.

If that is the case, all you need to do is look at every place tiles join together (on the x axis and the y axis) and see if the edges are compatible.

You'd loop until you either found a broken edge (and you'd return true), or until you ran out of edges to check (and you'd return false).

It would basically be a for loop within a for loop (one would be X axis, the other would be Y axis) so would be an N^2 algorithm.

Is that what you are after? Does this help?
> 0 votes

---
Tags: tiles
---


# Question
Title: Lookrotation of a gameObject in just one axis
So I am trying to orient a gameObject ( house in the picture below) which is nothing but a plane and has a 2d texture on it as you see below. The whole game is made on a hex sphere. I am using Orthographic camera projection for this game. I have oriented the house plane to the normal of the tile and rotated it by 90 degrees in x axis to begin with

```
cityDummy.transform.rotation = Quaternion.LookRotation(normal);
cityDummy.transform.Rotate(90, 0, 0);

```

Now I am trying to orient the house to make it look at the center ( blue capsule object in the image is the center point ) but I don't want to rotate it in all angles. Basically that is what LookRotation or LookAt does inside Unity. So after orienting the house with the normal, how do I make the house object look at the center and just rotate it in one axis that would be the y-axis in this case?

The reason why I need to do this is first of all I want to orient the house texture to the normal of the tile it gets placed on as you see in the image above. That works fine.

Now the next thing is we want them to face the south which is the blue capsule in the image above. So they would still be oriented like in the image below but the forward of the city should be facing south or towards the blue capsule. If I do LookAt it messes up the current orientation as it rotates in all axis. I would only want to rotate it on one axis and make it face the capsule

# Answer
> 2 votes
`Quaternion.LookRotation(forward, up)` has a nifty property:

* it rotates z+ *exactly* to `forward`
* it rotates y+ *as close as possible* to `up` (given the constraint on z+)

(You might not be used to `up`, since it silently defaults to (0, 1, 0) if you leave this parameter out)

What we want here (and this comes up pretty often) is the reverse: we want y+ controlled *exactly*, and we want z+ to get *as close as possible* given this constraint.

We can get this just by playing with the axes a bit:

```
Vector3 lookDirection = target.transform.position - cityDummy.transform.position;

Quaternion rotation = Quaternion.LookRotation(normal, -lookDirection)
                    * Quaternion.AngleAxis(90f, Vector3.right);

```

This looks weird, so let me unpack it a bit...

We're using Quaternion.LookRotation with `normal` in the first position (ordinarily used for `forward`), to ensure the resulting rotation sticks to `normal` *exactly*, and then aligns *as close as possible* to (negative) `lookDirection`.

This gives us a rotation where the local z+ is pointing in the `normal` direction, and local y- is pointing toward `lookDirection`.

(If you orient your head this way, you're looking out of the sphere along the normal, and your chin is pointing toward the target)

But we want the axes switched. So we compose this with a rotation that takes y+ to z+, and z+ to y-, namely `Quaternion.AngleAxis(90f, Vector3.right)`

(Continuing with the head analogy, this corresponds to tilting your head forward 90 degrees)

The result of composing these two rotations with `*` is a rotation that takes +y exactly to `normal`, and +z as close as possible to `lookDirection`.

I use this pattern so much, it might be worth adding it as an extension method to Quaternion, so you can get it with a single call, like Quaternion.LookRotationExactUp(forward, up)

# Answer
> 1 votes
(Posting my comment as an answer)

If you take the 3d plane for your cell and the line for that south pole, and find the intersection point, then you could use LookAt for that point.

You would also want to handle the case where the plane is parallel to that line, in which case you could rotate the plane to a predetermined angle, to orient it correctly.

---
Tags: unity, mathematics, rotation
---


title: LibGDX destroy object when not used

text:
# Question
Title: LibGDX destroy object when not used
I am developing a game where objects move in the screen. My object is instantiated in Y = 0 and I want to destroy this object when it goes under the screen Height. So if (positionY \>= ScreenHeight) I have to destroy this object to clean my game and prevent "lag".

How to do this? I have a dispose method (this.dispose) but it cause the dispose of the app and I want destroy only the object.

Thanks in advance

# Answer
It's not a good idea to dispose/destroy your objects unless you want to change your screen (for example moving from menu to game level ) because when your are disposing/destroying objects , garbage collector is called ,so it's better to store your dead objects in memory instead of destroying them.

First off all read this article https://github.com/libgdx/libgdx/wiki/Memory-management specially **Object pooling**.

Pooling objects allow you to reusing your dead objects instead of recreating them.For example in your case you have several ways to reuse your dead object like this

```
if(myObject.getY>=screenHeight)
   myObject.setY(0);

```
> 0 votes

---
Tags: libgdx, gameobject, objects
---


# Question
Title: Will Frame Independant Movement break collision
Using my game loop to give my game movement which is independant from the framerate, has been working fine for me but, I've started to consider my games running on machines which cannot keep up with my expected frame limit of 60fps, I've tried manually setting it to a lower cap and noticed that my collision detection starts to go off and objects on screen overlap because of this.

How can I make collision detection occur on movements which are too great and overshoot boundary checks?

Below is my loop for running my game

```
  while (g_Window.isOpen()){

    sf::Time dt = clock.restart();
    timeSinceLastUpdate += dt;
    while(timeSinceLastUpdate > TIME_PER_FRAME){

         timeSinceLastUpdate -= TIME_PER_FRAME;
         processEvents();
         update(TIME_PER_FRAME);
}
   updateFPSCounter(dt);
   render();
}

```

# Answer
> 0 votes
I'm not sure if you're speaking of inability to keep up with FPS or UPS (Updates Per Seconds), but if machine has **lower frames per second** than expected you shouldn't change rate at which you're logic is being updated (UPS). Content of window is drawn depending on machine's capabilities but logic (and physics) run at constant and independent rate. In this situation you can precisely predict where sprite (or whatever) will be since logic which moves sprite and physics which detects collision run at the same rate (UPS).

Example: Logic runs at **60 Hz - UPS**, but your machine can only process game loop 30 times per second, so your **FPS is 30**. One loop iteration takes longer than 60 Hz, so `update(...)` might be run few times, but that's ok, because you move sprite by `distance * UPS` and your collision detection system (assuming it's called after sprite update) detects that sprite will collide so it moves sprite back to safe area. Same result would be if you check if sprite will collide before moving it: `if(!border.getGlobalBounds().contains(sprite.getPosition().x + sprite.getSize().x + distanceX * ups, sprite.getPosition().y + sprite.getSize().y + distanceY * ups))
 sprite.move(distanceX * ups, distanceY * ups);`

---
Tags: c++, collision-detection, sfml
---


# Question
Title: What is the difference between a Viewport and a Scissor Rectangle?
In XNA, what is the difference between a Viewport and a Scissor Rectangle, and when should I use each one?

It looks like viewport clipping is applied to the geometry before the rasterization state, which should make it "faster", while the scissor test is applied afterwards during the pixel stage.

I primarily work with 2D graphics, and from what I can tell, they both *seem* to function the exact same way with no appreciable difference otherwise, save that the scissor test is more annoying to set up, because you have to create a new `RasterizerState` object to enable it.

# Answer
> 7 votes
Viewports and Clipping (Direct3D 9) is a good overview that, while specific to D3D9, is relevant to all APIs.

The viewport defines an additional transformation that occurs before rasterization:

> Direct3D uses the viewport location and dimensions to scale the vertices to fit a rendered scene into the appropriate location on the target surface. **Internally, Direct3D inserts these values into the following matrix that is applied to each vertex**. (...matrix description follows...) This matrix scales vertices according to the viewport dimensions and desired depth range and translates them to the appropriate location on the render-target surface.

Scissor Test on the other hand operates within a viewport, occurs after the pixel shader stage, and gives you the ability to constrain per-pixel operations to a rectangular portion of the screen, but without actually modifying the current viewport transform.

---
Tags: xna, graphics
---


# Question
Title: Box2d joints still attached after Explosion simulation
I ported simple Box2d Explosion simulation the function is called once when there is some event with the "Truck Car"
the problem is that the Explosion working fine but it looks like when the explosion done the "parts" of the car Returning to
the initial car position instead of bean scatter on the floor.
what am i doing wrong here ?

here is the code for the Explosion

```
class MyQueryCallback : public b2QueryCallback {
public:
    std::vector<b2Body*> foundBodies;

    bool ReportFixture(b2Fixture* fixture) {
        foundBodies.push_back(fixture->GetBody());
        return true;//keep going to find all fixtures in the query area
    }
};
void BackgroundSprite::explode()
{
        float m_blastRadius = 40.0f;
        float m_blastPower = 50.5f;
        MyQueryCallback queryCallback;
        b2Vec2 locationPnt = _truck->truckBody->GetPosition();
        b2AABB aabb;
        aabb.lowerBound.Set((locationPnt.x - m_blastRadius), (locationPnt.y - m_blastRadius));
        aabb.upperBound.Set((locationPnt.x + m_blastRadius), (locationPnt.y + m_blastRadius));
        m_world->QueryAABB(&queryCallback, aabb);

        for (int i = 0; i < queryCallback.foundBodies.size(); i++) {
            b2Body* pBody = queryCallback.foundBodies.at(i);
            b2Vec2 pBodyPos = pBody->GetWorldCenter();
            b2Vec2 pHitVector(pBodyPos.x - locationPnt.x, pBodyPos.y - locationPnt.y);
            float radDist = pHitVector.Normalize();
            radDist = (radDist * PTM_RATIO);
            if ((pBody->GetType() == b2_dynamicBody) == (radDist <= m_blastRadius)){

                float nHitForce = ((m_blastRadius - radDist) / m_blastRadius) * m_blastPower;
                b2Vec2 appForce(pHitVector.x*nHitForce, pHitVector.y*nHitForce);
                pBody->ApplyLinearImpulse(appForce, pBody->GetWorldCenter(),true);
            }
        }
 }

```

see what i mean in the video at 3:30 https://www.youtube.com/watch?v=3JmimxLiTpo

# Answer
It doesn't matter what forces you apply, explicitly or implicitly to the joined bodies, the joints will always attempt to restore the relative position/angle of the joined bodies in accordance with the joint type. There are only three ways I can think of for which a joint will stop functioning:

1. The joint is explicitly destroyed using `b2World::DestroyJoint`
2. One of the bodies is destroyed using `b2World::DestroyBody` which destroys all connected joints automatically.
3. At least one of the bodies is deactivated by passing a `false` argument to the `b2Body::SetActive` function. All connected joints are implicitly deactivated. The joint is reactivated when both bodies are again active.

I recommend option 1, unless you have some special reason to do otherwise:

```
    /* ... */

    void BackgroundSprite::explode()
    {
        /* ... */

        for (int i = 0; i < queryCallback.foundBodies.size(); i++) {
            b2Body* pBody = queryCallback.foundBodies.at(i);

            /* ... */

            b2JointEdge* jointEdge = pBody->GetJointList();
            while(jointEdge) {
                b2Joint* joint = jointEdge->joint
                jointEdge = jointEdge->next;
                m_world->DestroyJoint(joint);
            }
        }
    }

```

What you may want to do is destroy the joints when a threshold force is exceeded. For those cases, you need to check the forces exerted by every joint on every iteration to determine which (if any) joints need to be destroyed.
> 1 votes

---
Tags: box2d
---


title: Neural Net Controlled Car

text:
# Question
Title: Neural Net Controlled Car
I'm trying to make an AI car controlled by a neural net.

I saw this two videos: Neural Network Demo and Q Learning and neural network in 2D car driving and I want to replicate that.

I already have the neural net code made, with a back propagation algorithm.

The thing is, I don't know how to reinforce the learning of the net. What kind of value should I use to calculate the error?

My car currently have 5 inputs (similar to the first video), and outputs 2 numbers, 1 which is plugged in the rotation torque of the car, if it's positive it will rotate clock-wise, if it's negative counter-clock-wise, and how much it will turn is based on it's magnitude, it ranges from -1~1, and I mapped it to a desired min-max rotation. The second output number is acceleration, it's from 0~1, but mapped to -10~100 (so it can reverse).

# Answer
In general you want to give the neural net a reward function that it is trying to maximize, or, alternatively, a cost function it is trying to minimize. In the car example, "distance along the track" is a good indicator of progress. You can simply reward the neural net for making progress along the track.

In the simple case, imagine a neural net that tries to drive a car along a perfectly circular track with radius `R`, centered at `[0, 0]`. It has only one output to the car: steering angle `(a)`, and only two inputs: the angle of the car around the track `(t)`, and the radius from the center `(r)`. Assume the car has a constant forward velocity of `1`. Assume the car moves for a fixed number of timesteps `N`.

Therefore, given an action `a_i`, we can produce a state `[t_(i + 1), r_(i + 1)]` as:

```
x_i = [cos(a_i), sin(a_i)] + [r_i * cos(t_i), r_i * sin(t_i)];
f(a_i, t_i, r_i) = [atan2(x), norm(x)];

```

We can create a simple reward function as telling it to advance along the circle and maintain a constant radius:

```
R(t, r) = t + (R - r)^2;

```

The car tries to maximize the sum of this reward over its entire trajectory with its policy:

```
Sum(i = 1 to N of R(t_i, r_i))

```

So, the neural network generates a policy based on the state of the car. This in turn produces a trajectory, which is scored based on the reward function. The neural net attempts to learn a policy that maximizes the reward function in expectation over time. That is, it is trying to find:

```
policy*(t_i, r_i) =
  arg_max Sum(i = 1 to N of R(f(policy(t_(i - 1), r_(i - 1)), t_(i - 1), r_(i - 1)))

```
> 2 votes

---
Tags: ai, car, reinforcement-learning
---


title: Game Opens then Stops Responding Python

text:
# Question
Title: Game Opens then Stops Responding Python
Sorry for the bad title, if you think of a better one please tell me.

So I was asked to make a button that says a line from a video game. I attempted to have the while loop add 1 to a variable every time it looped through, then display the variable in the caption of the window. I did this so that I could see if it was looping, and really, what was going on. It showed a rapidly increasing number, then froze the computer (I had to restart the computer). I tried putting a short wait in the loop, still would not respond. I am also having this exact same problem in a much longer and more complex program that I'm working on, so if I figure it out, it will solve both issues. Don't just give me code, please tell me why I need to use it or what it does. Here's the program:

```
from pygame import *
import pygame
pygame.init()

pygame.display.set_caption('Potato')
screen = pygame.display.set_mode((224, 224))
button = pygame.image.load("C:/Python34/redbutton.jpg")
screen.blit(button,(0,0))
pygame.display.flip()

potato = pygame.mixer.Sound("C:/Python34/potato.wav")

test = 0
pressed = False

while pressed == False:
    if pygame.mouse.get_pressed()[1]:
        pressed = True

    if pygame.mouse.get_pressed()[0]:
        potato.play()

sys.exit()

```

# Answer
From the documentation for `pygame.mouse.get_pressed()`:

> Note, remember to call `pygame.event.get()` before this function. Otherwise it will not work.
> 1 votes

---
Tags: python, pygame
---


# Question
Title: Feasibility of a project in certain languages
My current project is a very simple browser-based game. The player moves with the keys and draws a bow with the mouse to shoot arrows at approaching enemies. This seemed to me like the perfect game for a Python/PyGame implementation and it proved to be true - except if I want it browser-based (Desktop version already works perfectly).

Is there any way I can get Python/PyGame running from a server in a browser window? I tried Kivy but it seems to have problems handling PyGame.

Is there a way to use HTML, PHP or the like to get the Python/PyGame script running in a browser window by "translating" inputs to the Python script and vice versa translating returns into view changes?

Is there an alternative (JavaScript + additional libraries?) that offers me: PNG with Alpha handling readily implemented (I don't really want to use another few days to write that on my own...), easy catching of mouse/key inputs and an "easy-going" license policy that allows me to publish it donation-based without having to pay for a license?

*Note: If I really have to change to another language anyway, then I'd prefer one where I can implement catching touch-screen inputs from mobile devices.*

I'd really appreciate any advice on these questions as I'm really stuck with it until I know to which language I have to translate the Python/PyGame version.

# Answer
I don't think you can use Python in browser like you want.

But you can sure use Javascript for your needs.

I've made an experiment back to when I was still in school.

Check the source code, it should help you to reach your goal.

The game works in pure Javascript and CSS, no canvas, no library besides jQuery, you need to use the arrows to move, there was a Ajax functionnality I stripped of, so you can run it as is from the html file.

http://dl.free.fr/fxByZo3hd
> 1 votes

---
Tags: platform
---


title: Understanding CGPoints in SpriteKit

text:
# Question
Title: Understanding CGPoints in SpriteKit
I am planning to place three cards on a view which I add to the background. However I wanted to combine two of the cards and replace the first card position with the new card position. Is there any way I can do this?

I am trying to read the selected node position by:

```
CGPoint position = CGPointMake([self nodeAtPoint:touchLocation].position.x, [self nodeAtPoint:touchLocation].position.y);

```

However what I read is (0,0).

What happened?

# Answer
> 1 votes
In your scene controller, you should do this inside `-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event`:

```
UITouch *touch = [touches anyObject];
CGPoint touchPos = [touch locationInNode:self];

```

`touchPos` will have the position inside your scene, and you can do:

```
if ([self.cardOne containsPoint:touchPos]){
    //Do something
    CGPoint cardOnePosition = self.cardOne.frame.origin;
}

```

If you want to get what node are you touching in a better way, you can subclass SKSpriteNode (for your cards) and from there implement `-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event`, make sure inside init you make `[self setUserInteractionEnabled:YES]`. Then you could set up a delegate from this subclass that calls a method in your scene, and from your scene controll what to do better.

---
Tags: ios, objective-c, spritekit
---