# Question
Title: MonoGame.Extended Exception when loading a TMX file
I'm getting a strange exception when trying to load in a .tmx file using MonoGame.Extended. I can load the same .tmx file into other 3rd party libraries (tried to recreate the error) without any problem which makes me suspect it's not something to do with the file.

```
tiledMap = Content.Load<TiledMap>("Test");  //line of code for exception

```

Message:

> Microsoft.Xna.Framework.Content.ContentLoadException Could not load Test as a non-content file!

# Answer
This error is most likely happening because the content hasn't been built correctly with the MonoGame Pipeline tool. All content in MonoGame must be built into an XNB file before in can be loaded into the game.

The first thing to check is to make sure you've added a reference to the `MonoGame.Extended.Content.Pipeline.dll` in your `Content.mgcb` file.

Open the `Content.mgcb` file in a text editor and look for lines like this:

```
#-------------------------------- References --------------------------------#

/reference:..\..\packages\MonoGame.Extended.0.3.44-alpha\lib\MonoGame.Extended.Content.Pipeline.dll

```

If it's not there you'll need to add it. Unfortunately, this reference is not automatically added when the NuGet package is installed so you'll need to do it manually.

Copy the above `/reference` line and add it to your `Content.mgcb` file. Make sure the path is correct, in particular the version number. You should be able to locate the DLL in your `packages` folder. There's also an install guide blog post that goes through this in more detail.

If everything is correct you should see the Tiled Map Importer and Processor show up in the Pipeline GUI.
> 2 votes

---
Tags: monogame, monogame-extended
---


# Question
Title: Making Edges of Hand-Drawn Tileset Match Up
I'm making a tile-based platformer. A friend at college is doing all my art, and so far it's beautifully hand-drawn. The problem is, I can't seem to make the edges of the tilesets match up. He measures them meticulously to get sections to match up, but, due to variations in his art medium, tiles that aren't next to each other in his drawing don't match up. For example, he's drawn a basic 9-slice tileset, and the top-to-center, left-top-to-left-center, right-top-to-right-center, etc. all connect perfectly because they're touching each other in his drawing. But when I clip the tiles apart and put them together in other variations or try to put other "change-up" tiles together (any tile that wasn't touching in his drawing), the larger features fit together because of his measurements, but you can see an obvious seam where they join.

I've been using the heal tool in my graphic editor to fix the seams and re-export the tiles with edited edges to fit together correctly, and it works well, but when I heal the edges for one seam, it makes another seam appear.

*Note: I don't want a solution to fix the seams at runtime using graphical filter magic or something on the code side. I'm looking for a solution to process the images and export them so that they fit together.*

\[EDIT:\] Here's one of the tiles for reference. It tiles along the bottom of a block of stone.

And here's a 9-slice thumbnail of an early stage of the tileset:

\[Edit again:\] To be clear, it's not the big-ish things (stone sides, grass, etc.) connecting that's my problem. My artist already measures everything to make it match up. It's the variations in shading and impreciseness of the physical medium that's the problem.

# Answer
Here's one method that works well:

(Though I've done a bit of a quick & sloppy job of it here. Original rock texture from this site)

1. Duplicate your 9-slice and offset it by one tile width (so the seam between the left & center tiles now sits over the seam between the center & right, or vice versa)
2. Trim this duplicated layer to a narrow strip, making sure it completely covers the seam line. You want to keep as much of the underlying tile visible as you can, to reduce repetition.
3. Blend this strip into the background tile, either by feathering out its transparency, or painting/cloning *behind it* so that you keep the copied strip's pixels unchanged in the immediate viciinity of the seam.
4. Now the immediate neighbourhood of the seam is identical, whether you're laying a left tile beside a center, a center beside a right, or a left beside a right - they all flow together correctly.

5. Repeat by copying one of the horizontal seams over the other and blending accordingly.
> 5 votes

# Answer
Sorry, I may have this wrong. Am I correct in believing that you want your textures to be seamless. So if you have 2 of them side by side they match up without you being able to clearly see the edge.

Here is a zoomed up image:

Usually you want to create these hand drawn pictures and try to make them seamless. So basically if a line is going from the left, it must end in the same location at the right. Here's an example:

The line begins at the left, it goes swirly, then ends in the same location at the right. This is the same for lines going from the top to bottom and bottom to top. Using that image I can do this:

The lines don't match up exactly but that's just because I've done it very crudely and quickly.
> 0 votes

---
Tags: graphics, tilemap, art
---


# Question
Title: This if statement doesn't end once triggered by touch
I have an if statement that successfully recognizes a touch, but continues executing after the touch has ended.

```
void Update() {

    float currentstep = speed * Time.deltaTime;
    Vector3 newDirection = Vector3.RotateTowards(transform.forward, head.Gaze.direction, currentstep, 0.0F);

    foreach (Touch touch in Input.touches) {
        if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
            fingerCount++;
    }

    if (fingerCount > 0){
        transform.rotation = Quaternion.LookRotation(newDirection);
        transform.position += sub_speed * head.Gaze.direction;
        Debug.Log (fingerCount);
    }
}

```

I want the transforms to stop executing once the touch has ended. I'd expect Update to catch that for me. Why isn't it?

# Answer
You could simplify things by using GetMouseButton, like this:

```
if (Input.GetMouseButton(0)){
        transform.rotation = Quaternion.LookRotation(newDirection);
        transform.position += sub_speed * head.Gaze.direction;
        Debug.Log (fingerCount);

```

This will work on touch devices, and execute the if statement while touch is held down.
> 0 votes

---
Tags: unity
---


title: Game Maker Studio Not Drawing Variable?

text:
# Question
Title: Game Maker Studio Not Drawing Variable?
```
///Draws
draw_set_color(c_red);
draw_text(view_xview + 128, view_yview + 128, string(global.fuel));

```

Why isn't it drawing my variable?

# Answer
> 0 votes
Firstly, always use view's index:

```
draw_text(view_xview[0] + 128, view_yview[0] + 128, string(global.fuel));

```

Next, what you need check:

1. Current alpha (`draw_set_alha(1);` before draw)
2. Current blend mode (`draw_set_blend_mode(bm_normal)`)
3. Depth of the object. Maybe you drew behind other objects. Draw order is from biggest value to lower value. If two objects has same depth (and they overlaps) you need set different depth.
4. Used font includes needed chars (and you set it using`draw_set_font(...)`)
5. Used correct alignment (`draw_set_halign(...)` and `draw_set_valign(...)`)
6. Object exists. Maybe you didn't create it. Or maybe you deactivated it. Or maybe you deleted it.

---
Tags: game-maker
---


# Question
Title: Generate Geodesic Sphere from Hex and Pentagons
I have two polygonal meshes, a hexagon and a pentagon (They are tiles in a strategy game). I want to use them to construct a geodesic sphere (https://upload.wikimedia.org/wikipedia/commons/e/e7/G%C3%A9ode\_V\_3\_1\_duale.gif).

I can modify the sizes of each mesh to fit what I need, but **I can't figure out how to get the radial coordinates of each face in the geodesic sphere. Is there a way to do this?**

I'd like to only need two meshes for the tiles, but I can make different versions if absolutely necessary.

# Answer
The typical way is to map a triangular grid of the desired density over the faces of a Platonic solid (specifically an icosahedron if you want to use hexagons and pentagons). I describe mapping triangular grids onto icosahedra in this answer, and you can find more details here. This method lets you change the number and arrangement of tiles very flexibly, so you can make any of the three classes of geodesic:

Next, you project each vertex of the mapped grid onto an enclosing sphere. There are many ways to do this...

* Gnomonic Projection is the easiest - just normalize the vector to get its projection onto the unit sphere. This leads to significant distortion however - hexagon tiles near the middle of each icosahedral face will be much larger than those near the pentagons at the corners.
* Recursive subdivision is probably the most popular. Starting with one triangular face of the icosahedron, find the midpoint of each edge and project it gnomonically onto the sphere. Join these new points to split the original triangle into four smaller triangles. Now you can repeat the process on each of those four until you reach your desired density. This does a better job of spreading out the distortion than pure gnomonic, but there are only certain geodesic breakdowns it can achieve (most easily: Class-I with frequencies that are a power of two)
* Snyder's equal-area projection, or similar projections, are common in geographic information systems. They reduce the distortion while still giving you flexibility to use any class of geodesic, but they tend to be complex to implement or, as in the link above, described in academic papers locked behind a paywall.
* Buckminster Fuller developed a projection for his Dymaxion Map that also reduces distortion, but while it's easy to find a description of the method, equations to execute it also tend to sit behind a paywall.

Here's a good resource for these and other projection methods.

Once you have your points projected onto the sphere, each one becomes the center and normal for a face (this is performing the dual operation to get a Goldberg polyhedron). You can get the vertices of these faces by taking the three faces that surround each vertex and intersecting the planes defined by their positions/normals.
> 3 votes

# Answer
The way I would do that is to create an icosahedron and then divide the edges in steps until you have a geodesic:

1. Create an icosahedron with a 1 unit radius (we can scale the whole thing later). You'll have one vertex at the zenith of your sphere and one at the nadir. Then 5 vertices evenly spaced at 30°N latitude and again at 30°S latitude, so basically every 72° of longitude. The ones at 30°N will be halfway between the ones at 30°S latitude. That gives you your 12 vertices of an icosahedron.
2. Divide the edges into thirds. For every pair of vertices that share an edge, create two new vertices that break the edge into thirds. What will happen when you do that is that you will now have four vertices per edge, *but they will all lie in a straight line*. Its not really a geodesic at this point so you need to adjust those vertices so that they lie on the surface of that sphere, so assume each vertex is a vector and divide that vector by it's own length. That essentially normalizes it and places it at one unit from the center again.
3. You now have enough vertices to make a geodesic out of triangles. But it looks like you want smaller triangles. So divide all those edges again the same way. Don't forget to divide the new edges as well. It's easiest if you divide the edges into halves this time so that you can systematically create triangles. repeat as necessary until you have as many divisions as you like. Again, you'll need to normalize all those new vertices so they fit onto the outside of a sphere again at one unit distance from its centroid.
4. Once you are done dividing to the size you like you can use the triangles in sets of six to make hexagons and in exactly twelve spots (your vertices from step 1) there will only be five adjacent triangles from which you make your pentagons. You'll have to distort your hexagons slightly to fit them into these *non-equilateral* hexagons. Your pentagons will be fine.
> 2 votes

---
Tags: mathematics, algorithm, geometry
---


# Question
Title: how to transform the position of an object
I am trying to transform the position of an object. I have totally 3 Objects and 2 triggers, objects are 1. Left\_Wall, 2. Right\_Wall, 3. Obstacles. 1st trigger for transform the position of an objects y = -50, 2nd trigger for transform the position of an objects y = -7. Left wall and Right Wall are placed inside the environment. the environment will instantiate automatically for looping. if the player crossed the first environment previous environment will delete automatically. at that time in second clone environment if the player triggered means it will display a message as

> MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

In first Clone environment its working perfectly. second clone environment its not working.

# Answer
> 2 votes
Please please please use *Code Blocks* to paste your code instead of screenshots.

Now you say that

> the environment will instantiate automatically for looping

And your variables *sideLft* and *sideRit* are null when you need them. So why not perform the search of the scene just before you do your action? Take your code from *Start* function and move it in the beginning your *OnTriggerEnter*. I would provide a code block for you if I could copy some from your question.

---
Tags: unity, monodevelop
---


title: Speeding up point-in-polygon for Python

text:
# Question
Title: Speeding up point-in-polygon for Python
In researching collision detection methods for non-Rect-like objects I came across point-in-polygon -- specifically, the even-odd rule.

The one presently on Wikipedia claims it is written in Python, but it is a little bit pedantic:

```
# x, y -- x and y coordinates of point
# a list of tuples [(x, y), (x, y), ...]
def isPointInPath(x, y, poly):
    num = len(poly)
    i = 0
    j = num - 1
    c = False
    for i in range(num):
            if  ((poly[i][1] > y) != (poly[j][1] > y)) and \
                    (x < (poly[j][0] - poly[i][0]) * (y - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]):
                c = not c
            j = i
    return c

```

This didn't particularly remind me of Python, so I spent my lunch break working on this. I don't consider myself a master chef optimizer, but I came up with something slightly more attractive:

```
def fast_pt_in(pt, poly):
    testX, testY = pt
    last = -1
    answer = False
    for now in xrange(0, len(poly)):
        nowX, nowY = poly[now]
        lastX, lastY = poly[last]
        if (nowY > testY) != (lastY > testY) and (testX < (lastX - nowX) * (testY - nowY)/(lastY - nowY) + nowX):
            answer = not answer
        last += 1
    return answer

```

A couple of `cProfile` tests reveal mine to be faster - both when returning True and False - when done 2\**16 times (I figure… 60 FPS, 20 minutes of gameplay, assuming it's brute forcing the collisions without other things to prevent overchecking of course).

In the example below the 'old version' is `pt_in` and the new version is `fast_pt_in`. `cProfile` is executing the following:

```
cProfile.run("shp = [(x, y) for x in (10, 30) for y in (10, 30)]; [func(point, shape) for x in range(0, 2**16)]")

```

where `func` is either function, and `point` is either one inside the shape (15,15) or outside(5, 5).

```
Stick$ python pt_in.py

---TRUE hit in Rect---
=== fast_pt_in ===
         131075 function calls in 0.211 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.021    0.021    0.211    0.211 <string>:1(<module>)
    65536    0.184    0.000    0.188    0.000 pt_in.py:64(fast_pt_in)
    65536    0.004    0.000    0.004    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.001    0.001    0.001    0.001 {range}

=== pt_in ===
         196611 function calls in 0.312 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.021    0.021    0.312    0.312 <string>:1(<module>)
    65536    0.266    0.000    0.291    0.000 pt_in.py:1(pt_in)
    65536    0.005    0.000    0.005    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    65537    0.021    0.000    0.021    0.000 {range}

---FALSE hit in Rect---
=== pt_in ===
         196611 function calls in 0.173 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.021    0.021    0.173    0.173 <string>:1(<module>)
    65536    0.126    0.000    0.152    0.000 pt_in.py:1(pt_in)
    65536    0.005    0.000    0.005    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    65537    0.021    0.000    0.021    0.000 {range}

=== fast_pt_in ===
         131075 function calls in 0.145 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.021    0.021    0.145    0.145 <string>:1(<module>)
    65536    0.119    0.000    0.123    0.000 pt_in.py:64(fast_pt_in)
    65536    0.004    0.000    0.004    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {range}

```

And that's just with Rect-like shapes; as the number of points in the polygon increases, mine eeks out further and further ahead.

This is all well and good, but I want to make sure I'm getting a lot out of this one. Are there any further changes I can make to this (apart from refactoring it into C, lulz) to eek a little more out of it? I believe I am assigning variables as efficiently as possible to get repeated lookup out of the loop unlike the original, but apart from that I am uncertain if there are other reasonable changes to make.

**EDIT**: The use of `xrange` prompts me to clarify - I'm using Python 2.7.

Bonus question -- I'm right, right; that Wiki example is super-unpythonic. Should I replace it? :/

# Answer
Before testing for performance, test for correctness. The way you have defined your shape in the test results in wrong answers:

```
shp = [(x, y) for x in (10, 30) for y in (10, 30)]

```

This results in the following shape:

```
[(10, 10), (10, 30), (30, 10), (30, 30)]

```

If you plot this, you will notice it looks like this:

```
(10, 30)  (30, 30)
      B----D
      |    |
      A----C
(10, 10)  (30, 10)

```

The polygon `A-B-C-D` is not a convex polygon. What you want instead is `A-B-D-C`:

```
shape = [(10, 10), (10, 30), (30, 30), (30, 10)]

```

Now we have a shape that is a convex polygon, and we can use your two points for verification:

```
inside = (15, 15)
outside = (5, 5)

```

To make it easier to compare both functions, I've changed the signature of `isPointInPath` to be the same as `fast_pt_in` and just unpack `pt` to `x` and `y` in the first line (the rest of the code is the same):

```
def isPointInPath(pt, poly):
    x, y = pt
    # ... rest of the code ...

```

And because we can possibly have multiple candidates, let's define a global list of functions that we test:

```
candidates = [isPointInPath, fast_pt_in]

```

Now, we can use nosetests to write a unit test. What we want to check is that the function returns `True` when given `inside` and `shape` as parameters and `False` when given `outside` and `shape` as parameters (read up on test generators in the nose docs to find out how this test works):

```
def test_correctness():
    def test_call(func, point, shape, result):
        assert func(point, shape) == result

    for func in candidates:
        yield test_call, func, inside, shape, True
        yield test_call, func, outside, shape, False

```

Assuming we have both functions, and those variables (`shape`, `inside`, `outside`, `candidates`) in a file `point_in_poly.py`, then we can run it with nosetests (use `pip install nose` to install nose if you don't have it yet):

```
% python -m nose point_in_poly.py -v
point_in_poly.test_correctness(<function isPointInPath at 0x10a2aaaa0>, (15, 15), [(10, 10), (10, 30), (30, 30), (30, 10)], True) ... ok
point_in_poly.test_correctness(<function isPointInPath at 0x10a2aaaa0>, (5, 5), [(10, 10), (10, 30), (30, 30), (30, 10)], False) ... ok
point_in_poly.test_correctness(<function fast_pt_in at 0x10ac272a8>, (15, 15), [(10, 10), (10, 30), (30, 30), (30, 10)], True) ... ok
point_in_poly.test_correctness(<function fast_pt_in at 0x10ac272a8>, (5, 5), [(10, 10), (10, 30), (30, 30), (30, 10)], False) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

```

Ok, so now we can be sure the functions actually return a correct result for these test cases (if you set `shape` to your original definition, you see it failing).

Let's get to the performance test. For that, you don't need to use profile, Python provides a nice tool called timeit. At the end of the file add the following:

```
if __name__ == '__main__':
    import timeit
    for func in candidates:
        duration = timeit.timeit('%s(%r, %r); %s(%r, %r)' % (func.__name__, inside, shape,
                                                             func.__name__, outside, shape),
                                 setup='from %s import %s' % (__name__, func.__name__))
        print '%-30s: %.5fs' % (func.__name__, duration)

```

What this does is for each candidate function it calls the function with a point inside and one outside and run this 1000000 times and returns the number of seconds passed, then running it results in:

```
% python point_in_poly.py
isPointInPath                 : 3.21318s
fast_pt_in                    : 2.50431s

```

So yeah, `fast_pt_in` is a bit faster. Now, for the question about increasing performance: You can avoid having to use range together and just remember the last point, then you don't need to index into `poly` at all:

```
def faster_pt_in(pt, poly):
    testX, testY = pt
    last = poly[-1]
    answer = False
    for now in poly:
        nowX, nowY = now
        lastX, lastY = last
        if (nowY > testY) != (lastY > testY) and (testX < (lastX - nowX) * (testY - nowY)/(lastY - nowY) + nowX):
            answer = not answer
        last = now
    return answer

```

Add this to `candidates` like so:

```
candidates = [isPointInPath, fast_pt_in, faster_pt_in]

```

Use nosetests to see if it still gives the right results (it does) and then run the performance check:

```
% python point_in_poly.py
isPointInPath                 : 3.22605s
fast_pt_in                    : 2.42880s
faster_pt_in                  : 1.72670s

```

Now of course there might be other improvements, but with this framework you should now be able to easily add new variants, see if they still do the right thing, and then compare their performance.
> 2 votes

---
Tags: collision-detection, python, optimization
---


title: Internal Game Economy

text:
# Question
Title: Internal Game Economy
I need to set up a monetary system for my game however I am unsure how to craft an internal economy for that money. I want to make an rpg with a economy system that keeps the player for a time from just selling numerous of the same item to grind for money. So when the player sells to much of a certain item the buy price for that item will go down temporarily. Also, I would like to add a system where certain items go up in terms of what they can be sold for temporarily as well.

For example, in "Story of Seasons" I can sell items to vendors in order to get money, however if I sell to much of that type of item the price I get for it goes down. Also, there is a system where for a certain vendor or more the price I can get for the items actually increases.

# Answer
Well why not model your economy system after a real economy? Maybe have a `supply` variable that for each item in circulation (i.e. if you sell ten bushels of wheat to one vendor, 17 to another, and 2 to a third, then this `supply` variable for the wheat is `29`) and have another variable, `demand`, that fluctuates based on some sense of demand that your citizens in your game have (i.e. if there is a famine occurring, the demand for your wheat rises). Then, use some simple formula to determine the appropriate price for your item based on its current `supply` and `demand` values. This would prevent a player from simply selling all his wheat in one sitting because the `supply` variable's value would increase while the `demand` value would remain relatively the same since (I would assume) demand would not be that volatile.

Also, as for your "different prices to different vendors" comment, maybe you could make the previously mentioned `supply` and `demand` variables vary according to geographic location, that way it takes into account the situations of that area (like if only one city was experiencing famine). You could then keep the same formula for determining pricing as earlier since now the both variable values change according to the location. You could also have specialist vendors that simply pay more or less.

Overall, this is a system I've seen several times now and it does work pretty well as far as I've seen. I'll leave the actual programming up to you. Good luck!
> 4 votes

# Answer
Since the player regulates supply through their actions you are responsible for handling how demand is calculated.

Lets start with a simple model. Consider the function f(x) = 1/x where x is number of an item the player has sold to this specific vendor and x \>= 1 (avoid division by zero). We can use this function to modify the price a vendor pays the player, c, for a given item. The result is c' = c * f(x) = c * 1/x.

Now lets make our model a bit more realistic. Now suppose that we want the price the vendor pays to increase the longer it has been since a player sold them that item. Let t be an arbitrary amount of time, we can then use the function g(t) = t. Now we have c' = c * f(x - g(t)) = c * 1 / (x - g(t)) = x * 1 / (x - t).

This is still a very basic model, lets make it a bit more interesting. Now suppose that g(t) = sin(t). By using a periodic function we can model supply and demand over say seasons or even the course of a day or week. These models can be applied locally and regionally as well to increase immersion and the intricacies of your worlds economy.

The point of all this is you have free reign and a lot of very cool ways to add depth to your games world through economy.
> 0 votes

---
Tags: rpg, economy
---


# Question
Title: How to make my components only contain raw data?
I'm reading that Components in ECS are just only data and have no logic. I'm trying to follow this and I got that working:

```
class Sprite : public Component
{
public:
    Sprite(const std::string &textureid = "");

    std::string getTextureId() const;
    void setTextureId(const std::string& textureid);

    void setColor(const Color& color);
    Color getColor() const;
private:
    std::string m_textureid;
    Color m_color;
};

```

Now in my SpriteRenderingSystem I have to create every frame for every Entity that has a Sprite component a SFML Sprite object (I'm using it right now), set the parameters of that object, render it and destroy it. I know it's not optimized and I don't like it.

I think that I can use my component to hold a pointer to the SFML::Sprite object and then I only have to render it every frame without having to create/set/render/destroy it as you can see there:

```
class Sprite : public Component
{
public:
    Sprite(const std::string &textureid = "");

    std::string getTextureId() const;
    void setTextureId(const std::string& textureid);

    void setColor(const Color& color);
    Color getColor() const;

private:
    friend class ::SpriteRenderSystem;
    std::shared_ptr<sf::Sprite> m_sfspr;
    std::string m_textureid;
};

```

Am I breaking the "only data in a component" rule here? If so, what other alternatives are there?

# Answer
The way to make your components "only contain raw data" is to *write them* so they "only contain raw data."

What specifically "only contains raw data" means is up to you; there are several ways you could interpret it, and whether or not those ways make sense depends on the implementation you're building.

The two most common interpretations of "only containing raw data" I've seen are as follows:

* The component is literally a POD/standard layout/trivial structure. This distinction is important when your implementation will make use of copying via `memcpy` to move component data around and doesn't want to deal with the potential overhead of copy constructors, non-standard-layout bits in the data (such as the virtual function table pointer), complex ownership, or any of the other things you don't have to deal with if your types conform to one of those three concepts.
* The component has no non-trivial behavior, it just consists of fields of data and possibly some trivial bits of utility behavior (functions to access the data or mutate it in a simple form while maintaining invariants). This distinction tends to be important if your implementation is focused on centralizing complex logical behavior outside of the components themselves (typically within "systems"), either for maintainability or to allow that behavior to exist as a synthesis of data from multiple, possibly-heterogeneous sets of components per entity.

(There are of course other ways to interpret the phrase, but these are the two most common in my experience.)

Both sprite implementations you posted "only contains raw data" in the second sense. There's absolutely nothing wrong with this, and no need for you to fervently excise all member functions or non-POD fields from your component types if this approach is working for you. If the second one is more straightforward or more optimal (as it sounds, from your description), then use it. It's fine.

Don't let dogmatic purism get in the way of actually making your game work and work well.
> 2 votes

---
Tags: c++, entity-system, component-based, entity-component, game-component
---


# Question
Title: Libgdx change to other screen and dispose current one
I am trying to switch to a GameScreen when the LinearVelocity of a Box2D - Object is x = 0. If it is so, I am using the setScreen() - Method by calling the main class. This works perfekt, but when the screen should change, it just flickers, which is most likely caused by the render() - method in the screen class. So my question is now, how to dipose that render method or how to dispose the whole screen class, so that I only the new screen appears! Thanks

# Answer
> 1 votes
The **libGDX** `Game` class delegates to a single `Screen` so if your game is flickering between the new `Screen` and the old `Screen` after you call `Game.setScreen` it is likely because the new `Screen` sets the old screen back.

# Answer
> 1 votes
I found the solution.

The problem was, that the new Screen was actually empty resulting in an emtpy render - method aswell.

---
Tags: libgdx, rendering, box2d, screen
---


# Question
Title: Unity Application.LoadLevel freezes the game on Android device
I'm developing a game using Unity. The game has a single level and after the player wins/loses, I simply want to reload the same scene. Here's the code I'm using:

```
private void OnLevelFailed()
{
    IsGameStarted = false;
    Debug.Log("LEVEL FAILED");
    Invoke("RestartLevel",5);
}

void RestartLevel()
{
    Application.LoadLevel(Application.loadedLevelName);
}

```

When running this code on the editor, everything seems fine and the scene reloads as intended. However, when I build the game for Android and run it on a device (an LG G3), the game simply freezes. I used adb logcat to see the logs of any exceptions or errors if there were any but to no luck. I also suspected if the Invoke call was causing the problem and replaced it with simply the method call, but that didn't solve the problem either.

Anyone have any idea why this might happen?

# Answer
This **is** the expected behaviour of LoadLevel. If you don't want your game to freeze while loading scene, try LoadLevelAsync or LoadLevelAdditive.
> 1 votes

# Answer
This issue may be caused by other problems also.

1. Try loading the scene with this code:

```
 Application.LoadLevel(Application.loadedLevel);

```

sometimes the loaded level name gives problems if the build is a split binary.
2. Make sure your adb log cat limit is set to over 100k *(My mobile OS shoots lot of internal logs due to which unity logs just disappear form the list)*
3. Make sure you include the scene in your build.
4. If nothing works then duplicate the scene in the asset folder and try to load the duplicate scene, and check if it gives any error.
> 0 votes

# Answer
I don't know if you're still interested but I came across the same issue and solved doing a workaround.

Make a new scene, you're going to use it to load other scenes so a name of LoadingScene could do.

Inside this scene put an empty game object and attach to it a script that uses `Application.LoadLevel();` inside its `Awake()` method, or `Start()` if you prefer.

Here is an example:

```
using UnityEngine;
using System.Collections;

public class LoaderOfScenes : MonoBehaviour {

  // Use this for initialization
  void Awake () {

    //Just load something and catch the null exception with a default scene.
    Application.LoadLevel(References.SceneToLoad == null ?
      "ProtoMenu" :
      References.SceneToLoad);
  }

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

  }
}

```

The catch is `References.SceneToLoad`.

It's just a static string cached inside a public static class you make.

Whenever you need to load a scene, instead of using `Application.LoadLevel();` and passing as parameter the name of the scene you want to load, you assign that value to `References.SceneToLoad` and then load the scene that loads scenes instead.

I tried this with my builds and worked.

I don't know why.
> 0 votes

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


# Question
Title: Ideal draw order - sort primarily by distance or material?
When it comes to pre-sorting the draw calls for a given frame, I am aware of two different methods for optimising.

The first is to batch draw calls by their material. This minimises shader changes and limits the number of times constant buffers, textures, and other data need to be switched or updated also. Furthermore, this approach leads to easy multithreaded commandlist generation (important in the coming era of DX12 and Vulkan!), each thread can build a list of draw calls for each material independently.

However, one major source of framerate slowdown is 'overdraw'- i.e. drawing partially or fully obscured geometry BEFORE drawing the geometry that obscures it. When drawing roughly front-to-back the fragment shader has to do far less work because obscured pixels can be depth culled.

However, in order to sort geometry front-to-back, it is not really possible or practical to also try and sort draw calls by material (or is it?). Therefore, I ask, which of the two approaches is the 'better' (in terms of performance or general adoption); or is there a third or hybrid approach I am unaware of?

# Answer
**For a single pass approach:** Obviously if you don't have the front-to-back requirement (early Z), you can primarily sort on material. But yes, you're going to have to decide which is primary and which is secondary.

For mobile, reducing overdraw is top priority. If desktop / console, I wouldn't be worrying much about that, I'd opt to sort by material primarily as overdraw has to be carelessly high to impact perf.

Bear in mind though that there is another aspect to this even if you don't worry about sorting front-to-back to reduce overdraw, and that is back-to-front sorting for realistic transparency. If you have this requirement, you're still stuck doing a secondary sort on material. If neither this nor front-to-back, you're golden and can do material as primary sort.

P.S. Have you looked into occlusion queries? They might help, depending on your GL version.

**For multi-pass:** see DMGregory's wisdom in comments.
> 2 votes

---
Tags: architecture, performance, depth
---


# Question
Title: How can I randomly generate achievements?
Novice programmer here. To challenge my self i want to create an achievement system that randomly generates achievements for me based on a set of trackable metrics within my game.

To keep it as abstract as possible my game is a turn based highscore chaser. Each game has 13 turns. Each turn consists of placing 4 tiles, each tile can have an individual score which together form the turn score. There are 5 different tile types that can be individually combined to raise each tile's score differently. Each turn one of the 5 tiles gets a bonus making it worth double points. Also in each turn you can form "hands" similar to poker where for example two tiles of the same type next to each other are a pair, which nets a hand bonus for individual turns.

Here's what my generated achievements should look like:

Get a turn score of 15 and create a pair using tile type x.
Create a tile type y that has 5 points.
Create 5 hands of type x and use tile type x or y.
Get a total score of 50 without creating more than 3 hands of type x.

Obviously this seems kind of complicated and i'm kind of asking myself how to create such "complex" achievements. Seems like i need to establish some kind of syntax that i can feed the system to produce these kinds of requirements. But i'm kind of stuck since i couldn't find any info on this issue yet.

Maybe you have done something similar?

# Answer
> 2 votes
I'd solve this by breaking down an achievement into constitute parts and then randomly selecting values from pools for each part. Based on your examples, you have an achievement grammar that looks like

```
achievement = <verb> <instance count> <metric> <value count> [and <achievement>...]

```

that is, an achievement is a basically a verb associated with a metric which may be joined via 'and' with another achievement up to some arbitrary number of times you'll get to decide (probably no more than twice?)

You'd then define the valid values for each aspect of the grammar. For example, you've already got some metrics:

* turn score
* tile type value
* hand type
* use of tile type

And some verb types (plus a few extra I've made up that might work):

* create
* acquire ("get")
* use (play, as in play a hand)
* last (as in, "last for X turns")

The instance and value counts are just numbers, so you can pick ranges for them that seem appropriate ("5" hands seems reasonable, "0" hands does not, for example).

Whether or not you stick two conditions together with an "and" can just be a fixed percent chance that you deem appropriate. At this point generating a random achievement is simply a process of generating a random value for each component of the grammar.

You'll probably want to introduce some data dependence between the various components. For example, the valid range of values for instance counts might depend on the metric that was randomly selected, because a range of one to five might work for "hands" but may be too small to be a challenge for "score," for example. Similarly you may want to prevent certain verbs being generated with certain metrics because they may be nonsensical for the rest of your game.

# Answer
> 0 votes
Make a base for the types of achievments, like you started. Example in a Hack'n Slash game: Slay X enemies Survive X seconds Block X hits

And so on. Then you need to setup a few metrics. I can't use the same Block metric for the Survive, because Survive 10 seconds is far easier than Blocking 10 times. So, your best bet is to make a multiplier to the random number you got. Slay (rnd() * 50 + 10) enemies Survive (rnd() * 30 + 15) seconds Block(rnd() * 10 + 2) hits

The plus part represents the minimum, and the multiplier the max without the min. So the Slay means that the minimum is 10 up to 60(50+10) enemies.

---
Tags: procedural-generation, achievements
---


# Question
Title: How to Implement a Timer for my Prefab for Roll-a-Ball Game (C# in Unity)
I am trying to create a public float timer that senses when the particular prefab has not been there for a certain amount of time. Then, it will replace that particular object.

The goal is to randomly spawn 10 of these cubes across the game board. Then when the player picks one up, it disappears. Then after say, 2 seconds, a new cube should be placed on the board.

Right now the Player already moves around the board just fine, and can pick up the cubes. When the player picks up a Cube, a new cube is automatically placed on the board with no delay.

This script will be attached to the cube prefab directly.

Apologies for the appearance of the code in advance.

```
using UnityEngine;
using System.Collections;

public class RandomPlacement : MonoBehaviour
{
public GameObject prefab;
private GameObject prefabClone;
public int count;
private GameObject[] getCount;
public float timer = 2;
// Instantiate the Prefab somewhere between - 10, 10 on the x, and z planes, with a height of 0.5 in y.

void Update ()
{
   getCount = GameObject.FindGameObjectsWithTag("PickUp");
   count = getCount.Length;
   if (count < 10)
   {
        timer -= Time.deltaTime;
        if (timer <= 0f);
        {
            Vector3 position = new Vector3(Random.Range(-9.0f, 9.0f), 1.0f, Random.Range(-10.0f, 9.0f));
            prefabClone = Instantiate(prefab, position, Quaternion.identity) as GameObject;
            timer = 2;
        }
    }
}
}

```

The code for the collision between the pick-up and ball is given by:

```
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("PickUp"))
    {
        other.gameObject.SetActive(false);
    }
}

```

}

The "Cube" prefabs are all given the tag "PickUp" This script is attached to the "Player"

# Answer
> 1 votes
I don't know what is your optimization logic is here, but below is the limited optimized and required code for you according to code you did provide.

```
void Update()
{

}

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("PickUp"))
    {
        other.gameObject.SetActive(false);// other.gameObject should destroy here by the way.
        getCount = GameObject.FindGameObjectsWithTag("PickUp");
        count = getCount.Length;
   if (count < 10)
   {
         Invoke("SpawnObject",2.0f);
   }
}
}

void SpawnObject()
{
    Vector3 position = new Vector3(Random.Range(-9.0f, 9.0f), 1.0f,        Random.Range(-10.0f, 9.0f));
    prefabClone = Instantiate(prefab, position, Quaternion.identity) as GameObject;
    prefabClone.tag = "PickUp";
}

```

---
Tags: unity, c#, game-mechanics, game-loop
---


# Question
Title: Cost of Using Virtual Methods to Query Properties?
Let's say *you're* making a tile-based roll-playing game, and *you're* **obsessed** with OOP.

You have an abstract base class `Tile` which will be inherited from by **many** derived classes, like `Grass` `Sand` and `Water`

The base class declares virtual methods for querying properties of derived classes, such as `isCollidable()` and `isFlammable()`

```
class Tile{
public:
 virtual constexpr bool isCollidable() = 0;
 virtual constexpr bool isFlammable() = 0;
};

class Grass:
public Tile{
public:
 constexpr bool isCollidable(){
  return false;
 }
 constexpr bool isFlammable(){
  return true;
 }
};

class Sand:
public Tile{
public:
 constexpr bool isCollidable(){
  return false;
 }
 constexpr bool isFlammable(){
  return false;
 }
};

class Water:
public Tile{
public:
 constexpr bool isCollidable(){
  return true;
 }
 constexpr bool isFlammable(){
  return false;
 }
};

```

When you want a new type of `Tile` you just create a new class, inherit from it, and implement it's virtual methods. Adversely, when you want a new property, you've to add `is` methods to all the classes.

My question is, what is the cost of using polymorphism in this way? Is this an inappropriate use of polymorphism? If so, What are some alternatives to this while maintaining nice, pretty OOP?

# Answer
No.

Grass, Sand and Water aren't different TYPES of tiles, they are different tiles.

i.e.

```
class Tile
{
private:
  Sprite sprite;
  bool collidable;
  bool flamable;
  bool walkable;
public:

 Tile(Sprite s, bool col, bool flam, bool walk)
 {
   this.sprite = s;
   this.collidable = col;
   this.flamable = flam;
   this.walkable = walk;
 }

 bool isCollidable()
 {
   return this.collidable;
 }

 bool isFlamable()
 {
   return this.flamable;
 }

 bool isWalkable()
 {
   return this.walkable;
 }
}

grass = Tile(Sprite(...),false,true,true);
sand = Tile(Sprite(...),false,true,true);
water = Tile(Sprite(...),false,false,false);

```

In general you only want to derive a class if the type adds some functionality. Since all the tiles you describe have the same attributes, they are instances not derived objects. Like a tile that can be walkable sometimes, but not others would be a reason to derive a new class.

I added sprite to represent the things I didn't add to the class, but a tile having a sprite isn't what I'd really do. Intead, Tile would have:

* Static image for tiles the sprite sheet.
* Static constant length and width of a tile.
* tile\_x and tile\_y for where on the sprite sheet to find it
* x and y of where this tile is placed.

Having a "sprite" was just a way in the above example to make all that easier.
> 5 votes

# Answer
> obsessed with OOP

What you've described isn't OOP. It's an abuse of inheritance, which is frequently attributed to OOP, but isn't an inherent part of the paradigm. :)

> My question is, what is the cost of using polymorphism in this way?

Virtual function calls are slower than regular calls, and much slower than directly accessing data members, but are not going to be the bottleneck in your game; I'd be surprised if you could even find any of your `Tile` virtual methods in a profiler.

If the design appropriately calls for virtual methods, don't shy away from them for performance reasons. That said, I don't think your design calls for them.

> Is this an inappropriate use of polymorphism?

It is a misuse of polymorphism and a misuse/misunderstanding of OOP.

> If so, What are some alternatives to this while maintaining nice, pretty OOP?

J. A. Streich's answer already covered a far better approach: data-driven design.

To expand upon his answer, I would say that you should only use a class when you are modeling something different from the computer's perspective. The computer does not care in the least about grass vs dirt vs stone. All it cares about are the operations it can perform with a tile. Since the operations that can be performed on a `Tile` are universal, there should be a single class.

Polymorphism comes into play when the implementation of the operations can vary. Querying a boolean as to whether a tile is flammable is not a different implementation: it's just the querying of a bool for all tile types. Tiles are thus a bad fit for polymorphism.

Good design - even good OOP design! - has a lot fewer uses for polymorphism than you might think. Most of them revolve around high-level abstract concepts; e.g. you might have an abstract `FileSerializer` type with polymorphic implementations `XmlFileSerializer` and `BinaryFileSerializer`. These are cases where the computer must do some low-level operation wildly different ("write XML strings" vs "write raw bytes") for the same high-level operation (e.g. "save player state").

Your types (polymorphic or otherwise) should not be modeling real-world nouns and taxonomies.

A class for an abstract `ActorEntity` is fine, but a class for `ToughGoblin` is absolutely wrong, because the computations for enemies are identical between a tough goblin, a weak goblin, or an ogre; the only differences are the inputs to the calculation (how much damage they deal, which image to draw, etc.).
> 5 votes

---
Tags: c++, oop, polymorphism
---


# Question
Title: how can i make my game more intuitive without a tutorial?
i am currntly working on a mobile game app. the game details a tree with several branches on which diffrent types of birds fly and land on. every bird has a diffrent weight and the purpose of the user is to balance the weight on each side of the tree before the branches break. i attached a screen shot of the game, and i hope someone will have a suggestion on how to make the concept of the game more understandable to users without having to let them do a tutorial. second, what would be your guess about the purpose of the game when you look at the screen shot? and third, i was hoping to add a bending feature to the tree that will enable the user to save the tree by actually moving his phone but it is problematic when the design is made with pixel art - any other thoughts? thank you,

# Answer
A few ideas I had that were too long for just a comment:

1) Maybe have an opening scene before the user enters the first level that displays several birds attempting to sit on one branch and then the branch starts to break and the tree starts to fall so one larger bird flies from the branch to a different branch on the other side of the tree and this everything. Kind of a tutorial but with no text.

2) Definitely have some sort of branch bending animation like I alluded to in point 1. This would allow the user to realize that they're putting too many birds on one branch.

3) Bad sounds. Like creaking of the tree as you put too many birds on one side or the other.

4) To go with sounds, this would be very tough but you could have music that seamlessly gets more faster-paced/scary-sounding as the bird placement gets more precarious.

5) Maybe phone vibration that has increases in intensity as more bad stuff happens.

