# Question
Title: How can I save and load an adventure game?
I'm using cocos2dx and sqlite to store datum. The table looks like this: `x INT, y INT, className TEXT, properties TEXT`. I use json to serialize terrains and sprites. But I don't know how to synchronise it. Below is how I'm doing:

```
//1: create a interface takes an range and returns data in it.
Data getData(Rect range);

//both are global objects.
cachedRange = [];
cachedData = [];

//2: while reading from sqlite, I scale the range and cached other data.
Data getData(Rect range){
    //if it has been cached.
    if(cachedRect.contains(range)){
        return retrieveDataFromCached(cachedData, range);
    }

    var scaledRange = scale(range, 10);
    var data = retrieveFromSqlite(scaledRange);
    var inRange = [];
    for(var d : data){
        if(range.contains(d)){
            inRange.append(d);
        }else{
            cached.append(d);
        }
    }
    cachedRange.append(range);
    return inRange;
}

```

However, these data will change. For example, some mobs are instantiated and then killed, and some are moved. When should I delete original records of the table.

# Answer
> 0 votes
Give each persistent object an unique `id` value (an `unsigned int` should suffice unless the number of objects can go into billions). Use that value as the `primary key`* of your database table. This ensures that the database will never have two entries for the same object. I would recommend you to not use `auto increment` for the id and instead assign that value by the game. That way the game doesn't need to ask the database which id value it assigned to the object.

When you update or remove a game-object, always do so by referring to it by its `id` (`DELETE/UPDATE table ... WHERE id = ?`). That way you make sure that no other game-object is modified.

<sub>* for those which do not often work with relational databases: the primary key uniquely identifies each row. There can only be one row per unique primary key value and finding database rows by primary key is usually very fast because it is automatically indexed. </sub>

---
Tags: c++, cocos2d-x, adventure-games
---


title: Port forwarding client and server?

text:
# Question
Title: Port forwarding client and server?
So, lets say i have a client and server sending information to each other. Do i have to port forward both the server and the client, or do i just port forward the server? If i have to do both, is there any way of not needing to port forward? Im using SFML to be specific.

This isnt on local networks and its using UDP.

# Answer
> 1 votes
No, you don't need to port forward the client. If the server runs on a home computer (behind a NAT) then yes, you need to port-forward the server or check out how udp-hole-punching works but if the server runs on a *real* server (a server you rent with a public ip-address) then it should work out of the box.

Note though, the client, which is probably behind a nat, needs to send the first (and possibly a few more) UDP-packets to the server before the server can reach the client.

Another thing to note: It doesn't matter on which port the client listens for UDP-packets (and on which port it sends), the server *has to* send it's packets back to the port which the receiving packets contain as sender-port, which is not necessarily the port the client listens on!

For example:

The client listens on port 5555 and therefore sends its packets from port 5555. The server also listens on port 5555 and sends its packets from port 5555. The client now sends a packet to the server to port 5555 but the server sees the packet coming from client\_ip:45671. The server now needs to answer to port client\_ip:45671, **not** to client\_ip:5555 even though the client listens on port 5555!

---
Tags: c++, networking, sfml
---


# Question
Title: Box2d How to connect distance joint to the ground?
I have a rectangular fixed size world. I want to connect a body inside it to any place(near that body) in the world with a `b2DistanceJoint`. Do I need to create a large static body with the size of the world that can't collide with anything? Or is there a better method? Will it slow down simulation speed if I have around 300 bodies moving on the surface of this static body?

# Answer
**Do I need to create a large static body with the size of the world that can't collide with anything?**

No.

**Or is there a better method?**

In the wise words of master Yoda:

> Size matters not

In this case it means that the joint anchor points on a body need not be inside any of the fixtures of the body. They can be miles away if you want.

Make a small `b2body` somewhere well outside the gameplay area, make it a `b2_staticBody`, and make the fixture a sensor body so that any collisions that do happen to occur don't affect the simulation. Then use this body whenever you want to join something to the ground.

**Will it slow down simulation speed if I have around 300 bodies moving on the surface of this static body?**

Yes. The reason you want to make a *small* body is precisely because of what you mentioned. Any collisions with this body are meaningless, and box2d creates a contact object and stores it on the world for every contact between fixtures. It also iterates through this list every time the `step` function is called. So by keeping it small and out of the way you can conserve memory and cpu time.
> 0 votes

---
Tags: box2d
---


# Question
Title: Does distant and large objects use up a lot CPU usage?
Okay I'm new to Unity, and I'm making a space sim pc game. You know, space is huge, light years of distance between stars. Even if I set 1 AU (150,000,000 KM) as 1 unit, 1 light year will be 63,000 units, that's far far away from one another. Let say planet Earth's scale is 1, then the Sun will be 110x times the size of the Earth. This is big, because if the player's scale is 1, then we need to rescale the planets, the stars. I don't know whether or not Unity will handle large objects or far objects nicely, what I mean here is if a planet is, for example 10000 units, will the objects stop being processed by cpu? And does large objects use more cpu performance, if it does, how much it use?

**What I want to know**
1. Does far far away objects use up more cpu usage?
2. Does gigantic objects use up more cpu usage? I know it sure does, but how much? Is it 2x scale = 2x cpu usage on that object?
3. Do you have a way to minimize the usage of cpu, or more efficient way to do with large and distant objects?

I'm just started Unity last month, and get excited about how much could Unity do, but i always concern about how much cpu usage does this task use up. Any ideas?

# Answer
Aside from my comment (don't have the flexibility to pull back a specific post at the moment) the answer to your question:

# No, but...

There is no CPU gain or loss by changing scale. It's not even correlated, except for one case.

And that one case is *rendering.* When you scale an object (especially non-uniformly) then it cannot be batched with other like-objects. There are two kinds of batching, static and dynamic.

Static batching is super ridiculously fast. But....it only works on objects that don't move, rotate, scale, animate, or in any way change. They are *static.* This is functionally equivalent to `Mesh.CombineChildren` though it happens automatically and will have better results.

Dynamic batching is slower, but still faster than not-batching in most cases. Dynamic batching will group objects that have the same material together into a larger mesh, provided that:

* They have the same material (material instances, even if 100% identical, break batching)
* The total vertex-attributes is 900 or fewer (if more than 900, they will be grouped in batches of 900).
    + This value may change in the future
* The objects have the same lightmap
* Single-pass shaders (multiple passes will break batching)
* Real time shadows break batching
* The objects have the same scale
    + Non-uniformly scaled objects *can* batch, but the exact details aren't listed.

There may be an impact from having a view frustum that is very large (measured in AU) due to the large size/very distant object jackmont mentions. This is less of a concern than his comment makes it out to be *except for* the amount of geometry involved.

Largely speaking Unity can render a single 100,000 vert mesh faster than it can render ten 10,000 vert meshes (I cannot find the thread where this was posted now) but that test was done with a very simple flat plane. In terms of real impact, simpler geometry renders better at longer distance (also known as LOD = Level of Detail) because it's so small, calculating the UV and lighting details for something that's only a few hundred pixels shouldn't involve more than a few dozen verts: there's simply not enough screen space involved to make the increased detail matter.

Same thing applies to textures and animations: at very long distances where the object shrinks below the size of a dime, you can start using smaller textures and simpler models and disabling animation entirely: the user simply isn't going to notice.

However, all of the constraints involved in rendering these are GPU and RAM/vRAM based, not CPU.
> 3 votes

---
Tags: performance, unity, gameobject
---


title: Get bullet movement direction?

text:
# Question
Title: Get bullet movement direction?
I have two objects, A and B, at two different points. I want B to fire at A. B's shot moves so far x and y every frame. How do I get the angle it needs to travel at as two numbers, one representing how much X changes and how much Y changes per frame?

# Answer
You don´t need the angle. Just use:

```
x(v)= x(a)-x(b)

y(v)= y(a)-y(b)

```

Your new vector (x,y) (v) will have the ammount of movement in X and in Y axis needed to go from one point to another.

You can then calculate the ammount of distance per frame based on this vector.
> 3 votes

# Answer
You don't seem to need the angle, only the delta vector between the two positions.

vA = vector representing position of A

vB = vector representing position of B

vD = vA - vB // distance and direction to travel

vD / len(vD) = vDu // direction of travel

And you multiply vDu with your speed per frame, this will give you the distance per frame.
> 3 votes

# Answer
Well, as you mentioned only mathematics tag so I'm assuming that you have to do everything manually, without built-in vectors functionality.

So, I'm writing here on of the may methods to do so.

First find the Slope between two points at which bullet A and B do exist, by which we can calculate angle through which I'll determine the direction.

Considerations:

Slope = **m**

A's position = **x1, y1**

B's position = **x2, y2**

tan inverse = **atan**

angle = **theta**

First find **m** between both bullets as,

**m = (y2 - y1)/(x2 - x1)**

**theta = atan(m)**

Now using parametric equation of circle which will give you the direction, and you want **B** to fire at **A**

**newX = Cos(theta)** --(1)

**newY = Sin(theta)**

**B's position = x2 + newX, y2 + newY**

**Repeat from (1)**
> 1 votes

---
Tags: mathematics
---


# Question
Title: Is there a known most efficient version of A* search algorithm?
Is there a known 'most efficient' version of the A\* search algorithm? I know some people write papers on the most efficient way to compute common operations, has this been done for A\*?

# Answer
If you don't mind bibliography, take this list as a starting point. It's a series of articles from the Game Programming Gems and the AI Game Programming Wisdom series, with the most relevant ones being:

* Beyond A\* - Game Programming Gems 5
* Advanced Pathfinding with Minimal Replanning Cost: Dynamic A Star (D\*) - Game Programming Gems 5
* How to Achieve Lightning Fast A\* - AI Game Programming Wisdom
* Practical Optimizations for A\* Path Generation - AI Game Programming Wisdom
* A\* Aesthetic Optimizations - Game Programming Gems
* A\* Speed Optimizations - Game Programming Gems

If I remember correctly from what I've read, there's no *ultimate version of A** being presented, but rather a series of optimization and improvements you can make to increase its performance or memory usage in *specific scenarios*.

---

I wanted to add a bit more detail since I own these books, but I won't have access to them until the end of the month. Here's what I can somewhat recall from memory though. First, there are several optimization you can apply while using a regular A\* implementation.

The most significant change you can make is *simplifying the search space*. There are many different ways to represent your search space, each with pros and cons, and choosing the correct one for the job is pretty much the most deciding factor in A\* performance. The most common space representations are using a grid, a navigation mesh or a visibility graph.

*Tweaking the heuristic* can also affect the speed of your pathfinding. For instance, they say that the heuristic has to be admissible (i.e. it never overestimates the actual cost) for A\* to find you the best path. But sometimes if you overestimate the heuristic *a little* it will speed up the search and the paths returned will be similar enough (maybe not perfect every time, but significantly close).

Finally, there are many *variations on the algorithm* itself to make it work under different circunstances, for instance, just to name a few:

* D\* (Dynamic) - Dynamic in the sense that it works under the assumption that the terrain can change even while you're still looking for the path.
* HPA\* (Hierarchical) - Uses several layers at different abstraction levels to speed up the search. For instance, an higher level layer may simply connect rooms, while a lower level layer takes care of avoiding obstacles.
* IDA\* (Iterative Deepening) - Reduces memory usage in comparison with regular A\* by using iterative deepening.
> 15 votes

# Answer
Bit of an old one (stumbled into this searching for something else entirely) but I didn't see Jump Point Search explicitly mentioned.

There's a good article here (which I think is from someone who worked closely on the development of the approach) that describes very well how it works, how to implement it, and why it's faster.

Briefly it works on the notion that you can cull the search space on A\* without needing to consult the heuristic, due to the flat (as in space-curvature) nature of grids (examples are 2D, but it works for 3D as well, if properly extended). There's no need to add the node you *just came from* to the search space, obviously, but there's also no need to add *any common neighbors* either: it will always be faster to go from the parent to the common neighbor directly than to pass through the current node, so you end up with the following:

Where the arrow represents parent-to-current, the gray nodes can be ignored, and the white nodes are the new ones that need to be added to the search space. \[4,2,3\] and \[4,x,3\] have identical path lengths, but it is excluded as it will already be checked later when expanding from node #2 diagonally (see Figure 3) or earlier (e.g. the parent of node #4).

There are some special-case rules dealing with obstacles (e.g. if in the right half of the above image, if node #4 was impassable, you'd need to include node #1 in addition to 2, 3, and 5):

As well as simply heading in a straight line until an obstacle is reached before adding any nodes to the search space at all (hence the name of the optimization: "jump point" as the code locates virtual "lily pads" that it jumps to as the only *important* nodes in the path).

> Intuitively, the objective is to eliminate symmetries by recursively “jumping over” all nodes which can be reached optimally by a path that does not visit the current node. We stop the recursion when we hit an obstacle or when we find a so-called *jump point* successor. Jump points are interesting because they have neighbours that cannot be reached by an alternative symmetric path: the optimal path must go through the current node.

> **Figure 3: Jumping Examples.** Node x is currently being expanded. p(x) is its parent.
>
> (a) We recursively apply the straight pruning rule and identify y as a jump point successor of x. This node is interesting because it has a neighbour z that cannot be reached optimally except by a path that visits x then y. The intermediate nodes are never explicitly generated or even evaluated.
>
> (b) We recursively apply the diagonal pruning rule and identify y as a jump point successor of x. Notice that before each diagonal step we first recurse straight (dashed lines). Only if both straight recursions fail to identify a jump point do we step diagonally again. Node w, which is simply a forced neighbour of x, is generated as normal.

Even without the recursion, the simple pruning and forced-neighbors rules improve the performance of A\* dramatically and are incredibly easy to implement. I did it once myself and only had a few minor problems related to pruning the list post-A\* so that I could have straight lines through open spaces (rather than diagonal doglegs) that resulted in a very hard to replicate issue where a path tried to prune 90% of its length by going through a wall. It only happened in a very specific setup, only in the one direction, and never managed to figure out why it thought it was ok (project has since been scraped and rebuilt from the ground up).
> 4 votes

# Answer
**D\* Lite** if you want AI that behaves in the way that a human might when exploring a completely new and unknown area, needing no prior knowledge of the map except for the coordinates of start and goal, and which can adapt to a changing map. This algorithm is both conceptually simpler and more efficient than the original D\*, effectively obsoleting D\*. It's been used in some of the Mars rovers. This algorithm eliminates the typical "omniscient", know-it-all behaviour of AIs we've all seen in games, the ones that move based on a single pre-emptive A\* run on a known map.

D\* Lite works on an *ad hoc* basis. It begins by calculating a fairly direct path between the designated goal and start points, working backward from goal to start, not *yet* knowing the occupancy status of those nodes along the path. It then begins to walk this path, like a pioneer.

This continues until it hits an obstacle on a node which it previously expected to walk through on its way to the goal. As a result of this mishap, it recalculates the remaining path (again backwards from goal to present position) based on the now known obstacle(s) and tries to continue stepping. Each time it find a new obstacle along its path, it recalculates as best it can based on the sum total of its current knowledge. If it follows a path to a dead-end, it will backtrack and seek new routes to goal.

P.S. "Most efficient" depends on your use case. For procedural, changing terrains and where realistic exploration is paramount, D\* Lite is "most efficient".

P.P.S. Just like A\*, you can also accelerate D\* Lite with Jump Point Search, also mentioned here.

---

Generalized Adaptive A\* (GAA\*) is good where you want a constantly moving target. I've not tried it myself but the linked paper suggests that it is faster than A\* and D\* Lite etc. for this purpose.
> 4 votes

# Answer
A\* is the basic, most widely used, most general purpose graph traversal algorithm. Given a set of nodes, edges, and weights for those edges, a starting node, and an ending node, A\* will find the shortest path between the 2 points.

As you must know, many variants on A\* exist.

Some of these variants do things like allow for edge weights to change (dynamically "updateable" solution) (D\*: The name D\* comes from the term "Dynamic A\*", because the algorithm behaves like A\* except that the arc costs can change as the algorithm runs.).

Algorithms such as LRTA\* (learning real time A\*) will modify the graph as it explores it, increasing costs of edges that lead to dead ends and the like (hence "learning").
> 2 votes

---
Tags: algorithm, search
---


# Question
Title: Simplyfing/dissolving octree to simple boxes by adjacent octants with similar traits
I am looking forward to create a navigation volume to be utilized by AI actors.

The approach I am trying to tackle here is to first generate an octree and associate with respectable flags/data (type, what's contained for now). The octree is going to be fairly deep (up to 0.1 units).

This is the scene I am using for testing purposes:

results in 1947817 nodes in 9 levels. (22 x 9 x 22)

I am looking for an algorithm/concept/pseudo-code that would transform this octree into non-uniform, axis-aligned boxes derived from octants that match certain flags/data, that would, for instance, help me determine the navigation volume similar to what can be seen here (Havok):

With "I am looking for" - I have a feeling of such an algorithm/concept already existing, though, I am not sure. The feeling drives me towards this being a fairly mathematical problem that resides behind a common name.

The other approach would be to utilize a non-uniform grid (creates 4356000 cells) for the detailed shape to then be expanded (simplified) down to some boxes. Which my feeling tells, would utilize the same algorithm.

As for the "what have you tried part" - well... I have googled for some time with various combinations from keywords *grid, merge, cell, flags, occupied, gamedev, octant, grow, largest space, adjacent* and maybe some others to no avail. Well, before pushing the **Post** button, I did try some more keywords and ended up with this answer: https://gis.stackexchange.com/questions/23365/how-to-combine-adjacent-polygons-sharing-similar-trait-into-single-polygon which appears to be close to what I am looking for, except that it's 2D (though, I gave the keyword "polygon" for this query). Having learned that the process is called "dissolve", I made some more attempts with various combos with added word "dissolve". And through my findings some more searches and so on... Well... nothing.

If the answer wont yield any results, I know that I could attempt this by raying the hell out of the **graph** by starting at either corner and flooding through it all, basically, brute forcing my way.

So...

**Is the common algorithm/concept already out there, that I could be pointed towards?**;
or - **what guidelines should I follow to produce such a product?**

# Answer
If what you mean is that you need a nav-volume with fewer nodes because the oct-tree ends up leaving you with too many nodes, the main issue behind you problem is, of course, symmetry.

Or better said, the fact octrees do not allow for asymmetric nodes. The result of that is empty space ends up being wastefully divided - either in the within a given level, or worse, having to go down to more levels.

There are, of course, ways of just merging the boxes generated by octrees into arbitrary polyhedron. But I think that before going that route, what you are needing is the same I myself needed in a similar project: the correct spatial partition tool. In this case, KD-trees. These are much more appropriate than octrees for what you seem to be trying to achieve. The reason is that KD-trees are precisely spatial partitioning that allow for irregular (asymmetric) axis-aligned boxes.

In youtube you find some examples of 3D KD-trees: https://www.youtube.com/watch?v=\_mzArAN7HYc

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

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

More technical links are:

Introduction to kd-trees

Kd-trees and range trees

Specifically on navigation using nav-volumes, you can take a look at:

Getting off the NavMesh: Navigating in Fully 3D Environments

Efficient path-finding in free space

Practical motion planning for aerial-like virtual agents in Meta!Blast: A full and complex three dimensional virtual environment

http://web.archive.org/web/20110830022549/http://face2face.grandnotions.com/2011/08/pathfinding/

3D Pathfinding – Simulating Intelligent Navigation for Flying Creatures in Computer Games

Or see it in action here: https://www.youtube.com/watch?v=pq\_nte8bVoE

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

And for gentle introductions to the many spatial partitioning possibilities, see these two slide-shows: Acceleration: Spatial trees

CS 354 Acceleration Structures
> 1 votes

---
Tags: unity, procedural-generation, 3d-meshes, octree
---


# Question
Title: Best way to draw 2D shapes on a 3D flat object
I want to draw shapes (arcs, circles, lines) on a table, which is in 3D space. The table top is at Y=0 level and oriented so it points to (0, 1, 0). There are some other 3D objects on the table, so depth buffer has to be used. What is the best way to do this?

I do it now by drawing triangles or flat models on top of it. But for this I have to draw them at - for example - y = 0.05 This causes problems, because too small value makes z-fighting, especially on Android, and I'm going to have more of these drawings, so I would need to use different Y levels. I want the object to be perceived that they are exactly at the table level.

Some texturing? Some other way? Performance is of course important.

# Answer
> 0 votes
This is the best solution I found to this problem:

* I splitted the table model to two separate models. One contains only the table "bed" (not sure if the name is right - I mean the table top / plate). The other model has all the rest, which includes some geometry drawn over the table top (this is a kind of a billiard table actually, so it has some cushions).
* Now I start scene rendering from drawing the "table bed" object normally.
* Then I disable the depth buffer and draw all the geometry which should be drawn on the table. Some if it are flat objects made of triangles, some of it are textures (especially if arcs are needed). Geometry is drawn at the same height level as the table top (y=0 in my case). I also draw some simple shadows this way, as I don't need full blown shadow mapping or other kind solutions. No Z-fighting, because the depth buffer is off.
* Then I enabled the depth buffer, draw the rest of the table (separate model) and all the rest of geometry, including room walls, 3d objects on the table etc.

Additional bonus of this solution is that all 2D geometry drawn on the table is automatically clipped to the table bed shape (which is not 100% rectangular in my case and would be hard to clip otherwise). This is because 2d geometry doesn't write to depth buffer, so gets erased as soon as anything else is drawn in this place (ie. room walls).

The solution seems to work great.

# Answer
> 0 votes
A possible way to solve this problem is to draw your shapes on the table texture, and then apply that modified texture to the table geometry. This would allow you to keep the shapes at the exact same level as the table, and removes the need for extra geometry to handle them.

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


# Question
Title: How do I turn an image into a Box2D physics object?
I'm using Box2D for a Game Programming course, and I was wondering if it is possible to choose the best shape and size of shape for the rigidbody/fixture for a sprite based on its transparency.

I've tried to build with the idea of new content being easy to add (all data for enemies, terrain, etc. is stored in XML documents). Because of this, there will not be a new class for every enemy. This makes creating the fixture shapes difficult, since it has to be a generic solution but still map realistically to the sprite when the game is being played. The best solution I've come up with so far is to somehow figure out where the majority of the non transparent pixels are in the sprite and build the shape from that.

Does something like this exist? If not, would it be hard to implement?

# Answer
> 10 votes
I tried this. It was *hard*, but I did it.

Left is GIMP, top-right is a Box2D debug renderer, bottom-right is a build shell

## Code repository for reference

The full code is on github here. It's scattered in a whole lot of files, so it's a bit big to put here. See below for an explanation of the technique.

# How?

I used ImageMagick, Potrace, Node.js (with poly2tri.js and simplify-js), and two evenings.

This is possible also with other tools, so I'll go over the steps in a general way:

1. Draw an input image.
2. Extract the alpha channel, because we only care about the shape.

```
convert infile.png -alpha extract outfile.png

```
3. Threshold the alpha (push everything under 75% opacity to 0% and the rest to 100%)

```
convert infile.png -threshold 75% -negate outfile.png

```

This gets rid of the barely visible parts.

I also negated the image because the next step's Potrace understands black pixels as stuff it should be tracing.
4. Trace to a vector format.

With the right options, Potrace outputs an easily readable PostScript file.

```
potrace --longcoding --postscript --tight --alphamax=0 \
  --cleartext --output=outfile.ps infile.bmp

```

I wrote a fairly uninteresting Node.js script to parse the path data out of that and into a JSON data structure.

I threw the JSON at D3.js to see what the path data looks like. Sure enough…
5. Simplify and triangulate the path.

Again a pretty simple Node.js call through simplify, then poly2tri.
6. Put it in Box2D!

Create a body for each set of triangles, and add the triangles as fixtures. Remember to handle each triangle's vertices in counter-clockwise order.

Success!

# Shapes with holes in them

Sometimes your images have holes, like the One Ring here—

Thanks user Xander at Wikimedia!

The PostScript path data represents such situations as a sequence of paths (`rlineto`/`moveto`-commands followed by a `closepath`), such that the *first path* is the enclosing one, and all the rest are holes. That group of paths is then terminated by a `fill` command.

It looks somewhat like this:

```
<x> <y> moveto
<x> <y> rlineto
<x> <y> rlineto
[ ... more rlineto ... ]
closepath
<x> <y> moveto
<x> <y> rlineto
<x> <y> rlineto
[ ... more rlineto ... ]
closepath
fill

```

Here's how it looks when parsed, simplified, and plotted:

The blue path is the enclosing one. The red is the hole.

An image might have arbitrarily many holes:

poly2tri has methods that allow you to add holes to the generated path, as any other Delaunay triangulation library worth its salt should.

And finally, the ring in Box2D for good measure:

# Answer
> 2 votes
R.U.B.E. does this. The feature was included with the addition of samplers since v1.6.0. This tutorial video gives a description of how it can be done.

To test, I used Anko's and Xander's images for comparison.

First I imported the image of the sword and heart wand into RUBE (I'm on v1.7.0) and created some samplers (shown by dashed outlines) over them.

Once this is done the threshold alpha value can be set in the properties window for any selected samplers.

As seen above, a green outline appears showing the predicted outline of the shape. Then by using a special edit mode to select key points on your fixture outline. Depending on where the key points are, you can increase the density of fixture vertices in different areas of the outline. I've shown a couple of fixtures generated by RUBE when the control points are placed in different areas:

There is also a shortcut to create a new body from an image with a single shape (see the video for details).

It does not currently handle holes properly:

**Summary**

Here is a comparison with Anko's solution:

```
+---------------+----------------------------+-------------------------+
|               | Anko's image-to-box2d-body |         R.U.B.E         |
+---------------+----------------------------+-------------------------+
| Platform      | Linux, Mac, and Windows    | Linux, Mac, and Windows |
| GUI           | No                         | Yes                     |
| Price         | Free                       | ~$35 USD                |
| Open-source   | Yes                        | No                      |
| Handles Holes | Yes                        | No                      |
| Dependencies  | Yes (See github page)      | No                      |
+---------------+----------------------------+-------------------------+

```

---
Tags: c++, 2d, sprites, box2d, pipeline
---


# Question
Title: Solution for lightweight LAN peer discovering?
I built a library for purely cross-platform programming. My games made with it run fine in Android , Pc, Linux, Mac etc.

The networking capabilities are provided by ENET library, therefore all communication between my apps is not TCP or UDP compatible, but only in the custom protocol, even tough its based on the UDP ultimately.

I don't think its possible to do what i want with ENET, thats why I ask here for help!

Lets say I have the same game running in my Android phone, my laptop and my pc. They are all in the same wifi network, and therefore in a LAN, whether its Wifi hotspot(?) or the household router.

I need each of those 3 peers to discover the other two in the network. This is meant only to find the IP of alive apps in the LAN network, to be able to host multiplayer games between them.

I can only think of one effective way to do this, UDP broadcast, wait responses, but if that is the solution, i need something small, since its the only purpose of the implementation.

Other way could be to try to connect to all IPs in the LAN address subrange, but I don't think the OS would be with me on this one :p

# Answer
> 7 votes
As many people have been saying, the solution would be to use **UDP broadcast**, but there's a lot of implementation details involved. I recently ran into the same problem, and after working out a solution I've made a blog post, and a sample project in the form of a LAN chat server/client. I'll be summarising those here, but you should check them out for more details, and real code.

Here's how it works, based on a description by Lee Salzman, creator of ENet:

* Your game server runs on one socket, as an ENet host
* The server also binds to a known "listen" port, as a regular UDP socket (i.e. not an ENet host)
* The client sends a UDP broadcast message (i.e. IP 255.255.255.255) to that listen port, and waits for responses
* All servers in the LAN will receive that "scanning" message, and respond. Ideally you can respond with the port that the game server (ENet host) is running on; that way you don't have to have your game server running on a fixed port)
* After the client has received some responses, it will know which servers are present. Then you can choose one of them to connect to, as a regular ENet peer. At this point the client doesn't need the UDP "scanner" socket anymore.

The good news is that ENet provides wrapper functions for using sockets, so you can do everything in ENet. The bad news is that the wrapper is extremely thin; you'll need to know about socket programming, such as what `select()` does. This is why I encourage you to take a look at the blog post and sample project so you can copy/paste the code and save yourself lots of time.

Here are some notes and pitfalls should you choose to do your own implementation:

* The listener/scanner *must* be UDP, so you need to create them using `enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM)` (or `SOCK_DGRAM` for plain old socket programming)
* For the server "listener", allow the port address to be reused using `enet_socket_set_option(socket, ENET_SOCKOPT_REUSEADDR, 1)` (or `SO_REUSEADDR`) so that multiple servers can run on the same IP
* For the client "scanner", you must enable broadcasts on the UDP socket using `enet_socket_set_option(scanner, ENET_SOCKOPT_BROADCAST, 1)` (or `SO_BROADCAST`), otherwise you can't send to the broadcast address. This is a safety feature only, to make it harder to accidentally flood the network.

Unfortunately this isn't exactly a "lightweight" solution; the sample project clocks in at a few hundred LOC altogether. It would be nice if this were packaged into a utility library for ENet, but I've found that for game servers, you often want to send some more game-specific information with the server reply to make this useful, such as:

* The game type (e.g. "co-op", "deathmatch")
* The "map", "level" or "campaign" the server is running
* The number of players and max players for the server
* Any other game-specific information that will affect the client's decision to connect or not. Think about the "server browsers" in games and the sort of information they show.

# Answer
> 2 votes
When you don't want to leave your library, you could just use brute-force and attempt to connect to each one of the possible addresses. Most home lans are Class-C networks (/24) where the first 24 bit of the IP address are the same and the last 8 bit differ. So you only have 255 possible IP addresses.

But still, doing an UDP broadcast would be the cleaner alternative. Just send an UDP packet to 255.255.255.255 and all clients behind the same router will receive it. They can then send a reply to the source IP and source port of the packet to inform the sender that they are present.

# Answer
> 1 votes
You could have a look at DNS-SD/ZeroConf/Avahi/Bonjour/mDNS. It's the stuff Apple use to share printers, iTunes folders and so on but it's been adopted elsewhere. Avahi is the opensource version that Linux uses (not sure if it's Linux only), not sure how portable the whole thing is (although there are implementations for most platforms).

Having said all that, it's probably easier to just do the UDP broadcast.

---
Tags: networking, enet
---


title: How can I create a spacial grid?

text:
# Question
Title: How can I create a spacial grid?
I just created a tile map for my game, and its a side profile game. The game looks sort of like Terraria, where there is blocks you can place and break. I want the player to be able to collide with the blocks, and I don't know how to achieve something like this.

The game is in Javascript but I can understand other languages so feel free to give examples in the language of your choice.

# Answer
> 0 votes
I created a simple platformer that used rectangle collision in order to detect if the player is currently colliding with a tile. I made the game in c# but I believe the concept will be the same for Javascript. Here are the steps I took:

1: Create a new class named **Tile**

2: Generate a list of **Tile**s in order to fill up the tilemap

3: Run a loop through each tile to determine if the player is colliding with the tile.

```
                player.Left <= rectangle.Right &&
                player.Right >= rectangle.Left &&
                player.Top <= rectangle.Bottom &&
                player.Bottom >= rectangle.Top

```

4: If the previous condition returns true, determine if the player's midpoint is above/below/to the left of/to the right of the tile's midpoint. (This is used to determine if the tile is being used as the ground, a wall, or the ceiling)

5: Manipulate Player's position according to step 4

There is a more optimal way of detecting collision, but I found this method the easiest to understand.

---
Tags: collision-detection, javascript
---


title: Problems managing collision filtering

text:
# Question
Title: Problems managing collision filtering
I have my character fixture and body(is a tank), so when I press the screen it throws a rocket(which also has a body and a fixture) that the player can controlll touching the screen. My game also has coins, which are dropped from boxes, when I destroy them, I don't want the rocket to collide with the tank, because the player can guide it anywhere(even to the tank), and it only get destroyed when touching an enemy. The problem here is that the rocket can touch a coin and move it, but it wouldn not happen. I've read that this can be solved using collision filtering, but I didn't understand very much this concept. I want the tank to collide with the coins, but not with the rocket, which should not collide with the coins.

# Answer
You can use the `filter` on the `FixtureDefinition`s to define what type of objects can collide with what.

You define a `category` bit-pattern, this describes what the fixture *is*. Then you define a set of categories that the fixture collides with.

For example;

```
class PhysicsConstants {
  // Categories
  public static final int CAT_SHIP   = 1;
  public static final int CAT_ROCKET = 2;
  public static final int CAT_COIN   = 4;

  // Collision masks
  public static final int MASK_SHIP = CAT_COIN; // This means a ship only collides with coins
  public static final int MASK_ROCKET = CAT_ROCKET | CAT_COIN; // Rockets collides with other rocket and coins, but not with ships
}

```

And then when you create your `Body` and its `FixtureDef` you set the bits on the filter;

```
public FixtureDef createRocketFixture(Shape shape) {
  FixtureDef fd = new FixtureDef();
  fd.shape = shape;
  fd.friction = 1.0f; // or whatever
  fd.density = 1.0f;  // or whatever

  fd.filter.categoryBits = PhysicsConstants.CAT_ROCKET; // I am a rocket fixture!
  fd.filter.maskBits = PhysicsConstants.MASK_ROCKET; // This describes what I can collide with
}

```
> 1 votes

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


# Question
Title: "Industry Standard" JSON formats for game assets
This question is inspired by my venture into the Phaser game engine but seems to apply to any engine that uses JSON for its asset format.

Phaser relies on PhysicsEditor to export and create the JSON data for its physics bodies and TexturePacker for its sprite atlases. When I learned this I found some free alternatives that look like they might do the job.

**So here's the problem**. These JSON creators claim their output works for a slew of different engines, but how can I be certain of that when there can't possibly be such universal collaboration between the creators of these engines? It's especially dubious considering I can't find a standard *anywhere*. I don't want to rely on a solution only to encounter a glitch I don't understand. I want certainty.

After a lot of searching I finally found this thread, in which a couple of posters also expressed these frustrations. The final post appears to come from the horse's mouth, explaining that there's some "industry standard" that everyone uses, but the poster doesn't seem to know where the industry standard comes from either.

So I'd really like to know, is this specification *actually documented* anywhere? Does it have an origin or did it just... accrete?

If there's no good answer to this question, can I at least trust the claims of, say, Physics Body Editor and Shoebox, that their exports will work anywhere?

# Answer
I am Andreas Loew - creator of TexturePacker and PhysicsEditor.

We define the export formats for our tools depending on the needs of the framework developers - in most cases we simply adapt to formats that are already available.

Most of TexturePacker's data formats are template based - you can adjust it to whatever you need.

We also have 3 generic data formats: XML, JSON Hash and JSON Array.

I currently don't remember which framework we created the format for but it was it 2011-02-14 - TexturePacker's 2.1.5 release that contained the format.

In case of Phaser we've also created clones of the JSON format "Phaser (JSONArray)" which export the same data format but do restrict the features that are available in TexturePacker. Phaser does not support polygon packing and pivot points - features that are recently available in the generic exporters.

We also work close with the framework developers to add new features - which might also extend the format. E.g. TexturePacker 4.1.0 next update will contain a pivot point editor - so the format has to be extended. We'll also make sure that the new extension is used by as many frameworks as possible.

This is how a basic entry looks like:

```
"Blue Key.png":
{
    "frame": {"x":1,"y":1,"w":117,"h":207},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":70,"y":46,"w":117,"h":207},
    "sourceSize": {"w":256,"h":256},
},

```

**frame**: The position of the sprite's data in the texture (in pixels) **rotated**: If the sprite is rotated in the texture. Clockwise by default. Might differ for some frameworks which rely on counter clockwise rotated sprites. **trimmed**: True if transparency was removed from the original sprite. **spriteSourceSize**: The non-transparent part of the sprite that is used in the frame. Additional space around the sprite is transparent. This value unfortunately contains redundancy because the w and h value is identical with the frame's w and h. **sourceSize**: The original size of the sprite including the transparency.

Recent additions to the format:

**pivot** "pivot": {"x":0.5,"y":0.5}

The pivot or anchor point of the sprite - relative to the sprite's size - 0.5/0.5 is the sprite's center. Might also be outside of the sprite. This value is optional.

**polygon mesh data**

```
    "vertices": [ [178,118], [215,168], [200,237], [159,256], [97,256], [64,218], [56,167], [86,124], [124,111] ],
    "verticesUV": [ [799,54], [836,104], [821,173], [780,192], [718,192], [685,154], [677,103], [707,60], [745,47] ],
    "triangles": [ [5,7,8], [5,6,7], [3,5,8], [3,4,5], [1,2,3], [1,3,8], [0,1,8] ]

```

Contains polygon mesh data of the sprite, split in triangles. **vertices** contains the vertices in sprite coordinates, **verticesUV** the vertices in texture coordinates and **triangles** index triplets which build the triangles.

Polygon meshes will most likely not be adopted by HTML5 game engines too fast - at least not as long as they have a fallback on Canvas sprites (which are rectangular) but will work well with WebGL renderers.

... so much for the data format.

But I agree: We should document the format so that people can rely on it.

Best Andreas
> 10 votes

---
Tags: assets, phaser, asset-creation, json
---


# Question
Title: How to access UI elements in a canvas in UnityUI
I am looking for elements on a canvas (a textfield and a slider); so I can retrieve values and pass them to a function.

But so far I can't figure out how to access them; I can see the methods of the canvas itself, but I can't see the name of the elements that I did add on the canvas.

I have the canvas saved in a variable which is public; then I did place a slider and textfield, connected to text labels; but I can't seem to access neither the label nor the slider or textfield.

```
Canvas --
        |___ Text
        |        |_____ InputField
        |
        |___ Text
                 |_____ Slider

```

I did plan to access to the text value in the input field doing something like canvas.text.inputfield.text, but this does not work, since I can't see the name of the text field when using dot notation. Same goes for the slider.

```
public Canvas mainmenu;

void Start() {
    mainmenu = mainmenu.Getomponent<Canvas>();
}

public RetrieveData(){
    // dot notation does not find sub elements of mainmenu canvas
    // only the properties and methods of the canvas itself.
}

```

How do you actually access elements on a UI canvas, if you can't see them directly, even if they are parented to other elements?

# Answer
> 1 votes
I'd recommend against finding GameObjects by name (using `GameObject.Find` or `transform.Find` as suggested in the existing answers) whenever you can avoid it.

In my experience this tends to lead to brittle relationships between scripts that are easy to break accidentally, and other more exotic bugs.

The most reliable method, if you have a script that needs to use a particular `InputField` and `Slider`, is to **give it public/serialized fields of these types**:

```
public class MyUIForm : MonoBehaviour
{
    public InputField inputField;
    public Slider slider;
    ...

```

**...and wire them up in the Inspector.**

This makes the dependency between these objects *explicit* to anyone using the editor - as soon as you attach this script, the Inspector tells you what it needs.

This dependency is also visible to Unity so it knows which assets need to be included together in a build, if they're not all scene objects. And these references are populated immediately when the object is loaded, which avoids common order-of-execution problems when one script tries to access fields of another one that hasn't had time to `Start()` yet.

Adding another object of the same type or the same name or changing the parenting hierarchy won't accidentally break this, because the object has a direct reference. Even in a scene with 100 similarly-named/functioning objects, you have the ability to specify the exact one you want.

If these objects don't exist in the same scene, you can also create intermediate scripts that hold these references. eg. a `MainMenu` script that knows about each of its child pages like `HighScoresMenu` and `SettingsMenu`, and `SettingsMenu` holding references to its inputs `PlayerNameField` and `GammaSlider`. Then if another script needs access to these fields (not sure why - any script using them should probably live in `SettingsMenu`, but let's assume there's a good reason) - it can get a reference to the `MainMenu` instance and use `mainMenu.settingsMenu.gammaSlider`. These intermediate scripts are cheap, and save the rest of your code from needing to know the guts of how your menu is organized in the hierarchy, as well as centralizing the work of wiring up scripts in the inspector.

---

If you want to wire it up more automatically, you can also use GetComponentInChildren:

```
public Canvas mainMenu;
private InputField _inputField;

void Start()
{
    _inputField = mainMenu.GetComponentInChildren<InputField>();
}

```

This will search the child hierarchy of `mainMenu`, including grandchildren and so on, until it finds something with an `InputField` component and return that. (You can also use GetComponent**s**InChildren to get an array of all matches)

This has some of the same problems as finding an object by name (moving the `InputField` to a new parent could cause us to miss it; adding another unrelated `InputField` could cause us to grab the wrong one), but we do know we're getting the right type back. It also won't be broken by someone trying to improve readability by changing the object named "InputField" to be named "PlayerNameInput" or just fixing a typo/capitalization.

When used with your own types that are explicit about their use, like the `SettingsMenu` example above, these risks largely disappear. You might create a form with two `InputField`s, but you're unlikely to ever use two copies of the `SettingsMenu`, so if the `MainMenu` script used `GetComponentInChildren` to find it instead of a direct reference, it's unlikely to ever be broken accidentally.

# Answer
> 0 votes
It is because you brought Canvas itself and you are trying to access gameObject's properties. So for that try,

```
mainmenu.transform.Find.......

```

# Answer
> 0 votes
There are multiple possibilities here.

* You can use the static function **GameObject.Find()** to find a gameobject by name in the entire scene. However, this function is a bit slow so try to call it only once.
* You can also use the non-static function **Transform.Find()** that will only search in the childrens of the transform. Transform.FindChild is deprecated and is the same as Transform.Find().

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


# Question
Title: Unity - Instantiated prefabs do not adapt to UI Layout
I have a small container, where I want listed a series of buttons. I try to fill them at Runtime like this:

```
using UnityEngine;

public class FillWithGearData : MonoBehaviour {
    public Transform SelectGearButton;
    public Transform GearPanel;

    void Awake() {
        Transform button = Instantiate(SelectGearButton, new Vector3(0, 0, 0), Quaternion.identity) as Transform;
        button.SetParent(GearPanel);

    }
}

```

But the buttons added at Runtime are not adapting to the Layout, even though the ones added before runtime seem to adapt without a problem.

Demo:

What is going on?

# Answer
> 1 votes
Your clone button's scale is Zero. Set its scale to one after instantiating it.

```
public GameObject SelectGearButton;
public GameObject GearPanel;

GameObject button = Instantiate(SelectGearButton, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
button.transform.SetParent(GearPanel.transform);
button.transform.localScale = Vector3.one;

```

---
Tags: unity
---


# Question
Title: How to make a ball hit many tiled circular objects in LibGDX
Hey guys I've been learning to make games with LibGDX. I did a tiled map in Tiled and the rest of code in java using Android Studio. I could make a ball bounce on the flour using Box2D, but I can't make this same ball hit some circular or elliptcal objects from certain Tiled's layer. I've been searching for days, but I'm very newbee to this and I can't understand the explanations the figure this out.

What happens when I click run:

It's showing the the ball image falling next to a circular shape (I think it's made by debug renderer) and the tiled image is shown, but the ball doesn't collide. The ball passes through and nothing happens. I can't see any circular shapes near the tiled image. Maybe the problem is in my for in the code below.

Here is my code:

```
public class MyBallGame extends ApplicationAdapter {
    World world;
    Box2DDebugRenderer debugRenderer;
    OrthographicCamera cam;
    SpriteBatch batch;
    Texture ball;
    Texture bg;
    Body body;
    Body circulo;
    Sprite sprite;
    //TILES
    //private TmxMapLoader maploader;
    private TiledMap map;
    private TiledMapRenderer tiledMapRenderer;
    //private OrthogonalTiledMapRenderer renderer;

    @Override
    public void create () {
        //TILES
        cam = new OrthographicCamera();
        cam.setToOrtho(false,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
        cam.update();

        map = new TmxMapLoader().load("tiles.tmx");
        tiledMapRenderer = new OrthogonalTiledMapRenderer(map);
        world = new World(new Vector2(0, -980), true);
        debugRenderer = new Box2DDebugRenderer();
        batch = new SpriteBatch();
        ball = new Texture("circulo.png");
        sprite = new Sprite(ball);
        // Center the sprite in the top/middle of the screen
        sprite.setPosition(100, 400);

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set(sprite.getX(), sprite.getY());
        // Create a body in the world using our definition
        body = world.createBody(bodyDef);
        // Create a circle shape and set its radius to 6
        CircleShape circle = new CircleShape();
        circle.setRadius(6f);
// Create a fixture definition to apply our shape to
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = circle;
        fixtureDef.density = 1.5f;
        fixtureDef.friction = 0.4f;
        fixtureDef.restitution = 0.6f; // Make it bounce a little bit
// Create our fixture and attach it to the body
        Fixture fixture = body.createFixture(fixtureDef);

        circle.dispose();
//Tiled objects:
        BodyDef bdef = new BodyDef();
        //PolygonShape pshape = new PolygonShape();
        FixtureDef fdef = new FixtureDef();

        for(MapObject object : map.getLayers().get(1).getObjects().getByType(CircleMapObject.class)){
            Circle circ = ((CircleMapObject) object).getCircle();

            bdef.type = BodyDef.BodyType.StaticBody;
            bdef.position.set(0, 0);

            circulo = world.createBody(bdef);
            CircleShape cShape = new CircleShape();
            cShape.setRadius(circ.radius);
            //pshape.setRadius(circ.radius);
            //fdef.shape = pshape;
            fixtureDef.shape = cShape;
            fixtureDef.density = 1.5f;

            body.createFixture(fdef);
        }
    }

    @Override
    public void render () {
        // Advance the world, by the amount of time that has elapsed since the
        //last frame
        // Generally in a real game, dont do this in the render loop, as you are
        //tying the physics
        // update rate to the frame rate, and vice versa
        world.step(Gdx.graphics.getDeltaTime(), 6, 2);

        // Now update the spritee position accordingly to it's now updated
        //Physics body
        sprite.setPosition(body.getPosition().x, body.getPosition().y);

        // You know the rest...
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        //TILES
        cam.update();
        tiledMapRenderer.setView(cam);
        tiledMapRenderer.render();
        debugRenderer.render(world, cam.combined);

        batch.begin();
        batch.draw(sprite, sprite.getX(), sprite.getY());
        batch.end();
    }
}

```

# Answer
> 0 votes
I had the same Problem with my game and i watch a tutorial series on youtube from Brent Aureli. He is explaining this really well i will put a link right here. Maybe it will help you as well .

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

Edit: Have you set the CategoryBits? like that

```
public static final short NOTHING_BIT = 0;
public static final short GROUND_BIT = 1;
public static final short LINK_BIT = 2;
public static final short BRICK_BIT = 4;
public static final short STONE_BIT = 8;

```

and then you need to write these lines of code for each object you create so that the categorybits can collide with each other:

```
fdef.filter.categoryBits = GetTheTriforce.LINK_BIT;
fdef.filter.maskBits = GetTheTriforce.GROUND_BIT |
            GetTheTriforce.STONE_BIT |
            GetTheTriforce.BRICK_BIT |
            GetTheTriforce.ENEMY_BIT |
            GetTheTriforce.OBJECT_BIT |
            GetTheTriforce.ENEMY_HEAD_BIT |
            GetTheTriforce.ITEM_BIT|
            GetTheTriforce.END_BIT|
            GetTheTriforce.HOLE_BIT;

```

so that the whole code should something like that:

```
BodyDef bdef = new BodyDef();
    bdef.position.set(currentPosition.add(0, 10 / GetTheTriforce.PPM));
    bdef.type = BodyDef.BodyType.DynamicBody;
    b2body = world.createBody(bdef);

    FixtureDef fdef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(6 / GetTheTriforce.PPM);
    fdef.filter.categoryBits = GetTheTriforce.LINK_BIT;
    fdef.filter.maskBits = GetTheTriforce.GROUND_BIT |
            GetTheTriforce.STONE_BIT |
            GetTheTriforce.BRICK_BIT |
            GetTheTriforce.ENEMY_BIT |
            GetTheTriforce.OBJECT_BIT |
            GetTheTriforce.ENEMY_HEAD_BIT |
            GetTheTriforce.ITEM_BIT|
            GetTheTriforce.END_BIT|
            GetTheTriforce.HOLE_BIT;

    fdef.shape = shape;
    b2body.createFixture(fdef).setUserData(this);
    shape.setPosition(new Vector2(0, -14 / GetTheTriforce.PPM));
    b2body.createFixture(fdef).setUserData(this);

```

thats just some of the code i used in my game

---
Tags: libgdx, box2d
---


# Question
Title: How can I differentiate 2 triggers in script?
I have two boxcolliders with triggers, and when I use the function OnTriggerEnter, even if I enter the first or the second trigger, it does the same thing. And I want a trigger to do a certain thing and the other to do another thing. How can I differentiate that 2 triggers?

# Answer
The better way to do so is to,

* Create 2 children gameObject of your object.
* Attach one collider to each child.
* Set tags for each collider. For example "Left" and "Right"
* Attach your script to both children.
* In script, check the tag first. Like,

```
void OnTriggerEnter(Collider col){
    if (tag == "Left"){
        print("Collided with left");
    }
    else if (tag == "Right"){
        print("Collided with right");
    }
}

```

Or you can use switch case instead of if-else.
> 1 votes

# Answer
Should be possible without using child objects, although trickier.

You would need to differentiate your colliders by something *other than* the GameObject's properties. That is: the collider properties.

If you have two colliders that cover a different volume, then one of their position or size properties is different than the other. You can use this to figure out which collider was triggered.

```
void OnTriggerEnter(Collider col){
   //arbitrary bounds determination, your setup may be different
   if (col.bounds.center.x < 0){
       Debug.Log("Collided with left");
   } else if (col.bounds.center.x > 0){
       Debug.Log("Collided with right");
   }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: How can I make libGDX text buttons look like clickable buttons?
I have this problem with my game where UI build a nice menu and other stuff with `TextButtons` and labels, but it doesn't look nice because it's mostly displaying the text of the buttons (which don't look like they are buttons).

Right now I'm using this little snippet of code to style my `TextButton`s:

```
TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle();
buttonStyle.font = new BitmapFont();
buttonStyle.fontColor = WHITE;

```

What do i need to add to make them look like a *button* and not like simple text? I'm using libGDX.

# Answer
> 1 votes
Do not just set `font` and `fontColor`, also set the properties that make up the vidual appearance such as `up`, `down` and `checked` etc. They take `Drawable` and will allow you to use any image to represent your button.

# Answer
> 1 votes
I think you mean just the look of the button? You need to do that in your favorite bitmap or vector app like Photoshop, Paint.net, Graphicsgale, etc. Search something like glossy button tutorial to learn how to make a nice looking button. Make a up, down and disabled state if you desire and set them as drawables to the corresponding "slots" for the button.

The trick with the NinePatch is that you can make the button very small and set the stretching area so it will scale to the size you need. Do this after you created a button. There are tools to create ninepatches but if you make a atlas with the texturepacker in `Gdx.tools` you can add a split parameter.

If you want to have the font have a indented look you have to edit your bitmap font for that. Render the bitmap font with extra padding so you have room to add this in your favorite drawing application. Gimp and Photoshop have filters that can create a instant intended look for you.

---
Tags: libgdx
---


title: A* in 2D game. corner pathfinding issue

text:
# Question
Title: A* in 2D game. corner pathfinding issue
the issue I'm having will be best described with pictures more so than with code, so lets have a look if you will.

So all the mobs followed the player and started attacking him, but as soon as 4 spots to the E, S, W, N were taken, mobs 1 and 2 are no longer able to find the path.

When mob from E/S/W/N spot dies they can of course find a way to the player.

My question therefore is **what is the way to implement this so that mobs can get to the player when only corners are free**?

Diagonal movement is not allowed and i'm using Euclidean distance. I've read this How do I avoid pathfinding characters getting stuck in corners? and other questions, but they dont quite cover what I need here. I'm sorry if this isnt specific enough, happy to clarify.

# Answer
**Edit:** I initially assumed both moving *and attacking* only happened N/S/E/W, and that your problem was other monsters were failing to approach the pile-up at all.

Now I understand that your attacking range is larger than your movement step, so enemies should prefer navigating to a tile diagonally-adjacent to the player over waiting behind an attacking monster when all 4 adjacent spots are blocked.

## New Answer (get to a valid attack location, even if it's diagonal)

---

As mentioned in a comment, we can fix this with a small modification to A\*.

We still invoke A\* once, with the goal as the player position. Anytime we evaluate the heuristic, we do it with respect to the player position. That's all the same.

What we change is the acceptance criterion. Rather than returning a path only when `currentNode == goal`, we accept a path if:

`AttackDistance(currentNode, goal) < attackRange`

So if we find a path that gets us to a spot diagonal to the player, within attacking range, job done! Return that path as though we'd reached the goal. Now an entity will get a valid path as long as *any* space in attacking range is reachable.

You can improve this further with the suggestion below about treating allies as high cost rather than total blockages, so that distant monsters will still approach a player who's completely surrounded.

Another possible improvement would be to cache this path, but not return it right away, to see if a closer option is available. Then we fall back on the initial find only if no closer option is found. This keeps a monster from stopping once it's in range and blocking everyone behind it, and will help for monsters that have ranged abilities but still prefer attacking in melee.

## Original answer (solves approaching a blocked target)

---

Have you considered making the pathfinding **treat cells occupied by the monster's allies, not as blocked, but as some exorbitantly high cost**?

That way, whenever there is a path that doesn't require moving through a fellow monster, the agent will still prefer such a path.

But if there's absolutely *no free path to the player*, then the agent will settle for a path that takes it through another monster (on the assumption that this monster is also piling up on the same target, and will eventually die or move).

Since your pathfinding can now return paths with other entities in them, you'll need to make sure your movement logic checks the cell before moving into it, rather than trusting that the path is always free. If it's blocked, the monster can either idle there until a clear path is found, or play some other behaviour (like ranged attacks or circling the mob).

---

The other common solution to multi-monster swarming like this is to ditch A\* and instead use something like Dijkstra's algorithm, working outward from the player and storing the path distance from the player to each cell, counting only terrain obstructions.

While this is more work, now every monster can share this one set of pathfinding data (which may pay off when you have many monsters). On its turn, a monster looks at the open cells around (and under) it, and moves to the one with the shortest stored distance to the player. (Gradient descent)
> 4 votes

# Answer
I think your issue is that you pathfind towards the players tile rather than to a tile that he can be attacked from. Since there is no actual path to the player in that case, since diagonal movement isn't allowed, of course they can't find a path.

If you just want them to get closer you can put a maximum on the number of tried nodes and always move towards the minimum of your heuristic.(In which case I'd recommend the manhatten metric)
Or you could change your metric a bit so that it's 0 when you're at a distance you can attack from.
> 2 votes

# Answer
You didn't provide a lot of information about how your pathfinding currently works, so I'm going to assume what Nils has assumed, which is that your bats are seeking a path to the player, not to the places adjacent to the player.

My solution to this would be: \- Find every spot next to the player. \- For every one of those spots, find a path to it. \- If no paths are found, quit. \- If any paths are found, take the shortest one.

For efficiency, you could even put this after your current algorithm, eg, \- Find path to player. \- If no path can be found, do the above.
> 0 votes

---
Tags: path-finding
---


# Question
Title: Problems with converting from Screen Space to World Space
I have an unproject function I've written, which takes in x and y values between -1 and 1, and a z value between 0 and 1 (0 is near plane, 1 is far plane). I create a vector off of this, and multiply it onto Matrix.Invert(ViewMatrix * ProjectionMatrix) to get the world-space coordinates of that screen position at that depth. The problem I'm having is that the given depth values don't result in the right position (at least as I understand it).

Above is a rough sketch of what I'm seeing. The black lines are the frustrum edges, red lines are near and far plane, and green line is the plane drawn at the given z depth. My assumption was that the depth would be linear, with z = 0.5 being halfway between the near and far plane, however the values all sit very close to the near plane until z is real close to 1, at which point it rapidly approaches the far plane. Am I doing my calculations wrong somewhere? Or did I just misunderstand how projections work?

# Answer
> 3 votes
The short answer is that the standard perspective projection has a side effect of focusing Z resolution near the camera, which is actually beneficial. A perspective projection turns out to be linear in 1/Z rather than Z, meaning that there are very large changes in Z near to the camera, but smaller changes as the distance increases. Here's an article explaining the effect.

Also here's another article that discusses alternatives to the traditional perspective transform, which has some graphs sort of depicting what's going on.

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


title: How to load sprite from JSON?

text:
# Question
Title: How to load sprite from JSON?
i know how to load text, but idk how to load texture from json..

this my c#:

```
 public void soalbegin(){
     filepath = System.IO.Path.Combine(Application.streamingAssetsPath, "soal.json");
     StartCoroutine ("Json");
     soaldata = JsonMapper.ToObject(jsonString);

 }

 IEnumerator Json(){
 if(filepath.Contains("://")){
     WWW www = new WWW(filepath);
     yield return www;
     jsonString = www.text;
     }
     else {
     jsonString = System.IO.File.ReadAllText(filepath);
 }

public void OnClick(){
         soalbegin();
 GameObject.Find("Panel/soal/gambar/Text").GetComponentInChildren<Text>().text = soaldata["data"][numbersoal]["soal"].ToString();//this to load text from json

//i need variable to load sprite / texture from link json
}

```

and this is my json:

```
 {
 "data":[
 {
     "id":"1",
     "soal":"siapa tokoh ini",
     "gambar":"//1.png",
     "jawaban":[
         "natsu",
         "shank",
         "goku",
         "gildart"
         ]
 }
]}

```

# Answer
**Expanded post on comment:**"JSON is just a means of storing text information right? Why not just hold a path to the sprite in the JSON file? Then whenever you obtain the information in the JSON file, call Resources.Load (jsonPath); ?"

The JSON language cannot directly load Sprites into Unity3D. However, as JSON can deal with strings, we can quite easily hold a reference to the path which contains the sprite.

Say for instance you have this basic JSON file

```
{
"data":[
{
 "id":"1",
 "soal":"siapa tokoh ini",
 "gambar":"//1.png",
 "jawaban":[
     "natsu",
     "shank",
     "goku",
     "gildart"
     ]
}
]}

```

I'm assuming the below line needs to hold the reference to where the sprite is located.

> "gambar":"//1.png",

You can quite easily use this to hold the path to the desired sprite. For this method to work, you'll need to have a folder in your Assets folder called "Resources".

> "gambar":"1",

Unity is extremely user-friendly and allows us to leave out image format types (.png/.bmp etc...) when loading them via script.

The way you would load a Sprite (.png/.bmp/.jpeg etc) contained within the "Resources" folder of your Unity project would be like so. Resources.Load

```
Resources.Load <Sprite> (spritePath);

```

So to put all of this together, you could have a basic script like so.

```
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour
{
    public string spritePath = "1"; //This should be used for the JSON string you're using to hold the reference to the path of your Sprite
    public Sprite exampleSprite;

    void Start ()
    {
        exampleSprite = Resources.Load <Sprite> (spritePath);
    }
}

```

**You would then just replace the "spritePath" string variable with the string parsed in by your JSON class.**
> 2 votes

---
Tags: unity, c#, textures, loading, json
---


title: Unity Ragdoll Colliders don't collide

text:
# Question
Title: Unity Ragdoll Colliders don't collide
I have a humanoid character with Ragdoll setup in Unity. However the box/capsule colliders on the various parts of the body don't collide with other static geometry. They do collide with the ground but not with any other static meshes. Is it possible to use them as colliders towards static meshes and what do I need to do for it to work?

# Answer
> 1 votes
Its possible that they might both be mesh colliders, if so they need to be marked convex.

Its also possible that the static meshes might not have colliders attached.

# Answer
> 1 votes
Every 2 objects that collide need to have at least 1 rigidbody between them. Both need some type of collider component, such as mesh, cube, cylinder

---
Tags: unity, physics, rigidbody
---


# Question
Title: How do I wrap textures inside shader GLSL?
I'm trying out GLSL and one of the problems I'm facing is wrapping a random texture sampler in the shader. Searching for answers on the web first, this leads me to using these:

* glTexParameter()
* GL\_TEXTURE\_WRAP\_S GL\_REPEAT
* GL\_TEXTURE\_WRAP\_T GL\_REPEAT

I'm not sure where to put this or how to use it. I'm using a custom engine for this shader and I would assume I could wrap the texture in the shader.

My main concern on this is my final output render having left and bottom artifacts. I got some previous advise it has to do with wrapping a random texture that is used for noise if that helps in my case.

# Answer
For people who come here from Google (like me), the shader version is:

```
fract (tex_coord.st)

```

this will loop coordinates in range 0.0 - 1.0
> 5 votes

# Answer
You don't set these values in the shader. You set them in your program, generally when first creating the texture (though it can be set or changed whenever).

If you've already uploaded your texture data to OpenGL then all you have to do is this:

First bind the texture if it is not already.

```
glBindTexture(GL_TEXTURE_2D, texture_id);

```

Then set the parameters.

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```
> 4 votes

---
Tags: opengl, glsl, fragment-shader
---


# Question
Title: C++ OpenGL More textured objects equals less FPS
So I'm creating a game engine with many features, last time I focused on textures.

When I finished implementing some new code (Made by myself) I created new Entity with texture, and it was working really nice.

But If I create 2 or more textured objects game starts lagging..

* 1 Cube without texture = \> 60 FPS
* 1 Cube with texture = \> 60 FPS
* 2 Cubes without texture = \> 60 FPS
* 2 Cubes with texture = 40-50 FPS
* 10 Cubes without texture = \> 60 FPS
* 10 Cubes with texture = 20 FPS
* 100 Cubes without Texture = \> 60 FPS
* 100 Cubes with Texture = \< 1 FPS
* 10000 Cubes without Texture = \> 60 FPS

I'm using GLSL sampler2D, texture UV from VBO, here is my renderer code:

```
bool textured = false;

if(entity->hasComponent("MaterialComponent"))
{
    MaterialComponent *materialComponent = (MaterialComponent*) entity->getComponent("MaterialComponent");

    if(materialComponent->material != NULL && materialComponent->material->texture != NULL) textured = true;
}

if(component->cullFaces)
{
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
}

if(textured) glEnable(GL_TEXTURE_2D);

glBindVertexArray(component->model->vaoID);
glEnableVertexAttribArray(0);
if(textured) glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

//glDrawElements(GL_TRIANGLES, component->model->getVertexCount(), GL_UNSIGNED_INT, 0);

if(textured)
{
    MaterialComponent *materialComponent = (MaterialComponent*) entity->getComponent("MaterialComponent");

    if(materialComponent->material->texture->textureID == 0) glGenTextures(1, &materialComponent->material->texture->textureID);

    glBindTexture(GL_TEXTURE_2D, materialComponent->material->texture->textureID);

    SDL_Surface *surface = IMG_Load(materialComponent->material->texture->textureFile->getPath().c_str());

    if(!surface) Error::throwError("Cannot load texture file!");

    S32 colorMode = GL_RGB;

    if(surface->format->BytesPerPixel == 4) colorMode = GL_RGBA;

    glTexImage2D(GL_TEXTURE_2D, 0, colorMode, surface->w, surface->h, 0, colorMode, GL_UNSIGNED_BYTE, surface->pixels);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
   // glGenerateMipmap(GL_TEXTURE_2D);

    glActiveTexture(GL_TEXTURE0);

    glUniform1i(baseShader->loc_sampler, 0);

    SDL_FreeSurface(surface);
}

glDrawElements(GL_TRIANGLES, component->model->getVertexCount(), GL_UNSIGNED_INT, 0);

if(textured)
{
    //glBindTexture(GL_TEXTURE_2D, 0);
    glDisable(GL_TEXTURE_2D);
}

glDisableVertexAttribArray(0);
if(textured) glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glBindVertexArray(0);

if(textured) glDisable(GL_TEXTURE_2D);

if(component->cullFaces)
{
    glDisable(GL_CULL_FACE);
}

```

So I can create new TextureAsset for each cube or I can use one TextureAsset for each cube, it makes no difference about FPS.

I'm creating new TextureAsset like this:

```
TextureAsset *textureAsset = new TextureAsset(new FilePath("PATH_TO_TEXTURE"));

```

Then putting it inside Entity' MaterialComponent:

```
MaterialComponent *materialC = (MaterialComponent*) cube1->getComponent("MaterialComponent");

materialC->materialAsset->texture = textureAsset;

```

I think there is something bad inside my renderer method, it happens only if there is more than 1 textured object. Maybe I have to clean-up texture in different way?

I'm using SDL2, SDL2\_image and GLEW.

If you need more code - just tell me.

# Answer
> 3 votes
I know it's stupid to answer my own question but...

With very, very big thanks to @Ben I fixed this problem by creating SDL\_Surface and load image to it once for each TextureAsset and store it inside TextureAsset instead of creating new SDL\_Surface for same texture and free it each draw call.

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


# Question
Title: How do you define and draw rectangles in OpenGL?
I am very new to OpenGL and I am not sure one the basis of how to create and draw objects. So how would I draw simple rectangles in a window using OpenGL? My understanding is that I need to define an array of vertices like

type name\[n\] = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};

but I am not sure how to proceed from here.

How do I used glBegin(what goes here) to draw a rectangle using this?

Thanks.

Edit 2: We are using OpenGL 2.6 or 2.7 for my class so can't use stuff from 3.0+. Also using C++ on windows

Edit: Why does this now draw 4 vertices? I know this function is supposed to work because it is from an example. It prints points but when I change it it won't draw the 4 vertices I define.

Edit: Uploaded all code I am working with.

```
void myinit(void)
{   /* attributes */

      glClearColor(1.0, 1.0, 1.0, 1.0); /* white background */
      glColor3f(1.0, 0.0, 0.0); /* draw in red */

/* set up viewing */
/* 500 x 500 window with origin lower left */

      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      gluOrtho2D(0.0, 500.0, 0.0, 500.0);
      glMatrixMode(GL_MODELVIEW);
}

void display( void )
{
    GLfloat rect[4][3] = { {0.0,0.0, 0.0}, { 500.0,0.0, 0.0 }, { 500.0,500.0, 0.0 }, { 0.0,500.0, 0.0 } };

    glClear(GL_COLOR_BUFFER_BIT);  /*clear the window */

          glBegin(GL_POINTS);
               glVertex3fv(rect);
          glEnd();
     glFlush(); /* clear buffers */
 }

void main(int argc, char** argv)
{

/* Standard GLUT initialization */

    glutInit(&argc,argv);

/* default, not needed */
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);

    glutInitWindowSize(500,500); /* 500 x 500 pixel window */

    /* place window top left on display */
    glutInitWindowPosition(0,0);

    glutCreateWindow("Sierpinski Gasket"); /* window title */

    /* display callback invoked when window opened */
    glutDisplayFunc(display);

    myinit(); /* set attributes */

    glutMainLoop(); /* enter event loop */
}

```

Edit: I was actually painting something the entire time but it was too small to see. Once I changed the point size with glpointsize() I was able to see it.

# Answer
> -1 votes
There are plenty of ways to do this, I mention here the 2 most popular one, so vertex array objects and immediate mode.

To draw a rectange on the scree with immediate mode, you need to do the following:

```
glBegin(GL_TRIANGLES);
    glVertex2f(-0.5, 0.5);
    glVertex2f(-0.5, -0.5);
    glVertex2f(0.5, 0.5);
    glVertex2f(0.5, 0.5);
    glVertex2f(-0.5, -0.5);
    glVertex2f(0.5, -0.5);
glEnd();

```

*Note: For some languages (like java) if you write a floating point number, you get a double instead of a float, so you need to give a suffix to it, like 0.5f*

*Note2: Don't use GL\_QUADS, it is deprecated, because it makes things harder for the GPU*

This is the easiest method for drawing simple things, however, because you do a lot of native API calls, it is really slow compared to other techniques. Instead, if possible, and you GPU allows it, use `Vertex array objects`.

This can make your game even faster, if you have multiple of the same model, like a 2d plane for sprites, different tree models, etc. In these cases, you only need to bind the vertexArray once, then render different objects at different location, with different attributes, it depends on **you** what you do with it.

Sadly, this topic is too in-depth for this post, and because I don't even know what language you're using, I can't even link a tutorial. Google it.

# Answer
> -1 votes
First you have to clear everything - because you are a newbie you can use `glClear(GL_COLOR_BUFFER_BIT);`

After that it's time to "set" your "background" color like this:

```
glClearColor(0.0f, 0.0f, 0.0f, 255.0f);

```

You can put your own RGB color here.

And finally draw simple quad.

And after that you have to update your screen, the way to do that depends on which library you are using for windowing.

So here is the final code:

```
float r = 0.0f; //RED
float g = 0.0f; //GREEN
float b = 0.0f; //BLUE

glClear(GL_COLOR_BUFFER_BIT);
glClearColor(r, g, b, 255.0f);

glBegin(GL_QUADS);
glColor3f(1.0f, 1.0f, 1.0f); //You can set RGB color for you vertex
glVertex2f(-0.5f, 0.5f);
glVertex2f(0.5f, 0.5f);
glVertex2f(0.5f, -0.5f);
glVertex2f(-0.5f, -0.5f);
glEnd();

//UPDATE THE SCREEN

```

Edit:

For now you can keep using Fixed Function Pipeline but in the future I suggest you to learn shaders.

You can read about OpenGL's rendering pipeline here: Rendering Pipeline

---
Tags: opengl
---


# Question
Title: ARMv7 vs FAT in Unity Android Build Settings (release multiple valid APKs)
If I select ARMv7 instead of FAT (ARMv7+x86) in the Android Build Settings of Unity5-Free, the APK binary drops to half size.

```
FAT => ~20MB
ARM => ~10MB

```

(Tested with an empty scene, no assets, nothing, just the core libraries).

I've seen the "official stats" of the CPU usage are here:

http://hwstats.unity3d.com/mobile/cpu.html

So not a lot of business to loose as for the date of publishing this question. But x86 seems to be an increasing trend.

**Questions:**

1. Is there any way to publish a binary to the ARM users and another version to the x86 users but with the same product-id so if they change the mobile phone, the software gets properly downloaded (but still each one gets a small footprint)?
2. Does this CPU correlate with WinPhone? Or is an othogonal measure? In other words: Are all Androids ARM? Or there are ARM and x86 Androids?

Thanks!

# Answer
> 4 votes
1. you can publish different versions of your APK targeting different CPU architectures, with the same package name:

Build an ARMv7 only package and an x86 only package with different version codes. The versionCode of the x86 package has to be higher than the one of the ARM package.

When publishing, send both of your APKs to the developer console. Note that you need to be in "advanced mode" to distribute multiple APKs.
2. There are ARM and x86 Androids, there is no x86 WinPhones yet.

---
Tags: android, unity, cross-platform, cpu
---


title: Mode 7 in xna/monogame

text:
# Question
Title: Mode 7 in xna/monogame
I want achieve a view like Mode 7 from snes games where the closer textures get stretched out more and more far away textures look smaller. Something like this:

What I have in my project at the moment is a flat 2d floor made from multiple textures aligned next to each other, but I'm not sure on how to add perspective to it. I'm using a matrix to transform the view, but when I tried using Matrix.CreatePerspective I only got an empty view. Is this effect possible to achieve using matrices? Or do I have to use the billboard effect on every texture that I'm drawing? And if so, how do I make it so that it's still possible to rotate the camera in every direction? I'm new to matrices and 3d in Monogame, so this is still confusing to me.

# Answer
You want to create a flat plane in 3D for this, set texture sampling to point sampling and use Matrix.CreateLookAt for the view matrix.

I suggest you read up on what the world, view and projection matrices are and what they do.
> 0 votes

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


# Question
Title: How do you apply relativistic physics to a 4x strategy game?
I had the big idea of trying to create a hard science fiction 4X strategy game (with the obvious space setting), which is supposed to simulate a realistic way of creating interstellar societies while simulating real life physics as well.

The problem is: how do I apply Einstein's relativistic equations into the game? I will make a separate series of questions for other issues, such as applying Keplerian planetary movement and Newtonian combat physics.

Do note: the game is being made in C++ and in Unity. Be warned: I am trying to simulate special relativity, not general relativity quite yet. That I can try in a different game.

# Answer
> 4 votes
Ultimately including special relativity will put limitations on the players ability to control and monitor their empire.

The most important aspect I think would be as you mentioned, communications delay. This could be implemented in different ways,

* omnipotent player - this player is not limited by relativity and is aware of everything that occurs in the galaxy (can include normal fog of war etc). The limitations occur when sending orders to systems/fleets far from the empires homeworld as orders take time to arrive.
* limited player - this player is limited by relativity and so sees a previous game state depending on how far away that part of the game is. This means that knowledge of what might happen becomes much more important. (I can imagine this would be quite annoying)

Either of these could be frustrating but I think if you give the player ways to combat these limitations they could prove to be interesting mechanics.

Some ways to do this could be,

* allow the player to prepare distant systems for different situations i.e. if an enemy is detected approaching one system others back them up.
* give the player several 'heroes' through whose eyes they can observe the universe around them and so see up to date information. The relativistic effect would be similar to a fog of war around these heroes and cause them to observe those distant systems in a previous state.

Note: sorry if this is not what you are looking for but instead want help with actual implementation. I would welcome any help with editing etc as I tend to ramble. (I would have commented but unfortunately don't have high enough reputation.)

# Answer
> 3 votes
To help with potential implementations, I think a good first step is OpenRelativity.

You can also explore the game they made - A Slower Speed of Light \- to see whether different SR consequences are interesting to you.

On the page for ASSOL you can also find links to some related publications about the experience and intuition around relativity in a game, which may guide your thoughts on how to apply them to a 4X.

# Answer
> 1 votes
I am no game designer or have any qualification but I have an idea for a realistic tactical semi turn based ship to ship combat system.

Ideally it would be full 3d movement but it is likely easier to explain in 2d.

So you would have the area of space between the 2 ships. This is measured in light seconds. Therefore at the start lets say there is a 120 light seconds between you and the opponent. You therefore have the position of them 2 minutes ago.

You then plot a course for your ship. in practical terms this would be taking your ship and placing it in the place you want it. The computer would then plot the course and tell you at what time point you would arrive at that point. a line would be drawn from your current location to the end point. The plot could be adjusted by dragging the line.

At the bottom of the interface would be a slider that you can use to show where various objects, such as the enemy ship, will be at a particular time (assuming there is no changes).

Once you're happy with the plot you can hit play and the ship will follow the commands. Now as ship to ship combat in space is actually likely to take weeks (and no one wants to play that) there will be a fast forward button. If you hit fast forward the game plays out until you pause it or there is a change in direction in the enemy ship.

remembering of course that the change is course will be reported late as you have to wait for the light to reach your ship. So you know say 120 seconds ago the ship changed course you can then project its current position (assuming no further changes of course) using the time slider and you position assuming no changes of course. You can then adjust you course in response to thier adjustment. And so the game plays out.

Combat therefore becomes more about placement of the ships. It also become faster as the ships get closer. The skill will be in placement, angle of attack and speed.

If the ship engage at high speed you could add in an effect that causes the weapons to miss due to time dilation.

Add in power and fuel constraints and need to flip 180 to burn main engines to slow down.

You get an RTS style game play with realistic physic deep and complex game play.

This Could also be expanded to fleet combat creating tactical decisions on whether to attack on mass or split and when to split etc.

At the moment the only tactics in space combat is how large is your fleet and how quick can you get it into the fight. Also if you wanted a low graphics solution do it as a tactical plot rather than a realistic representation.

I hope this makes some sort of sense. I came across this post whilst trying to find a game that did something like this.

---
Tags: physics, 4x
---


# Question
Title: How To Make My First Person Controller turn left and right in unity 5
I want my first person controller to turn left and right instead of just moving straight on that axis.

i have a 3d environment setup in "unity 5" and i am working with the "first person controller" script in unity 5 by default it moves my camera forward,back,left and right what i want is to change the left and right so that it turns the camera instead of moving straight over.

# Answer
What you want, is a rotation around the local y-axis when either A or D is pressed.

With the standard assets, this can be achieved quite easily, with the Input manager. To alter the settings, go to **Edit-\>Project Settings-\>Input**.
You should now see the settings for the Input in your Inspector window.

You want to change the Horizontal movement, so expand that and delete the Negative and Positive Buttons, as well as the alt buttons. Alternatively, you can set your preffered keys for horizontal movement. For Q and E, it would look like this:

If you look through the Settings, you can see a "Mouse X" setting. If you want to remove rotation with the mouse, you can directly edit this, or increment the Size field by 1. This will add another property at the end of the list, which you can edit.

Here are the important changes that need to be done, in order to work with the standard assets:

* Name needs to be set to "Mouse X"
* Negative and Positive Buttons need to be set, A and D in your case
* Type has to be Key or Mouse Button

Also, you will probably want to set a high Gravity, so that the rotation stops quite soon, after releasing a key. You can also play around with the sensitivity, to get a faster or slower rotation.

The final input could look similar to this:
> 1 votes

# Answer
Open up the `FPSInputController` and `CharacterMotor` classes.

Look at how `FPSInputController` reads keypresses and then sends a command to the `CharacterMotor`. You will want to create two new commands to pass (or possibly more, I've added "crouch" and "sprint" to mine, you're looking for "rotate right" and "rotate left"). You'll have to define new inputs as well, Edit -\> Project -\> Input. Add 2 to the array size and define your keys.

Start with the `FPSInputController` as it will be simpler. Do not worry about if the lines you add throw errors that prevent compilation: you're simply trying to use a method you haven't made yet.

Next, go into the `CharacterMotor` and implement the methods you are attempting to call in the `FPSInputcontroller`. They might be named `setRotateRight()` and `setRotateLeft()`, so find an existing one, e.g. `setJumping()`, duplicate, rename, and alter the variable, then go define the variable (there are multiple classes inside this file, your input booleans should be part of the `CharacterMotor` class, not the internal subclasses).

Next, find the `Update()` function, it will call another function, go to its definition. Now add some lines that look at your rotateRight / rotateLeft booleans and do:

```
var dir:int = 0;
if(rotateRight && rotateLeft) dir = 0;
else if(rotateRight) dir = 1;
elseif(rotateLeft) dir = -1;

gameObject.transform.RotateAround(Vector3.zero, Vector3.up, dir * 20 * Time.deltaTime);

```

Alter the "20" amount until you have the desired rotation speed.
> 1 votes

---
Tags: 3d, unity, character, control, single-player
---


# Question
Title: How can I communicate between libGDXand the Android Studio Java files?
The reason I'm asking is because I wanted to create a game and I know I could use Scene2D to create the UI but as far as menus go I wanted to use the tools in android studio to at least create a menu that would lead to the game screen.

They say you should try to do everything in libgdx but how would I go on about trying to accomplish this task?

# Answer
Create the menu in one `Activity`, and let that `Activity` be a "*normal*" Android activity, then have that `Activity` launch the **libGDX** game `Activity`. That sort of approach would allow you to use Android layouts for the menu but **libGDX** for the actual game.
> 1 votes

---
Tags: java, android, libgdx
---


# Question
Title: How to make my "first person controller" continue to turn left or right when key is pressed in Unity 5?
I recently posted this How To Make My First Person Controller turn left and right in unity 5

but now I'm having a slight problem when I press the key that turns my camera it only does it for a little and then it stops. I want to be able to hold say the A or D key in and continue turning until I stop holding that key.

# Answer
> 1 votes
`Input.GetButton()` instead of `Input.GetButtonDown()`

The former checks to see if the key is currently down and outputs true for every frame during the press. The latter checks to see if the key was up last frame and down this frame (that is: true for exactly one frame until released again).

---
Tags: camera, unity, control, controllers
---