6) Having a score that increases when the player does something correctly and decreases when they do something wrong is a very common way of telling the user if they're playing correctly.

**Just an idea a friend of mine thought of**: You could include levels where there is wind and the birds become necessary to prevent the tree from falling. Just an idea. Oh! And you could have an animal scare birds like a cat that climbs the tree that throws off the weight so the user needs to re-balance the weight without getting the birds eaten by the cat. Again, though, your game.
> 5 votes

---
Tags: game-design, animation
---


# Question
Title: What makes MMOs with real-money economies legal?
I beieve most MMOs with an in-game currency tied to a real-world currency (e.g. *Guild Wars 2*'s gems or *Eve*'s PLEX) do *not* allow in-game items to be traded back into real cash for a bunch of reasons—partly because they may be subject to changes to the game's "normal" economy but generally because this would open up a bunch of legal issues with money laundering, gaming/gambling laws and so on.

However, *Entropia Universe* (wikipedia link) has an in-game economy which is tied directly to US dollars, allowing players to "cash out" of the game and back into real money. They have even gone so far as to produce bank cards which withdraw from the game and have now formed an actual bank to regulate trades.

Why are there not more games which take this approach of a game economy tied directly to real money?

I understand that the economy needs to be carefully designed and balanced to avoid in-game over-inflation or other exploits leading to in-game currency being "created" from nothing, but the bigger concern seems to me to be the legal issues this would create. Given the amount of random chance involved in the game, is this not effectively gambling? If so, how does *Entropia Universe* allow worldwide users without kicking up a storm of trouble from different regional authorities and governments? Surely this is exactly the kind of thing which is banned in certain US states or other countries. Is it because the game is based in Sweden and their more permissive laws allow it?

# Answer
In my experience, the reason you don't see this very often (at least in the US) is "it's very complicated, we as game developers lack the expertise, and there isn't much profit in it."

Online gambling laws are *really* complicated. I'm not even going to pretend my limited comprehension of legalese is up to the task of parsing them. It's not necessarily very clear how MMO games fit into that law:

> During an interview with Virtual World News, Alex Chapman of the British law firm Campbell Hooper stated: "Now we’ve spoken with the gambling commission, and they’ve said that MMOGs aren’t the reason for the \[Gambling Act 2005\], but they won’t say outright, and we’ve asked directly, that they won’t be covered. You can see how these would be ignored at first, but very soon they could be in trouble. It’s a risk, but a very easy risk to avoid."

But I know of no cases where a game operating in the US (at least) has tried to go up against this law and get it sorted it out in the courts. Consequently, everybody seems to feel like the safer thing to do is simply avoid the possibility by preventing cash-outs and prohibiting secondary markets, rather than deal with having every aspect of the game scrutinized constantly and possibly repeatedly by gambling lawyers.

But the legal specifics are just one aspect of the problem. Another major part of the issue is that when you start allowing cash-outs, you're building more than just a game. You're building a game with a pseudo-bank attached to it.

The logistical implications are many. Primarily though, this means you need to be able to keep sufficient liquidity of assets in order to serve all your potential cash-outs. Game studios aren't really banks (and even then, banks are only required to keep 10% of their outstanding liability in the US at least), so they're not FDIC-insured. If everybody tried to withdraw what they're owed from the game at once, the studio would probably fold unless they kept all of that money readily on-hand. And since nothing like the FDIC backs game studios, most of those players would get nothing.

Even *having* that money is a problem. If a game allowed you to generate real money from in-game currency or items that did not at one point originate from putting real money into the system, you'd have to produce that money from *somewhere* (your profits or savings from elsewhere).

Even if you do restrict the system so at any given point, only cash that has been put in (by somebody) can be taken out (possibly by somebody else), backing 100% of cash-out severely curtails your ability to make any profit off that money... and micro-transactions are an appealing and reliably form of generating profit for a studio. This means the studio can't funnel that profit back to shareholders or employees (in the case of a profit sharing plan).

The studio could invest the funds, certainly, but you wouldn't want it invested into anything high-risk because of the chance of dropping below the balance required to back 100% cash-out. The potential earnings on a very stable investment are much less attractive because of the typical lifetime of a game studio (short), to the point where that investment capital (that money players are putting in to your game) seems like a far better place to take profit from than a piddling amount of interest on said capital.

So games just stay away from it. It's less stressful.

---

As for Entropia Universe in particular, you're right that being based out of Sweden is probably the key factor in allowing it to operate the way it does. Swedish law regarding online gambling appears to be far more amenable to the scenario than US or UK law.
> 33 votes

# Answer
> My question is why are there not more games which take this approach of a game economy tied directly to real money?

I think the answer lies in what a game is. To most people, a game is something where you relax and can have carefree fun.

Some people will have more fun if game money is real money, but others will have less fun. So inherently it seems unlikely that linking game money to real money will make a better or more lucrative game. That doesn't have to be the case - it's sufficient that game developers and publishers think that's the case.

The other issue is risk, complexity, and cost. Linking real money and game money brings much larger risks in regards to legal, public perception, and hacker attacks. It brings legal and technical complexity, especially if you want to operate in more than a single jurisdiction. These create cost, which has to be offset somehow, or it's not worth linking real money and game money.
> 9 votes

# Answer
When you allow players to not just pay you money but also get out money, your game can easily fulfill the definitions of both **banking** and **gambling** which are both heavily regulated in many jurisdictions. While some game companies might feel comfortable with managing a gambling business, very few possess the know-how which is necessary for operating a bank in accordance with all the banking regulations which apply. For details about how far you can go and what you need to do to get a banking and/or gambling license in your jurisdiction, consult a lawyer, not a game developer.

But there is also another problem of a more economical nature: When you allow players to "cash out" at any time, you might end up in a situation where a large number of players cash out at once and the amount of money you need to pay to them is higher than your current liquidity and you won't be able to do so immediately. As soon as there are rumors around that you might not be able to pay out the money you promised, there will be a panic among your players who will then try to secure their money ASAP by also withdrawing it. This might quickly lead to you going bankrupt within just a few days.

And then is the question: Why would you? Many games are very successful with far simpler and far more reliable business models: Players pay for enjoying the game, no refunds unless you have to. Why would you willingly give money back to the players when you can keep it for yourself? Remember the Ferengi Rule of Acquisition number 1:

> Once you have their money, you never give it back.
> 9 votes

# Answer
Note that **Diablo 3** had the real-money auction house. (*before it was removed*)

**How it worked**: Players could purchase in-game digital items from other players using real money. There was a similar, but separate, auction house doing the same thing using in-game gold. The items are sold similar to how many MMOs have some version of an "auction house". A small cut of the action went to Blizzard.

**The auction house was removed from Diablo 3, because it ruined the actual game**. Loot and getting more powerful is the "reward" for playing in that game (*and in many dungeon crawlers.. and in most MMOs to some extent*). Players kept some amount, say the top 5%, of the Loot they collected. The stockpile of Loot grows and grows. Now you suddenly could afford an item which you normally would have taken days, if not weeks, to find. Your character's capabilities jumps immensely, to a level which would take an extremely long amount of time to get higher. As people continued to play, their character's capabilities felt like it was going nowhere, because they almost immediately reached a point where the effort was not worth the reward for them, and they quit playing.

**Why it works for Eve Online**: Eve has a massive amount of destruction happening. Ships, items, and isk(*money*) are destroyed at a rate *nearly* as fast as they are created. Since Eve is *not* a game "all about" items (*It's a stressful game if you try to play that way and aren't good at it*), they can get away with this massive destruction where many MMOs cannot. This helps prevent the incredible amount of inflation and stockpiling which happened to Diablo 3. From my understanding, stockpiling was a worry to Eve online some time ago - players were stockpiling massive amounts of resources in null sec (*player-owned areas, which were supposed to have a lot of pvp*), which is part of the reason they rebalanced the distribution of resources and pushed players to once again engage in more war. I cannot speak for Entropia Universe, but I hope they also have some strategy in place to prevent inflation.

**The problem with "cashing out"**: Outside of actual gambling games(*where everyone puts in "real money" to begin with*), a "cashing out" means that you have generated a bunch of in-game stuff and are giving them to the economy in exchange for something that is not within that economy. Things are going in, nothing is coming out. Most people would probably prefer real money like that - compared to how most games have some "destruction" mechanism whereby you would instead destroy the item for (*possibly*) some other item. "Cashing out" inherently starts generating a stockpile of "good" items that people believe they can get real money for, and few games have the innate amount of destruction involved to help mitigate this innate tendency for the items to be generated or resold more than they are discarded or destroyed.

**The legalities**: I only briefly scanned through it, but you may be interested in reading the old Terms of Service for the Diablo 3 auction house.

You were really buying or selling "Loot Licenses" in Diablo (*"Loot" is a legal term according to the TOS*). Agreeing to the TOS means you accept that all "Loot" is still owned by Blizzard. Blizzard is a big company, and presumably had a lot of legal people working out the kinks to make it available to as many countries as possible, but still could not make the auction house available to *every* country - as said by some of the legalese. They did manage to be available in most consumer countries though.
> 5 votes

# Answer
When the game currency is nonconvertible, the company can freely give it away. If "game$ 1" costs US$ 1 and a in-game competition gives a player game$ 100, that player will think "Wow, I just earned US$ 100", even if they cannot actually get the money out of the system.

Of course, the game money shouldn't be TOO freely given away or nobody spend real money for it.

And they can do deals like "TODAY ONLY: Get game$ 200 for only US $100! That is one hundred FREE game$!!!" without thinking too hard about it.

Still, this gives the impression of a game company that is gladly giving gifts to its players. Getting gifts makes players happy and makes them come back.
> 1 votes

# Answer
With regards to this sub-question:

> My question is why are there not more games which take this approach of a game economy tied directly to real money?

An aspect that not many people have covered is the psychological barrier of an intermediate currency that in-game scrips provide. Spending gems or credits or gold doubloons is an artificial action, in game a player can justify spending 30 gems on an item and be convinced of its fictionness.

Whereas, to get more gems they can either earn them in-game or buy them in bulk as a shortcut. They aren't buying the item, they are buying some gems instead.

As the linked article states all up this buy making it

> difficult to assess the value of unfamiliar items, so the price obscuring makes it easy to forget how much "actual" money they've spent.

So why don't MMO games use real currency - because its bad business.
> 0 votes

# Answer
Seeing as how fantasy football is still considered a skill game (not gambling) and as such allowed to reign free and seeing as how it is by many orders of magnitude more popular than MMOs, I don't think the reason MMOs don't allow cashing out in game currency for real cash has anything to do gambling laws.

There are essentially two reasons that I believe you don't see this.

1. There is nothing in it for them. The game creators can make as much in game cash as they want. Why would they want to promise to exchange in game currency for real money?
2. Even if you assume away #1 (or allow in game currency transactions on ebay, etc), there's a perception that it can only hurt the game. Instead of playing the game to have fun, you'd have a cottage industry of people "playing" the game as a job. These people would probably not be players themselves but would operate out of places with low wages and have people on accounts 24x7 taking up more in game resources and actual server resources. This would/could crowd out players that don't play as often and ruin (or at least hurt) the game for casual and even serious players.
> -2 votes

---
Tags: mmo, legal, monetization, economy, real-money-transactions
---


title: Randomize sound in Unity 5

text:
# Question
Title: Randomize sound in Unity 5
When I start my game, public AudioSource does not load sound but play a sound. My code does not have any error.

```
using UnityEngine;
using System.Collections;

public class random: MonoBehaviour {

    public AudioClip[] gravel;

    void Update()
    {
        if (!GetComponent<AudioSource>().isPlaying){
            GetComponent<AudioSource>().PlayOneShot(gravel[Random.Range(0,gravel.Length-1)]);
        }
    }
}

```

How can I put my random audio to my audio source. Video for describle my problem: In this video play sound twice (because I run my game twice) In first play I have to attach a file to audio source. I do not know why my audio source is empty and I have to attach a file to it. If I can load sound in my audio source I can fix my problem. I want to play one randomized shot.

# Answer
First of all your first sound playing well because you assigned it explicitly and you have mark on check **Play On Awake**.Uncheck it.

You can do something like,

```
public AudioClip[] _gravel;
private AudioSource _aSource;

void Start()
{
    // Get attach audio source once.
    _aSource = GetComponent<AudioSource>();

    // Start Coroutine for playing sounds. Call it once
    StartCoroutine("PlaySound");
}

void Update()
{
}

IEnumerator PlaySound()
{
    _aSource.clip = _gravel[Random.Range(0,_gravel.Length)];
    _aSource.Play();
    yield return new WaitForSeconds(_aSource.clip.length);
    StartCoroutine("PlaySound");

}

// ===== OR ===== //

IEnumerator PlaySound()
{
    while(true){
        _aSource.clip = _gravel[Random.Range(0,_gravel.Length)];
        _aSource.Play();
        yield return new WaitForSeconds(_aSource.clip.length);
    }
}

```
> 1 votes

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


# Question
Title: What happenes if you leave out buffers for the inputassembler that the vertex shader expects?
I'm working through my first attempt at a "graphics engine" (I use the term loosely as I'm not aiming for much more than something that will display a few meshes). I want to leave my classes as extensible as possible and am currently working on my mesh class.

I want my mesh class to be able to have optional UVs and optional normals, although I generally expect to use these. As I'm new to Direct3d I'm curious if I still have to define matching "zeroed" buffers for the missing normals and UV data if the vertex shader and input assembler is otherwise expecting this data? Should I have my mesh class assemble the missing data zeroed out and declare empty buffers or does Direct3d know to pass null arguments for missing data?

EDIT: I guess zeroed normals wouldn't work as any shader expecting normals would produce bad/bizarre results, but the question regarding texture coords still stands.

# Answer
If i understand your question correctly, you are asking if not providing any buffers for normals will cause the shaders to behave weirdly. Not providing buffers will simply cause the data to be uninitialized, or if you already set data before- to the data you last set. Therefore if you do not want to include texture and normal processing in your shader (omit the data input entirely) you should create a separate shader couple (vertex&pixel) that only inputs positions. When you want to render with normals/textures, you switch to that kind of shader, and when rendering with only positions you switch to the simplifed shader. This swap has generally negligible performance impact compared to filling a buffer with data, so this is the preferred approach.

I assume since you already have working shaders (right?), you know how to create others and set them accordingly. One thing to remember is that those different shaders have different input layouts and consequently different vertex structures/buffers, so don't forget to set those as well.
> 1 votes

---
Tags: c++, directx, rendering, graphics-programming, 3d-meshes
---


title: OpenGL Picking: How to avoid entities?

text:
# Question
Title: OpenGL Picking: How to avoid entities?
I have a terrain and entities(npc, house...).

I'm able to convert screen coordinates to world coordinates with the `glReadPixels` function:

```
glReadPixels(mousePosition.x, mousePosition.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);
// of course its not just that...

```

My character can move over that terrain without problem, but I'm not able to move when the mouse is over a big house and I try to move "behind" that house.

Do you know how I can avoid entities when converting screen coordinates to world coordinates ?

# Answer
Your depth buffer does not contain "entities". It contains the stuff you rendered. So if you read the depth buffer, you will read the depth for the closest stuff you rendered.

So either you make a special depth-only rendering pass that does not contain "entities", or you're going to have to do something else to convert from the user's selected location to a world-space position. And generally speaking, games use something else. Probably a ray-trace, but depending on the nature of your world, even that may not be necessary.
> 4 votes

---
Tags: opengl, depth-buffer, picking
---


# Question
Title: What can I do about a "missing mcp.cfg" error?
I am trying to use MCP. After trying to run `decompile.sh`, I manually ran `decompile.py`, getting the error "`ERROR:root:!! Missing mcp.cfg !!`"

I tried to copy the variables from `mcp.cfg` into the files which reference them, but I still got the error. How can I fix this?

# Answer
> 0 votes
The error is telling you that the file `mcp.cfg` can't be found. Normally this would mean you've deleted it, or you have a bad install of MCP that doesn't contain the file and should re-download it.

However, you mention that you have thought about copying variables from it, so that suggest to me that you do actually have the file on your disk and have seen it.

You also mention having "manually run" the `decompile.py` script, and that is, I think, your problem. You're probably running the script from a working directory that is unexpected (not the root of the MCP installation) and thus your `mcp.cfg` file isn't being found where the scripts think it should should be relative to that current working directory.

Run the script from the proper working directory; consult the documentation or the official website for additional help.

# Answer
> 0 votes
I had the exact same problem but I was able to get MCP running! Open terminal and type "cd (insert mcp dir here)" no quotes obviously. Then, type in "bash" and hit enter. Finally, "./(script name).sh", hit enter and Done! It took me a few hours of a sleepless night to figure this out, but now that I have, hacking is on!

---
Tags: minecraft-modding, modding
---


# Question
Title: How do I test for intersection between a ray and a cone?
I decided that writing a ray-tracer in my game was a brilliant idea, and so now I am looking for code to use for ray to primitive intersection tests. I have based my effort on this very nimble yet complete code. It works well but only supports sphere primitives. I have added plane, disk and ring (in that order) because they are easy. Next I am thinking about adding box and cone.

But while sphere and plane intersection tests are really simple cone seems really difficult.

I have yet to find a simple and easy to adapt java implementation of a ray cone intersection test. I am in this to get a ray-tracer up and working quickly without learning too much math underway, so is does anyone have a java snippet lying around that performs a trivial ray cone intersection test suitable for a small ray-tracer?

# Answer
> 4 votes
I had some time to read up on this and decided to share.

In "serious" ray-tracers that grown-ups use, cones and other similar shapes such as cylinders are usually represented as either tesselated surfaces or as quadric shapes. There exists pure cone-only intersection code that may or may not be more optimized, but implementing the more general quadric approach will give so much more value-for-effort for the beginner that it is worth implementing it first. Thus, in this answer I will focus on the quadric solution.

In geometry quadric shapes are

> any surface that can be defined by an algebraic equation of second degree

. On the normal form this equation looks like this:

**A**x^2 + **B**y^2 + **C**z^2 +2**D**xy + 2**E**xz + 2**F**yz + 2**G**x + 2**H**y + 2**I**z + **J** = 0

By selecting different values for **A** through **J**, and by carefully applying axis aligned clipping planes in the right places, we can define what kind of surface we want. Here are some example shapes (from here):

Finally to the code. Since my ray-tracer was based on the ubiquitous instructional ray-tracer by Leonard McMillan I found a plethora of student extensions more or less based on this code. One in particular by a guy called Charlie had an implementation of `Ray-Quadric` intersection and shading code. I have shamelessly copied the important parts here (full code here), and will comment on it as soon as I get a chance to actually test it in my own application.

```
class Quadric extends Renderable {
    private static final float twoPI = (float)(Math.PI * 2.0);

    float A, B, C, D, E, F, G, H, I, J;
    float A2, B2, C2;
    float miny, maxy;
    Matrix3D OStoWS, WStoOS;
    float theta;

    public Quadric(Surface s, Matrix3D o2w, Matrix3D w2o, float zmin, float zmax, float thetamax,
                   float a, float b, float c, float d, float e, float f, float g, float h, float i, float j )
    {
        surface = s;
        A = a; B = b; C = c; D = d; E = e; F = f; G = g; H = h; I = i; J = j;
        A2 = 2.0f * A;
        B2 = 2.0f * B;
        C2 = 2.0f * C;
        miny = -zmin - Constants.EPSILON; maxy = zmax + Constants.EPSILON;
        OStoWS = new Matrix3D(o2w);
        WStoOS = new Matrix3D(w2o);
        theta = (float)(thetamax * Math.PI / 180.0f - Math.PI);
    }

    Vector3D d = new Vector3D();
    Vector3D o = new Vector3D();
    float a2_1;
    float a, b, c, tOS, tWS, discrim;
    float dMagOS;

    public boolean intersect(Ray ray) {
        WStoOS.transform(ray.origin, o);
        WStoOS.transformNormal(ray.direction, d);
        dMagOS = 1.0f / d.length();
        d.normalize();
        boolean flag = false;

        a = A * d.x * d.x + B * d.y * d.y + C * d.z * d.z;
        b = A2 * o.x * d.x + B2 * o.y * d.y + C2 * o.z * d.z;
        c = A * o.x * o.x + B * o.y * o.y + C * o.z * o.z + J;

        if (a == 0.0f) {
            tOS = - c / b;
            flag = true;    // remember this
        } else {
            discrim = b * b - 4.0f * a * c; // compute discriminant

            if (discrim < 0.0f) return false; // no intersection

            discrim = (float)Math.sqrt(discrim);    // store sqrt value
            a2_1 = 1.0f / (2.0f * a);               // store 1 / (2a)
            tOS = (-b - discrim) * a2_1;            // near intersection

            if (tOS < 0.0f) {                       // near intersection too close
                tOS = (-b + discrim) * a2_1;        // use far intersection
                flag = true;                        // remember this
            }
        }

        tWS = tOS * dMagOS; // need to scale intersection tOS to get tWS
        if ((tWS > ray.tWS) || (tWS < 0)) return false;   // trivial reject

        ray.hitOS.addScaled(o, d, tOS); // get hit point in object space
        if (ray.hitOS.y < miny || ray.hitOS.y > maxy)   // outside clip box?
        {
            if (!flag) { // alright, so the near intersection is outside the clipping box,
                         // but that doesn't mean the far intersection isn't inside
                tOS = (-b + discrim) * a2_1;    // compute the far intersection
                tWS = tOS * dMagOS;             // need to scale intersection t
                if ((tWS > ray.tWS) || (tWS < 0)) return false; // trivial reject

                ray.hitOS.addScaled(o, d, tOS);
                if (ray.hitOS.y < miny || ray.hitOS.y > maxy) return false;

            } else {    // both near and far intersection flunked clip box
                return false;
            }
        }
        if (theta != twoPI) {       // now clip against the accept angle
            float a = (float)Math.atan2(-ray.hitOS.z, -ray.hitOS.x);
            if (a > theta) {

                if (!flag) { // alright, so the near intersection is outside the accept angle,
                             // but that doesn't mean the far intersection isn't inside
                    tOS = (-b + discrim) * a2_1;    // compute the far intersection
                    tWS = tOS * dMagOS;             // need to scale intersection t
                    if ((tWS > ray.tWS) || (tWS < 0)) return false; // trivial reject

                    ray.hitOS.addScaled(o, d, tOS); // update intersection point
                    a = (float)Math.atan2(-ray.hitOS.z, -ray.hitOS.x);
                    if (a > theta) return false;

                    // we haven't actually tested this yet at this point
                    if (ray.hitOS.y < miny || ray.hitOS.y > maxy) return false;

                } else {    // both near and far intersection flunked accept angle
                    return false;
                }
            }
        }

        ray.tWS = tWS;
        ray.object = this;
        return true;
    }

    public void computeNormal(Ray ray) {
        Vector3D nOS = new Vector3D(
            A2 * ray.hitOS.x,
            B2 * ray.hitOS.y,
            C2 * ray.hitOS.z);

        OStoWS.transformNormal(nOS, ray.n);
        ray.n.normalize();

    }

```

# Answer
> 2 votes
This is my Cone Cast written in C# for Unity. It should be fairy simple to port to Java and adjust for your specific needs. It tests if a position is within the cone's volume. Hope it helps!

```
using UnityEngine;

public static class Vector3Extensions
{
    /// <summary>
    /// Casts a cone and checks if the target is within its volume. Parameters are the target position, the angle of the cone, the direction to cast the cone, and optionally, the range of the cone.
    /// </summary>
    public static bool ConeCast(this Vector3 vector3, Vector3 target, float degreeOfAccuracy, Vector3 direction, float range = Mathf.Infinity)
    {
        if(Vector3.Distance(vector3, target) > range)
        {
            return false;
        }
        float actualAngle = Vector3.Dot(direction, target - vector3);
        float coneAngle = Mathf.Cos(Mathf.Deg2Rad * degreeOfAccuracy);
        return actualAngle >= coneAngle;
    }
}

```

If you have any questions, lemme know.

---
Tags: java, intersection, raytracing
---


# Question
Title: How to reduce color space in a post-processing material in Unreal Engine 4
I'm trying to get an old-school Quake 1 look going in UE4.

I am currently using this blueprint in order to get a retro style large pixel filter.

In game (might need to zoom in to see the difference):

The look I am going for now is a low color depth (8 bit etc) that old games such as Quake had. Here is a picture for reference.

Is there any way I can reduce the color space through either a post-processing volume itself or a post-processing material?

# Answer
Figured it out:

Download the default color LUT from here. Open it in Photoshop (or equivilant) and use posterize to reduce the colors. Then take that and use it as a LUT for your post-processing volume.

Here was my outcome:
> 2 votes

---
Tags: color, post-processing, unreal
---


title: About tiles in games

text:
# Question
Title: About tiles in games
I'm trying to learn how to develop games in Unity and my base is tiled games, I would like to know if a simple tile is an image (sprite in 2D) or a game object in 3D.

Since I'm trying to do some kind of 3D tiles with interaction with the user like press to do something + an animation, I would like to know how it works.

# Answer
Per your question, I understand you are not asking for detailed implementation code, since that would be asking for too much more than one single question can offer. So, I understand you are actually asking in conceptual terms.

That being the case, the first thing to tell you is that you can actually do both: you can have tile-based games both in 2D and in 3D. You can even have tile-based games that are programmed as 3D while looking as 2D (e.g. with a top-down camera over the 3D objects). And you can also have games programmed in a 2D logic but which appear to be 3D because of the angles of the objects that are displayed in the 2D sprites (sometimes these are called 2.5D tile-based games).

That being said, you can both use sprites in 2D and/or 3D meshes for a 3D tile-based game. Or you can even mix them. However, let me just give one further clarification. The sprites and/or 3D meshes are usually used for the 2D or 3D objects, respectively. Objects that *occupy* the tiles in the game-world.

But I always find it is easier if you think about the tiles in themselves as being the specific space that characters and objects can occupy and trough which they can move. These spaces can be of the shape of squares or hexagons, etc. These spaces can be filled with sprites or with 3D entities. Therefore, such spaces are previously defined in the code (this means to say the tiles can be merely given by the coordinates the objects can occupy/move trough. For Unity, see this tutorial on creating a square grid for future character movement: https://www.youtube.com/watch?v=nhiFx28e7JY).

I recommend you start by reading the following wiki entry: https://en.wikipedia.org/wiki/Tile-based\_video\_game

Later, search for tile-based games in the gamedev.net forums. There are tons of threads there with good conceptual debates (and even tutorials). And for the implementation of grids for character movement. Those can be of help to get you started, even if they are not tile-based specific.

Also, past questions in this very site can be of help to you. One is: Implementing a 3d tile engine
> 4 votes

# Answer
Even though its pretty straight forward to make tile based game in Unity , there are lot of small stuff which can be pain in the neck later on. As unity till now didn't had tools specifically for tile based game and hence little optimization for such genre. Some of the usual problems faced are tiling of texture on scaled block , gap between adjacent tiles , collision detection , optimization etc.

But recently they have been developing lot of useful tools which can be very helpful for making a tile based game. Here is the link to the video where these tools are demonstrated in detail :- Unite 2015 - Building 2D Worlds with new 2D features in Unity

The tools will be rolled out in future updates but you can get it early to test in this link.
> 1 votes

---
Tags: unity, tiles
---


# Question
Title: How do I make a 2D sprite flash green when tapped?
I have a sprite that is based on an image of a gray circle. When the user touches the sprite, I want the sprite to flash green, as in I want the circle to appear to turn green for 0.2 seconds. I tried setting the color of the sprite via SpriteRenderer's function SetColor, and it blended the color with the initial gray color of the sprite, so I got a very dark green even though I'm really sure I didn't mess up the values when I created the color. Now I'm trying to get my flashing effect by using separate images. I have the images I need, and I have a message getting logged when I tap the circle, I just need to setup a non-looping animation and trigger that animation in my code.

# Answer
I figured it out after learning about the animation editor (if that's what it's called). I'm using two sprites. Both of them are circles, but one is gray and the other is green. I used the animation editor to create an idle animation that just replaces whatever the current sprite is with the gray sprite from my Assets folder. I created a parameter ShouldFlashGreen of type trigger that triggers the green animation to start. When the green animation starts, it replaces whatever sprite is currently being used with the green sprite from my Assets folder. When it stops, it goes back to the idle animation. I then attached a C# script to my Sprite object. Here's the code in the script:

```
using UnityEngine;
using System.Collections;

public class TapHandler : MonoBehaviour {

    private Collider2D circleCollider;
    private Animator animator;

    void Awake () {
        circleCollider = GetComponent<Collider2D> ();
        animator = GetComponent<Animator> ();
    }

    void Update () {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
            Touch firstTouch = Input.GetTouch(0);

            Vector3 worldPoint = Camera.main.ScreenToWorldPoint(firstTouch.position);
            Vector2 touchPoint = new Vector2 (worldPoint.x, worldPoint.y);

            if (circleCollider == Physics2D.OverlapPoint (touchPoint)) {
                animator.SetTrigger("ShouldFlashGreen");
            }
        }
    }
}

```
> -1 votes

---
Tags: animation, sprites, unity, color
---


# Question
Title: Java Reversi/Othello - Checking if Valid move
I've written a gameBoard class for a Reversi/Othello which is the following:

```
import java.io.Serializable;

public class GameBoard implements Serializable {

private static final long serialVersionUID = 1034285059488509251L;
public char[][] board;

public GameBoard(){
    board = new char[8][8];
    setUpBoard();
}

  public void printBoard() {

      //prints numbers at the top of the board
        System.out.print("  ");
        for(int i = 0; i < board.length; ++i){
            System.out.print(i +  "   ");
        }

        //prints column icons and numbers and side of board
        System.out.println();
        for (int i = 0; i < board.length; i++) {
            System.out.print("| ");
            for (int j = 0; j < board.length; j++) {

                System.out.print(board[i][j] + " | ");
            }
                System.out.print(i);
                System.out.println();
        }

    }

public void setUpBoard(){

      // Loop through rows
    for (int i = 0; i < 8; i++) {

        // Loop through columns
        for (int j = 0; j < 8; j++) {
            board[i][j] = '-';
            System.out.println();
        }
    }

    //sets the default piece positions;
    board[3][3] = 'W';
    board[3][4] =  'B';
    board[4][3] = 'B';
    board[4][4] = 'W';

}

public String toString(){
    StringBuilder b = new StringBuilder();
    for(int i = 0; i < board.length; ++i){
        b.append(i +  "   ");
    }

    b.append("\r\n");
    for (int i = 0; i < board.length; i++) {
        b.append("| ");
        for (int j = 0; j < board.length; j++) {

            b.append(board[i][j] + " | ");
        }
        b.append(i);
        b.append("\r\n");
    }
    return b.toString();
 }
}

```

This class as you can see handles basics of the game board. Such as printing the board and setting up the default positions. It is also serializable and I have a saving and loading method to store the game state and an overriden toString method so that I can print the board again.

I have another class called boardLogic and I've been messing around in this class for about 4 hours now trying to figure out how to check what is a valid move in Reversi/Othello or not.

The simple rules are: -You cannot place a piece on any random place -If you are to place a piece it must me adjacent to another piece of your color Horizontally, vertically or diagonally and it doesn't matter how many pieces are in between.

So, can anyone help me out on how I would go about checking if the player had made a valid move or not.

# Answer
Given then two dimension array board\[\]\[\], when a player places a piece, loop over the adjacent elements and check if there is a piece in one of them that matches the player's colour. If so it is a valid move.

The difficulty is in the edge cases - you need to make sure if a piece is placed near the edge of the board you don't check outside the board boundary.
> 0 votes

---
Tags: java
---


title: Call function via ContactListener

text:
# Question
Title: Call function via ContactListener
I've been creating a game on my own in LIBGDX, BOX2D and there' s a problem I can' t solve. When two World bodies collide, method "beginContact" is called in MyContactListener class that implements ContactListener interface.
How am I supposed to change player's healthpoints when it's fixture collides with other bodies' fixtures. I know I have to do this somehow through MyContactListener class, but I can' t find the way how to call the method I need..
Note: My player's body and fixture are created in "Player" class and there are methods "setRemainingHealth()" and "getRemainingHealth()".

Here's also some code, which might illuminate this situation.
MyContactListener.java

```
package utils;

import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.Manifold;

public class MyContactListener implements ContactListener {

@Override
public void beginContact(Contact c) {

    Fixture fa = c.getFixtureA();
    Fixture fb = c.getFixtureB();

    if (fa == null || fb == null) return;
    if (fa.getUserData() == null || fb.getUserData() == null) return;

    if (isTunnelMachineCollision(fa, fb)) {
        // call somehow method "player.setRemainingHealthPoints(player.getRemainingHealthPoints-0.01f)" here
    }

}

@Override
public void endContact(Contact c) {

}

@Override
public void postSolve(Contact c, ContactImpulse arg1) {

}

@Override
public void preSolve(Contact arg0, Manifold arg1) {
    // TODO Auto-generated method stub

}

private boolean isTunnelMachineCollision(Fixture a, Fixture b) {
    return (a.getUserData()) == "terrain" && (b.getUserData()) == "machine";
}

}

```

TestPlayer.java

```
package testPackage;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;

public class TestPlayer {

private float remainingHealthPoints = 3;

private CircleShape shape;
private CircleShape defenseBarrier;
private Fixture defenseBarrierFixture;
private Fixture mainBody;
private BodyDef bodydef;
private Body body;

private float x;
private float y;
private float width;

public TestPlayer(World world, float x, float y, float width) {

    this.x = x;
    this.y = y;
    this.width = width;

    bodydef = new BodyDef();
    bodydef.type = BodyType.DynamicBody;
    bodydef.position.set(x, y);
    bodydef.fixedRotation = true;
    body = world.createBody(bodydef);

    shape = new CircleShape();
    shape.setRadius(width);
    mainBody = body.createFixture(shape, 1.0f);
    mainBody.setUserData("machine");
}

public float getRadius() {
    return shape.getRadius();
}

public BodyDef getBodydef() {
    return bodydef;
}

public CircleShape getShape() {
    return shape;
}

public Body getBody() {
    return body;
}

public void activateDefenseBarrier(World world) {

    defenseBarrier = new CircleShape();
    defenseBarrier.setRadius(width*1.5f);

    defenseBarrierFixture = body.createFixture(defenseBarrier, 1.0f);
    defenseBarrierFixture.setUserData("defenseBarrier");
}

public void destroyDefenseBarrier() {
    if (defenseBarrierFixture != null) {
        System.out.println("olemas");
        body.destroyFixture(defenseBarrierFixture);
        System.out.println(defenseBarrierFixture);
    }
    else {
        System.out.println("fixture on null");
    }
}

public Fixture getDefenseBarrier() {
    return defenseBarrierFixture;
}

public float getRemainingHealthPoints() {
    return remainingHealthPoints;
}

public void setRemainingHealthPoints(float remainingHealthPoints) {
    this.remainingHealthPoints = remainingHealthPoints;
}

}

```

# Answer
> 0 votes
Instead of setting the user data of your `Body` to a string like "**machine**", set it to the `TestPlayer` instance.

```
mainBody = body.createFixture(shape, 1.0f);
//mainBody.setUserData("machine"); don't do this
mainBody.setUserData(this); do this instead

```

That way, when you've identified that the colliding bodies are of the types you care about, you have an instance to the object you want to manipulate.

Something like this might work for you;

```
@Override
public void beginContact(Contact c) {

    Fixture fa = c.getFixtureA();
    Fixture fb = c.getFixtureB();

    if (fa == null || fb == null) return;

    Object udA = fa.getUserData();
    Object udB = fb.getUserData();

    TestPlayer testPlayer = null;

    if (udA != null && udA instanceof TestPlayer) {
        testPlayer = (TestPlayer)testPlayer;
    }

    if (udB != null && udB instanceof TestPlayer) {
        testPlayer = (TestPlayer)testPlayer;
    }

    if (testPlayer != null) {
        testPlayer.setHitPoints(testPlayer.getHitpoints() - 1); // or something like that
    }
}

```

As your world gets more entities it might make sense to let the *user data* of the `Body` to be some wrapper object that holds both the ID and the instance of an object, for example;

```
public class UserDataWrapper {
    public final String id;
    public final Object instance;
    public UserDataWrapper(String id, Object instance) {
        this.id = id;
        this.instance = instance;
    }
}

// when creating your bodies in some class like your TestPlayer
body.setUserData(new UserDataWrapper("PLAYER 1", this));

```

---
Tags: java, collision-detection, libgdx, box2d
---


# Question
Title: How do I convert 3D vertices and faces to 2D shapes?
I'm assuming all the math is done with projection matrices from linear algebra, but I don't yet understand how they work, and haven't found much information on them.

What I'm mainly curious about is how after you convert the 3D stuff to 2D, how do you attribute the vision through a portal (like in game Portal)? How is that math done?

# Answer
The transformation of coordinates is done in 3 steps.

**1. World Transformation:** Vertex coordinates are in relation to the origin of the mesh. To place it inside your world you have a so called world matrix, doing translation, rotation and scaling. Now your vertex coordinates are in world space.

**2. View Transformation:** In the next step the world space coordinates are transformed to camera space. You must note, that you are not moving the camera around, in fact you move the whole world aroung. This is done by the view matrix and the vertex coordinates are now in camera/view space.

**3. Projection Transformation:** Finally you project the coordinates from view space to screen Space. This matrix actually converts your 3D coordinates to screen coordinates, where they can be displayed.

As for you question on the portals: I'd guess they just render the screen a second time to a texture from the position of the "target portal". Then they use this texture for drawing the ellipse on the wall.

Click here for more information
> 2 votes

---
Tags: mathematics, projection
---