title: Pathfinding onComplete event?

text:
# Question
Title: Pathfinding onComplete event?
In HaxeFlixel 4 all `FlxObject`s have a `path` property which must be a `FlxPath` instance

```
class FlxObject extends FlxBasic
{
    ...
    /**
     * The path this object follows.
     */
    public var path(default, set):FlxPath;
    ...

```

a tilemap can be used to find a path

```
var points:Array<FlxPoint> = tileMap.findPath(pathStart, pathEnd);

```

and then an object can walk that path

```
object.path = new FlxPath();
object.path.start(points);

```

What I want to do is run some custom code when the path ends, whether it was cancelled or was fully completed

what I see others do is this (player being the object in question)

```
override public function update(elapsed:Float):Void
{
    if(Std.is(player.path, FlxPath)){
        if (player.path.finished || player.path.nodes==null) {
            trace('finished walking');
        }
    }

```

But this tends to run indefinitely once the player has finished walking, yet I want it to run once. Secondly I don't even want the `PlayState` `update` function to be aware that there was an event where the player finished walking, it's none of it's business unless I tell it that it happened, I want this code block to be self-contained.

I discovered that `FlxPath` has an `onEnd` function, which is exactly what I need, but it does not call any callback, neither are there any ways that I know of to attach it, there is also the `onComplete` property, but I was not able to make use of it.

so here is what I'd ideally like

```
object.path = new FlxPath();
object.path.start(points, function(cancelled){
    trace((cancelled) ? 'path cancelled': 'path completed');
});

```

and this would run only once upon the path ending or getting cancelled

any ideas on some way of achieving this?

# Answer
For now I have solved it in the following manner

in the `PlayState` class I added a function to move objects and an array to track what objects are currently moving

```
class PlayState extends FlxState
{

    public var TILE_WIDTH:Int = 16;
    public var TILE_HEIGHT:Int = 16;

    // since flixel pathfinding does not have an onComplete callback, lets add it ourselves!
    // this variable will hold the objects that are currently walking a path
    // the update function will track when the path was finished and remove the object from the list
    public var walkingPath:Array<Dynamic> = new Array();

    /**
     * Function that is called once every frame.
     */
    override public function update(elapsed:Float):Void
    {
        // track which objects are currently walking a path
        trackWalkingObjects();

        super.update(elapsed);
    }

    /**
     * Maintain a list of objects that are currently walking a path
     */
    public function trackWalkingObjects(){
        var i:Int = walkingPath.length, data:Array<Dynamic>, object:FlxObject, callback:FlxObject->Dynamic = null;

        // loop over the objects in the walkingPath array
        // each item will contain array with an object and callback variable
        while (i-- > 0) {
            data = walkingPath[i];
            callback = data[1];
            object = data[0];

            // check if there are any path to walk, nodes to walk or if the path has finished
            // if so, then the object is no longer walking and should be removed from the array
            if (!Std.is(object.path, FlxPath) || object.path.nodes == null || object.path.finished) {
                if(callback != null){
                    callback(object);
                }
                walkingPath.splice(i, 1);
            }
        }
    }

    /**
      * Simplify the pathfinding mechanism
      * Use as: walkTo(player, targetPoint, function(player){ trace(player, 'has finished the path'); })
      * @param  object
      * @param  targetPoint
      * @param  callback
      * @return FlxPath
      */
    public function walkTo(object:FlxObject, targetPoint:FlxPoint, ?callback = null)
    {
        // should pass around positions not coordinates
        // should have a function to snap to tile to avoid rounding, best if it's in the Position object?
        var tileCoordX:Int = Math.floor(targetPoint.x / TILE_WIDTH);
        var tileCoordY:Int = Math.floor(targetPoint.y / TILE_HEIGHT);

        if (tileMap.getTile(tileCoordX, tileCoordY) == 2) {
            var pathStart = FlxPoint.get(object.x + TILE_WIDTH / 2, object.y + TILE_HEIGHT/2);
            var pathEnd = FlxPoint.get(tileCoordX * TILE_WIDTH + TILE_WIDTH / 2, tileCoordY * TILE_HEIGHT + TILE_HEIGHT / 2);

            var points:Array<FlxPoint> = tileMap.findPath(pathStart, pathEnd);
            if (points != null) {
                object.path = new FlxPath();
                object.path.start(points);

                // add the object to be tracked for when it finishes walking
                walkingPath.push([object, callback]);
            }
        }

        return object.path;
    }
}

```

now I can just call this and be done with it

```
walkTo(player, targetPoint, function(player){
    trace(player, 'has finished the path');
});
player.path.speed = 300;

```

Since I am a beginner at haxe and flixel (2 days worth), any other answers are still appreciated!
> 1 votes

---
Tags: tilemap, flixel, haxe
---


# Question
Title: How can I implement A* so that it accounts for the size of the actor?
I'm trying to make a little A\* implementation using polygon verticies as nodes instead of grids and I ran into the problem of figuring out what paths are wide enough to accommodate the actor moving through them.

Lets say the actor was 10x10 and the space between two verticies was only 5 units wide, the actor shouldn't be able to fit into that space but with the regular A\* algorithm it would. How can I prevent this?

# Answer
> 1 votes
I personally don't like the idea of altering A\* for this and would instead create an abstract graph per actor size on which A\* would run.

I would precalculate a waypoint network or coarse grid (see The Mechanics of Influence Mapping: Representation, Algorithm & Parameters) per actor size which only contains nodes, on which an actor could stand.

I would then use A\* as usual on the waypoint network which suits the characters size.

This approach probably scales horribly with a very large number of different actor sizes. But if it's just a hand full, this should work fine.

---
Tags: path-finding, collision-prediction
---


# Question
Title: 2D Map Editor Tiles Palette - Best suited Java Elements to use?
I'm making a 2D RTS Map Editor and here came the moment to make a Palette which is just a popup frame showing tiles to be clicked on and then applied on the map.

I'm wondering which Java Elements to use for this palette? At the moment I have set a JFrame which will contain Jlabels which have their Icon set as some ImageIcon (which are the tiles of my game). (I have a `List<ImageIcon> tiles` which contains every tiles)

```
mainFrame.setLayout(new GridLayout(tiles.size() / 2, 2, 5,5));
    JLabel tilePanel;

    for (int i = 0; i < tiles.size() ; i++) {
        tilePanel = new JLabel();
        tilePanel.setIcon(tiles.get(i));
        mainFrame.add(tilePanel);
    }

```

Here's what I have:

However, I want to be able to click on these JLabels to be selected and so that I can use a function like `getSelectedTile` in my main JFrame to place them on the Map. But adding a mouseListener/Event to each and every JLabel doesn't seem right.

**My questions are:**

* Am I going the right way? If so, how should listen to my JLabels to know which tile is selected.
* What SHOULD I use if this isn't the way to go?

Thanks in advance! All suggestions will be taken into consideration :)

# Answer
> 1 votes
I'd go with an MouseListener per JLabel. Make a custom subclass of MouseListener which is parameterized with the tileId (or whatever you are using to identify the tiles).

Furthermore would not recommend using Swing for a game /mapeditor, we build a map editor using jmonkeyengine3 and Swing which is not working very well. You might want to look into JavaFX instead.

---
Tags: java, rts, map-editor, swing, palette
---


# Question
Title: Random number in a range, biased toward the low end of the range
I have an input of two values, let's say 1 and 10. Lesser numbers should overall occur more often in the output than higher numbers, while there is a peak in the probability at #2:

```
1: very common
2: extremely common
3: very common
4: common
5: somewhat common
...
10: extremely rare

```

How do I achieve this? My code until now looks like this:

```
function getValue($min, $max) {
    return random($min, $max);
}

```

# Answer
> 56 votes
Assuming you have a `random()` function that returns a uniformly-distributed numeric value in the interval \[0, 1)...

(I see the edit attempt to "fix" the mismatched bracket above, but this is deliberate and carries specific meaning)

```
random() - random()

```

Gives a distribution that peaks at 0 and falls off toward -1 and 1.

```
abs(random() - random())

```

Peaks around 0 and falls off toward 1

```
 floor(abs(random() - random()) * (1 + max - min) + min)

```

Gives you a random number between `min` and `max`, with outputs closer to `min` being more common, falling off linearly toward the max.

---

Note as pointed out by Logan Pickup in the comments below, there's a slight mathematical artifact here if you're using this to generate continuous random numbers (ie. without the `floor`): the only way to get zero out of `abs` is to start with zero, but you can get a value of epsilon if the input is either positive *or* negative epsilon. So you have about half the chance of getting *exactly* zero as you have of getting the next larger representable number. If you're using this with `floor` after the `abs` to generate random integers, then this little quirk will be swamped and not noticeably affect the result.

---

Using inverse transform sampling you can get this same linear distribution (without the 0 artifact) with one random sample via the formula:

```
1 - sqrt(1 - random())

```

(and we can apply the same scale/offset/floor approach to get a corresponding discrete distribution)

You can find methods to get custom-shaped probability distributions in this answer or the links suggested in comments above.

# Answer
> 37 votes
Let's say "rand()" gives you a random number between 0 and 1 (inclusive).

```
pow(rand(), 2)

```

will give you an answer between 0 and 1 (inclusive), but the result is more likely to be close to zero, following a quadratic curve.

```
pow(rand(), 0.5)

```

will give you an answer between 0 and 1 (inclusive), but the result is more likely to be close to one, following a square root curve.

And since the min and max of the output are still 0 and 1, this distribution can be mapped to any range (given *min*, *max*, and the exponent *p*) like so:

```
result = min + (max - min) * pow(rand(), p)

```

Using different values of p can bias you towards the minimum or maximum value depending on your needs:  (example of mapping a 0-1 range by raising x to different powers. From top to bottom: 1/4, 1/2, 2, 4)

Experiment with different powers to find what works for you. Just remember that bigger powers greater than one will bias you towards the minimum value, and smaller powers less than one but greater than zero will bias you towards the maximum value.

You can also swap *max* and *min* to flip the distribution of results, and if you want integer results, I'd use floor(x), increase *max* by one, and either use a rand() function that is exclusive at the top end (won't return 1.0) or clamp the final output to the range to filter out that rare case.

# Answer
> 10 votes
Why not use a system similar to advantage/disadvantage as used in DnD 5e?

It boils down to: disadvantage: roll 2 (or any number of) dice and keep the lowest. advantage: roll 2 (or any number of) dice and keep the highest.

for 1 out of 2 dice this gives a linear chance decreasing as you get higher:

example: http://anydice.com/program/1227

for one out of more dice this gives a curve:

example: http://anydice.com/program/585d

And picking more dice out of the set favors numbers in the lower-middle of your range.

I hope this helps

# Answer
> 6 votes
You can use a local variable to save a random call:

```
function F(min, max) {
  var t = random(); //Assuming this returns a value between 0 and 1
  return min + (max - min) * t * t;
}

```

This makes a non linear distribution where values close to `min` are more frequent. You can force even more extremal distribution by inserting `t = t*t` or user a `pow` with other values.

# Answer
> 5 votes
A naive and not efficient algorithm that would give you a linear distribution:

```
vector values;
int iterations = 1;
for ( val = max; val >= min; --val ) {
  for ( i = 1; i <= iterations ; ++i )
    values.push_back( val );

  ++iterations;
}

// The goal is to have in your values vector something like this for min = 1 and max = 4:
// [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]

return values[random(0, values.size() - 1)];

```

This will give you what you need.

# Answer
> 5 votes
If this is for a game, often you want to tweak values intuitively rather than rely on some existing distribution.

A good way to do this is to pick numbers from an array, and duplicate the values you want more than one. For example, here's some python code that does that. The nice thing about it is that you can see pretty easily the probability of the different options.

```
import random
values = [
1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3,
4, 4, 4, 4,
5, 5, 5, 5,
6, 6, 6,
7, 7,
8,
9,
10
]
random.choice(values)

```

Obviously this only makes sense with a small number of values.

Alternatively, if you have a probability distribution in mind you can use Inverse Transform Sampling. It can take the uniform random number from 0 to 1 and map it so that it matches any probability distribution. It's requires some maths, but if you have some good libraries they should be able to help you out.

# Answer
> 2 votes
If you have uniformly distributed random numbers, you can use those as the parameter to a mathematical function that has a exponential-like shape, so that most numbers in the random range yield a low value. The initial random input can be normalized, then scaled to your range, so the function is well-behaved.

For example, the following function, if given normalized values from 0 to 1 as input:

You can tweak the parameters to make this cover the whole output range from 0 to 1. And if you need higher numbers, just multiply or offset the result.

I didn't check this mathematically, but it seems good enough experimentally.

# Answer
> 2 votes
I recommend using the function:

where *s* and *g* represent your minimum and maximum values, respectively, *R* is a random number between 0 and 1 (inclusive) and *n* is a pre-determined constant. The notation ||x|| represents the nearest integer to x.

An example in PHP 5:

```
function biasedRandom($min, $max) {
  $power = 2;
  # lcg_value() returns a random number between 0 and 1
  $bias  = pow(lcg_value(), $power);
  return round($min + ($max-$min) * $bias);
}

```

---

In an IPython notebook I ran my function 1000 times each for different powers. It generated this graph, where each value (x-axis) is plotted against the probability of it occurring (y-axis):

The graph shows that as p, the power which we raise the random number to, increases, the 'steepness' of the graph also increases.

That is to say, a higher value of p will make the smallest value, in this case 1, to have a much higher probability of occurring than the highest value, 10. See the green line, where p equals 8.

In the case of the blue line, where p is only equal to 2, the bias is far less extreme, and all numbers are closer in probability.

This animation demonstrates how the probabilities of each value change with different values of p:

I used this python function to generate each of the biased random numbers used as data in all of the following graphs.

These box-plots each show the distribution of 500 values generated by my function, with powers of (from top to bottom) 2, then 2.5 then 4.

The box-plots clearly show that smaller numbers are more common than larger numbers (the medians are *all* less than 5.5), and that there is a higher density of values towards the lower end of the spectrum. However, one can also see how high values (all the way up to ten) still emerge sometimes.

If we compare the box-plots we can again see that a lower power (the top-most box-plot has the lowest power, in this case 2) leads to a more even spread of values, with high values appearing more frequently and low values appearing less frequently than when using higher powers.

Without rounding the function's final result, we can obtain the following visualisation, which shows clearly the higher density of smaller numbers. Values are plotted as they are obtained by the function.

The above image shows the distribution of results for powers 8, 16 and 32. The layout is intended to represent a number line, with 1 on the far left and 10 on the right.

# Answer
> 1 votes
Couple other ideas:

# Folded Normal Distribution.

This is achieved by generating a standard Gaussian random, then running it through `abs()`. Values greater than 1 are possible, feel free to deal with it however you choose; clamp it, re-randomize, ignore.

# Wald Distribution.

Also known as the Inverse Gaussian.

0 as a result has a very low probability, while values near 0 have a very high probability, trailing off towards infinity (see above about clamping).

# Answer
> 0 votes
The important thing is to re-map the function from 0-1 to what you desire. A big part of this depends on just what distribution you want from it. I suspect you want something that has an exponential decaying type curve in it, although you have to really ask yourself what you want the distribution to look like. A couple of possibilities are an exponential decay function, and a inverse function, although in both cases the edge cases need to be well studied. I'm not going to give you the code, but rather the formulas. Assume `R` is a random number between 0-1.

Inverse Linear:

```
while (R<.1) {
    R*=10;
}
return ceil(10-(1/(R))

```

Exponential Decay:

```
// Will likely need to work on some edge cases
return 10-10*(e-e^R)

```

To test it, I suggest that instead of using real random numbers, iterate through, say, every 0.01 value of R, and see if the distribution is correct. If there are points that lie outside your range, find a way to remove them. Good luck!

# Answer
> 0 votes
One can use a simple formula like so:

```
function getValue(min,max) {
    return min-1+Math.pow((max-min+1),Math.random());
}

```

When given min as 1 and max as 10 this generates a number from 1.0 to 10.0 where 10.0 is rare. Remember Math.random() generates a uniform random number from 0.0 to 1.0

Here is some R code to show you the results:

```
(function(min,max){
    x=min-1+(max-min+1)^runif(10000);
    print(summary(x));
    hist(x)
 })(4,28)

```

# Answer
> -1 votes
You could call the random function twice:

```
 function getValue($min, $max) {
     return random($min,random($min, $max));
 }

```

For numbers 1 - 5, the probabilities for getValue(1,5) are
1 = 137 out of 300
2 = 72 out of 300
3 = 47 out of 300
4 = 27 out of 300
5 = 12 out of 300

---
Tags: mathematics, random, distribution, probability
---


# Question
Title: SDL2, OpenGL, Nvidia laptop screen tearing
EDIT 2017-05-14 dvb. Issue still active to this very day, see geforce forum link in main question.

Note 3: "Stoltverd" has posted a "fix guide" on geforce forum. It has workarounds for non-OpenGL games.

https://forums.geforce.com/default/topic/1008527/geforce-mobile-gpus/-guide-diagonal-screen-tearing-problems-with-optimus-nvidias-control-panel-not-working-like-it-should-need-a-fix-get-in-here/

Note 4: My workaround for OpenGL games: use HDMI output to external monitor. (In my case, the only game I care about is my own, and I use a big cheap HDMI TV for demo.)

EDIT 2016-03-06.

Note 1: Apparently this is a known issue with Nvidia. If you've found here due to same problem, please stoke the collective "please fix it" by filing a "question" at https://nvidia.custhelp.com/app/ask.

---

Note 2: Doesn't happen on external monitor. Also doesn't happen on internal display if external monitor is mirroring. (Surprise.)

---

I'm developing my game directly in C++, OpenGL, and SDL2.

On an Alienware 15 R2 laptop with Nvidia GTX 965M, I get screen tearing in a curious diagonal line like shown below. It goes across the window top left to bottom right.

The image below is taken during a screen fade-in, so shows just a brightness line. But it happens between any two different frames.

If my window is full screen, the line goes top-left to bottom-right of the whole screen.

Same code runs fine (no tearing) on: All macs, same laptop on Intel integrated GPU, desktop PC with Nvidia 730.

Same laptop looks fine with other games, Chrome+Shadertoy, &c.

Main loop looks something like:

```
// setup code
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetSwapInterval(1);
    flags = SDL_WINDOW_OPENGL;
    SDL_CreateWindow(... ,flags);
// main loop
while(1) {
    this->checkEvents();
    SDL_GL_SwapWindow(this->mainWindow);
    this->doGlDrawing();
}

```

Grepping forums, I've seen reports of some OpenGL games showing this on Alienware & other Dell laptops.

All suggestions welcome! Thanks.

Edit 2016-02-20, some links to similar user-side reports: https://forums.geforce.com/default/topic/903422/geforce-mobile-gpus/diagonal-screen-tearing-issues-on-gtx-860m-870m-960m-965m-970m-980m-/

http://en.community.dell.com/owners-club/alienware/f/3746/t/19658623

https://www.reddit.com/r/Alienware/comments/427ltv/anyone\_have\_diagonal\_screen\_tearing\_when\_playing/

# Answer
> 0 votes
I don't know SDL at all, though I do know a little of OpenGL. Have you tried enabling VSync? I did some research, and you could accomplish this by passsing in SDL\_HINT\_RENDER\_VSYNC to SDL\_CreateRenderer(). This is where I found this information: https://wiki.libsdl.org/SDL\_HINT\_RENDER\_VSYNC

---
Tags: opengl, sdl2, nvidia, double-buffering
---


# Question
Title: Any downsides to exporting an audio file at double-speed then have the game engine playback at half-speed?
I want to cut back on my game's file size and music and SFX are taking up a good chunk.

If I make a song or sound effect at 120bpm and then apply a tempo and pitch doubling using a DAW or standalone program, then record the new double speed audio file, it ends up being half the original file size (because the song length is now halved). Then I use my game engine (Unity) to play back the 240bpm audio file at half speed, so now it sounds normal. No artifacts or distortion.

So here's the question: am I sacrificing anything like processing power in order to play it at half-speed? I am loading in a file that's half the size so there must be some kind of trade-off somewhere right? I have a feeling nobody in their right mind would do this but why not?

# Answer
By authoring an audio clip with high BPM, then playing back at half speed you are effectively halving the sample rate.

You can achieve a similar reduction in asset size without changing your workflow or any existing audio files by reducing the sample rate in the AudioClip inspector. Also checkout the various compression options on that page as they all have different storage / quality / CPU trade-offs.

It is often best to import assets files into your unity project as they are. Unity then allows configuration of independent quality settings for each build target.

---

"Am I sacrificing anything ... in order to play it at half-speed?":

Yes. You mention authoring at a high pitch so that it will sound normal on playback. By reducing the range of useful frequencies during authoring you are essentially compressing your audio into an artificiality narrow range of values, this may compromise the quality of sound on playback. This effect will not always be apparent to the listener.
> 43 votes

---
Tags: unity, audio, memory-efficiency
---


# Question
Title: IEnumerable Elements 'Where' and 'Select' In Unity?
I have a C# program that has a function that reads an XML. I took that function and brought it over to my Unity game which will be using the same XML. However, my reading method doesn't seem to work.

Libraries:

```
using System.Xml;
using System.Xml.Linq;

```

Reader:

```
static public XDocument ProjectXML = XDocument.Load(SaveHandler.gFolder + "xml");
    List<XElement> GameInfo = ProjectXML.Descendants("Project").Elements("Subsystems").Elements("Values").Where(x => x.Attribute("Name").Value == "GameInfo").Elements("Value").ToList();
    foreach (XElement elem in GameInfo)
    {
        if (elem.Attribute("Name").Value == "TerrainGenerationMode")
            GenerationMode = (elem.Attribute("Value").Value == "Flat");
        if (elem.Attribute("Name").Value == "WorldName")
            WorldName = elem.Attribute("Value").Value;
        if (elem.Attribute("Name").Value == "TerrainLevel")
            TerrainLevel = int.Parse(elem.Attribute("Value").Value);
        if (elem.Attribute("Name").Value == "TerrainBlockIndex")
            TerrainBlock = int.Parse(elem.Attribute("Value").Value);
        if (elem.Attribute("Name").Value == "TerrainOceanBlockIndex")
            OceanBlock = int.Parse(elem.Attribute("Value").Value);
    }
    PlayerPosition = new double[3]; // Temporary Line
    List<XElement> Player = ProjectXML.Descendants("Project").Elements("Entities").Elements("Entity").Where(x => x.Attribute("Name").Value == "Player").Elements("Values").Where(x => x.Attribute("Name").Value == "Body").Elements("Value").ToList();
    foreach (XElement elem in Player)
    {
        if (elem.Attribute("Name").Value == "Position")
            PlayerPosition = elem.Attribute("Value").Value.Split(',').Select(double.Parse).ToArray();
    }

```

That code is perfectly fine in my other program. But apparently `Where` and `Select` don't exist in Unity's libraries.

So what are my alternatives in Unity?

EDIT, Errors:

```
Error   1   'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' could be found (are you missing a using directive or an assembly reference?) F:\Repositories\SC TB 3D\Assets\Survivalcraft\Settings.cs   22  111 Assembly-CSharp
Error   2   'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' could be found (are you missing a using directive or an assembly reference?) F:\Repositories\SC TB 3D\Assets\Survivalcraft\Settings.cs   37  107 Assembly-CSharp
Error   3   'System.Array' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)   F:\Repositories\SC TB 3D\Assets\Survivalcraft\Settings.cs   41  75  Assembly-CSharp

```

# Answer
> 2 votes
LINQ expressions (Where, Select etc.) are a .NET 3.5 feature. By default, Unity only supports .NET 2.0.

You could change the used version of the .NET framework in the project settings of MonoDevelop / Visual Studio. But that will prevent your game from working on certain platforms.

When you want to keep compatibility with all available build targets, you have to implement `.Where()` yourself with a `foreach` loop.

```
foreach ( XElement element in ProjectXML.Descendants("Project").Elements("Entities").Elements("Entity")) {
    if (element.Attribute("Name").Value == "Player") {
         // ...etc...
    }
}

```

# Answer
> 2 votes
You are missing:

```
using System.Linq;

```

While a little out of date at this point I find the Mono Compatibility page form the 4.10 documentation to be useful.

It lists IEnumarable.Where() as compatible with both .NET 2.0 and .NET 2.0 Subset.

# Answer
> 0 votes
The code that I am using now is like Philipp's answer, but here's what I can up with for future reference:

```
    ProjectXML = XDocument.Load(SaveHandler.gFolder + "Project.xml");
    List<XElement> GameInfo = new List<XElement>(ProjectXML.Descendants("Project").Elements("Subsystems").Elements("Values"));//.ToList();
    foreach (XElement x in GameInfo)
    {
        if (x.Attribute("Name").Value == "GameInfo")
        {
            GameInfo = new List<XElement>(x.Elements("Value"));
            break;
        }
    }
    foreach (XElement elem in GameInfo)
    {
        if (elem.Attribute("Name").Value == "TerrainGenerationMode")
            GenerationMode = (elem.Attribute("Value").Value == "Flat");
        if (elem.Attribute("Name").Value == "WorldName")
            WorldName = elem.Attribute("Value").Value;
        if (elem.Attribute("Name").Value == "TerrainLevel")
            TerrainLevel = int.Parse(elem.Attribute("Value").Value);
        if (elem.Attribute("Name").Value == "TerrainBlockIndex")
            TerrainBlock = int.Parse(elem.Attribute("Value").Value);
        if (elem.Attribute("Name").Value == "TerrainOceanBlockIndex")
            OceanBlock = int.Parse(elem.Attribute("Value").Value);
    }

    Debug.Log("GenerationMode: " + GenerationMode);
    Debug.Log("WorldName: " + WorldName);
    Debug.Log("TerrainLevel: " + TerrainLevel);
    Debug.Log("TerrainBlock: " + TerrainBlock);
    Debug.Log("OceanBlock: " + OceanBlock);

    PlayerPosition = new double[3]; // Temporary Line
    List<XElement> Player = new List<XElement>(ProjectXML.Descendants("Project").Elements("Entities").Elements("Entity"));
    foreach (XElement x in Player)
    { // .Where(x => x.Attribute("Name").Value == "Player").Elements("Values")
        if (x.Attribute("Name").Value == "Player")
        {
            Player = new List<XElement>(x.Elements("Values"));
            break;
        }
    }
    foreach (XElement x in Player)
    { // .Where(x => x.Attribute("Name").Value == "Body").Elements("Value").ToList();
        if (x.Attribute("Name").Value == "Body")
        {
            Player = new List<XElement>(x.Elements("Value"));
            break;
        }
    }
    foreach (XElement elem in Player)
    {
        if (elem.Attribute("Name").Value == "Position")
        {
            string[] strings = elem.Attribute("Value").Value.Split(',');
            PlayerPosition = new double[] {
                double.Parse(strings[0]),
                double.Parse(strings[1]),
                double.Parse(strings[2])
            };
        }
    }

    Debug.Log("PlayerPosition: " + PlayerPosition);

```

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


# Question
Title: How to reduce polycount for game objects?
I am an intermediate in Blender, and I have always noticed that as the polycount increases to more than 20,000 polygons, Blender starts to slow down and I am not able to sculpt properly.

My PC is pretty powerful:

* i5 2500 processor
* 8GB RAM
* Radeon 7770HD dedicated graphics card

---

Does this mean that the poly count of all the games needs to be less than 20,000?

If not, than how can I reduce the polycount, and what should be the average polycount for all the game objects?

# Answer
> So does this mean that the polycount of all the games needs to be lesser than 20k?

Certanly not, there are games that render millions of triangles per frame. \[1\]

The other part of your question is somewhat harder to answer without more knowledge of target platform or type of game. For say, third-person shooters, characters are in the center of view most of the time and can have 10k triangles or more.

Most geometry in games have multiple levels of detail as well, so the futher away the are from the camera the smaller number of pixels they represent on screen, so we use simplified geometry. Same applies to textures.

I shouldn't worry about blender slowing down while modeling your assets, use your assets in an game engine and go from there.

\[1\] - http://www.eurogamer.net/articles/uncharted-2-mastering-the-cell-blog-entry
> 1 votes

---
Tags: blender
---


title: How to remove skeleton from a model?

text:
# Question
Title: How to remove skeleton from a model?
I have bought a 3d character on turbosquid. I opened it in Unity and everything loads fine except the animations. I then imported the skeleton to Mixamo to find out the skeleton is messed up. I use the set joints manually in Mixamo, but when it tries to fix the issue, the hands get attached to the butt/hips. I would like to get rid of the skeleton and remake it. How would I go about doing this?

I believe what I am trying to do would be called derigging? I could then use Mixamo's autorig tool to make a better skeleton.

# Answer
> 1 votes
Select all bones - delete all bones.
Select all weight maps - delete all weight maps.
If anything else remains, is it related to rigging - delete it.

---
Tags: rigging
---


# Question
Title: Detect Input.GetMouseButtonUp outside a GameObject in Unity?
How do I detect Input.GetMouseButtonUp outside a specific GameObject's area in Unity? Are there any Unity Assets for this?

# Answer
You could do it using Vector3.Distance(...), checking the distance between the mouse click position and the object(s). For simplicity though, I would suggest using colliders (sized according to your selection area) and casting rays from the mouse position.

```
void Update()
{
    if(Input.GetMouseButtonUp(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RayHit hit;
        if(Physics.Raycast(ray, out hit))
        {
            // do what you want
        }
    }
}

```

You can exclude certain object layers by passing an argument to the physics raycast call. Alternatively, just check that the collider you've hit belongs to a relevant object by checking it's tag, layer, name or one of its components.

Excluding certain layers using a layer mask would be my approach.

**Edit:** Just to be clear, if you're checking that the click wasn't within one of the non-detection areas, you could use a layer mask to detect only these special colliders and then do:

```
if(!Physics.Raycast(ray, 1000, layerMask))
{
    // ok
}

```

Where 1000 is some max distance and the layerMask is used to exclude non-relevant layers.

http://docs.unity3d.com/ScriptReference/LayerMask.html
> 1 votes

# Answer
> **Approach one**
>
> If this is a 2D game then I would suggest creating a quad and placing it below the rest of your objects. Then whenever `GetMouseButtonUp` is called fire a RayCast at the quad from the camera. If it hits the quad then you can progress the code. If it is stopped by another collider (i.e. collider defining do not detect here, then stop the code).

This approach I have decided would be worse to implement, I would go for the one below but have kept it in for the sake of completeness.

**Approach two**

Alternatively, for any areas where you do not want to have detection occurring assign them a layer i.e. `NoMouseDetectionLayer` then use the raycast and if it doesn't hit one perform the code.

```
public class GetInputs : Monobehaviour {
     int blockInputMask;
     // Range of the raycast (value not that important)
     public int camRayRange = 200f;

     void Start(){
         int blockInputMask = LayerMask.GetMask("NoMouseDetectionLayer");
     }

     void Update(){
         if(Input.GetMouseButtonUp()){
              Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);

              RaycastHit floorHit;

              if (!Physics.Raycast(camRay, out floorHit, camRayRange, blockInputMask)) {
                   // If it doesn't hit an object on the layer perform the code.
              }
              else{
                   // It hit the object so don't do anything.
              }
         }
    }
}

```

This has the benefit that it is easy to assign new areas, all you need to do is create a new object with a collider and set its layer as `NoMouseDetectionLayer` which is done in the top right of the inspector.
> 0 votes

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


# Question
Title: Achieve a red lighning effect in unity for a 2d game
Effect that im refering to: http://youtu.be/jaBY83WvS3M#t=05m36s

How could I achieve this kind of red lightning/flashing/shadowy effect in Unity3D for a 2D game? I'm trying to think of a way but I'm not that good with shaders or the particle system if thats even the right way to do it.

So I'm looking for any advice on how to achieve this or point me to the right direction.

# Answer
Attached to every sprite is a `SpriteRenderer` component which has a `color` property. You can use that property to recolor the sprite. The color is applied *multiplicative* to the sprite, so pure red means all color channels but red are filtered out and the scene becomes shades interpolated between pure black and pure red. This should look very similar to the effect in that video:

```
gameObject.GetComponent<SpriteRenderer>().color = Color.red;

```

This is how it looks in the game:

However, that will only recolor that one sprite this script is attached to. Attaching it to every single sprite in your game might be a bit tedious to set up and might also be quite inefficient at runtime. But when you want to change the color of *all* sprites in the game, you can abuse the fact that all sprites by default share the "Sprites-Default" material. This material also has a `color`, and changing it has the same effect as changing it on the SpriteRenderer. So you just need a script with a reference to any sprite in your scene and then do:

```
anySprite.GetComponent<SpriteRenderer>().sharedMaterial.color = Color.red;

```

to make them all red. As a starting point you can use this script I just hacked together and attach it to one sprite. It will cause all sprites in your scene to blink red:

```
using UnityEngine;

public class Blink : MonoBehaviour {

    private static readonly Color DEFAULT_COLOR = Color.white;
    private float blinkPhase = 0.0f;

    public float blinkSpeed = 1.0f;
    public Color color = Color.red;

    void Update () {
        blinkPhase += blinkSpeed * Time.deltaTime;
        if (blinkPhase >= 1.0 || blinkPhase <= 0.0) blinkSpeed = -blinkSpeed;
        gameObject.GetComponent<SpriteRenderer>().sharedMaterial.color = Color.Lerp(DEFAULT_COLOR, color, blinkPhase);
    }
}

```

If you want any sprites to *not* be affected by this (like your UI, for example), create a new Material with a different name, set its shader to "Sprites-\>Default" so it behaves like the normal sprite material and assign it to any sprites you want to be exempt.
> 3 votes

# Answer
I think I would start with simply putting a UI panel that covers the entire screen, and most of the time is disabled. When you want the effect, enable it and change the color.

Alternatively, you could use a red light source, and make a 2.5D game. That's basically what I suspect was done in Diablo.
> 0 votes

---
Tags: unity, c#, 2d, lighting, particles
---


title: Modeling an inventory system in SQL

text:
# Question
Title: Modeling an inventory system in SQL
I'm working on a multiplayer game played through the browser. It's not a real-time game which is why I decided to go with a database, however I'm pretty weak with SQL and starting to run into problems.

Right now I'm working on the inventory system, the requirements being:

* A Player can have 0 or more of each item
* Certain items have a max limit
* Certain items can only be bought with a minimum XP

I have a table for my Player and Item. How should I store the inventory relationship? I feel like I'll need a separate table for this, rather than a simple ManyToMany relationship, but I'm not sure what it would look like. My first thought is a table that has a player ID and the counts of each item that player has. I would need a column for each item I have which doesn't seem very maintainable... does that seem right?

And what's the best way to ensure the max limit and minimum XP constraints? The proper way seems to be a constraint in the database, but I can't think of a way to query items that the player is eligible to buy.

Thanks!

# Answer
You will need three tables: `Player`, `PlayerInventory` and `ItemType`.

`ItemType` stores the shared information by all instances of that item, like the name, maximum stack size, minimum exp, appearance and other properties. Primary key should be an integer-id. The advantage of storing these properties centralized is that if you decide to change the game balance and modify the value of "Gold Bar" from 500 to 600, you only need to modify one line of one table and not run a job over your whole inventory data.

`PlayerInventory` then represents what item stacks the players actually have with the current amount for that player. Depending on whether you want an auto-ordered inventory or a manually ordered inventory with n slots, primary key would be `PlayerId, ItemType` with another column `Amount` or `PlayerId, SlotNumber` with two additional columns `ItemType` and `Amount`.

To get information about the complete inventory of the player, you would do an inner JOIN:

```
SELECT ItemType.Name, PlayerInventory.Amount
FROM PlayerInventory
JOIN ItemType ON PlayerInventory.ItemType = ItemType.Id
WHERE PlayerInventory.PlayerId = ?;

```

The maximum stack limit and minimum exp stuff are business rules I would enforce on the application layer. Constraints are a more advanced feature of SQL I wouldn't recommend to bother with when you are "pretty weak with SQL". They are also not easy to deal with because you usually want to handle a constraint violation in your application anyway.

If you want all item types a player id `x` can buy, you would do:

```
SELECT * FROM ItemType WHERE MinExp <= ( SELECT Experience FROM Player WHERE PlayerId = ?);

```

But usually you might also want to show the player the neat stuff they *could* buy when they progress further in the game, so you would often select all anyway and then check on the application which ones are displayed as unavailable.
> 4 votes

# Answer
> How should I store the inventory relationship?

In the table for `Inventory`, have a column for `PlayerID` and one for `ItemID`, either use rows in the inventory table or have one more column for `Count` or something. Have the game logic set the restriction as in how many of each item a player can have.

> And what's the best way to ensure the max limit and minimum XP constraints?

Are you refering to an item level, that a player needs to be at least level N to be able to use? In the `Item` table, have a column for minimum level a player needs to have to be able to use that said item. Same thing applies here, have the game logic set restrictions.

An example query can be as simple as: `select ItemName, ItemImageUri from Items where ItemLevel < 15`
> 1 votes

---
Tags: databases
---


title: Attack Targetted Enemy Only

text:
# Question
Title: Attack Targetted Enemy Only
I have a perfectly working targetting script and I want to be able to deal damage to my currently selected enemy. I have a targetting script which is below:?

```
public GameObject enemy;
public List<Transform> targets;
public Transform selectedTarget;
public string targetTag = "Enemy";
private Transform myTransform;
private enemyHealth eHealth;

//Use this for initialization
void Start () {
    targets = new List<Transform>();
    selectedTarget = null;
    myTransform = transform;
    AddAllEnemies();
    eHealth = GetComponent<enemyHealth>();
}

public void AddAllEnemies() {
    GameObject[] go = GameObject.FindGameObjectsWithTag(targetTag);
    foreach(GameObject enemy in go) {
        AddTarget(enemy.transform);
    }
}

public void AddTarget(Transform enemy) {
    targets.Add(enemy);
}

private void SortTargetsByDistance() {
    targets.RemoveAll(target => target == null);
    targets.Sort(delegate(Transform t1, Transform t2) {
        return (Vector3.Distance(t1.position,    myTransform.position).CompareTo)
            (Vector3.Distance(t2.position, myTransform.position));
    });
}

private void TargetEnemy() {
    if(selectedTarget == null) {
        SortTargetsByDistance();
        selectedTarget = targets[0];
    } else {
        int index = targets.IndexOf(selectedTarget);
        if (index < targets.Count -1) {
            index++;
        } else {
            index = 0;
        }

        DeselectTarget();
        selectedTarget = targets[index];
    }
    SelectTarget ();
}

private void SelectTarget() {
    selectedTarget.GetComponent<Renderer> ().material.color = Color.red;

    enemyHealth eh = (enemyHealth)GetComponent("EnemyHealth");
    eh.target = enemy;
}

private void DeselectTarget() {
    selectedTarget.GetComponent<Renderer>().material.color = Color.blue;
    selectedTarget = null;
}

//Update is called once per frame
void Update ()
{
    if (Input.GetKeyDown (KeyCode.Tab)) {
        TargetEnemy ();
    }
}

```

and I have my enemyHealth script which is where I am handling the health and also dealing damage.

```
public float eHealth = 100;
public Slider EnemyHealth;
public GameObject target;

private float MHCD; // MeleeHit CD

void Start () {
    EnemyHealth = GetComponent<Slider> ();
}

public void MeleeHit() {

    float distance = Vector3.Distance (target.transform.position, transform.position);

    Vector3 dir = (target.transform.position - transform.position).normalized;

    float direction = Vector3.Dot (dir, transform.forward);

    if (distance < 4) {
        if (distance > 0) {
            eHealth -= Random.Range (4, 9);
            EnemyHealth.value = eHealth;
        }
    } else {
        Debug.LogWarning ("You are too far away!");
    }
    Debug.Log (eHealth);
}

void Update() {

    if (Input.GetKeyDown (KeyCode.Alpha1) && Time.time - MHCD > 1) {
        MeleeHit ();
        MHCD = Time.time;
    }

```

does anyone know how I can link the two so I am only dealing damage to my selectedTarget?

What the code is currently doing is attacking all enemies instead of just 1. I need it to only attack the selectedTarget until I switch to the others.

# Answer
> 0 votes
In the following snippet `eh` is being set to a null value.

```
private void SelectTarget() {
    selectedTarget.GetComponent<Renderer> ().material.color = Color.red;

    enemyHealth eh = (enemyHealth)GetComponent("EnemyHealth");
    eh.target = enemy;
}

```

This is due to typo in the name of the class. Try using this instead:

```
enemyHealth eh = (enemyHealth)GetComponent("enemyHealth");

```

---

To avoid this kind of error in the future I suggest:

1. Using a consistent naming scheme e.g. all types use CamelCase.
2. Use the generic form of `GetComponent()` as it allows compile time type checking:

```
enemyHealth eh = GetComponent<enemyHealth>();

```

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


title: Issue with in game replay system

text:
# Question
Title: Issue with in game replay system
I am creating a game in Unity 3D and I have recently come up with my own simple replay system. It works well except for one small problem: it doesn't always start off where I would prefer it to in the recording of the gameplay. Basically every replay should be 8 seconds long. All I am doing for my replay system is storing the position and rotation of all objects in the scene, since there are only a few, in an array and then playing them back once an even is triggered.

I have the logical idea of how I should pick a starting point for the replay to start playing. I have a counter that increments every time my StorePosition() function is called in FixedUpdate(). That counter essentially gives me the number of indexes in the array so I know how many positions have been stored in total. All I should have to do is take that number and subtract from it the number of iterations that would occur during the 8 second replay.

My issue is that if I do the math for this: FixedUpdate() is called every .02 seconds which equates to 50 calls per second which would mean FixedUpdate() should be called 400 times over the time of my replay. So should I just be taking that total length of the stored positions array and subtracting that 400 and that would be the starting position in the array to start my replay?

That is the way I work it out in my head but it doesn't seem to work out quite right in the game. My counter seems to get into the 4000s or more over the 8 second replay so just subtracting the 400 from it doesn't give me anywhere near the amount of the replay that I want to see.

Is my logic flawed here? Any ideas?

**2/21/2016**

Here is some code for an example of how I handle this:

```
static Dictionary<GameObject, Vector3[]> positions = new Dictionary<GameObject, Vector3[]>();
public static int positionFillLength = 0;
static int index = 0;

public void StorePositions(GameObject[] objects)
{
    foreach (var obj in objects)
    {
        if (obj != null)
        {
            if (!positions.ContainsKey(obj))
                positions.Add(car, new Vector3[10800]);
            positions[car][index] = car.transform.position;
            positionFillLength++;
            index++;
        }
    }
}

public void PlayReplay(int index, GameObject[] gobjects)
{
    foreach (var obj in positions)
    {
        if (Array.IndexOf(gobjects, obj.Key) > -1)
        {
            if (positions[obj.Key][index] != Vector3.zero)
            {
                gobjects[Array.IndexOf(gobjects, obj.Key)].transform.position = positions[obj.Key][index];
            }
        }
    }
}

```

So if I am storing values I just call StorePositions() at ever call of FixedUpdate() and send in the objects to get the positions of.

When it is time to play a replay, I just start calling PlayReplay(). I create an index that starts at size 0 and increments every time that PlayReplay is called, which will also be every time FixedUpdate() is called, and pass that along with the objects into PlayReplay().

# Answer
> 1 votes
Loos like the problem is here:

```
public void StorePositions(GameObject[] objects)
{
    foreach (var obj in objects)
    {
        if (obj != null)
        {
            if (!positions.ContainsKey(obj))
                positions.Add(car, new Vector3[10800]);
            positions[car][index] = car.transform.position;
            positionFillLength++; // <-- these lines
            index++;              // <--
        }
    }
}

```

`positionFillLength` and `index` are being incremented once *for every object* getting a position update, instead of once per update of the complete set of objects.

That means if you have 10 objects, then in the first `FixedUpdate()` pass, one gets its position stored in index 0, the next gets its position stored in index 1.... until by the end of the frame `index` and `positionFillLength` are both 10, even though you've only stored one position for each object. By the second `FixedUpdate` you're up to 20... By 8 seconds in (400 FixedUpdates) you're up to around the 4000th index, exactly as you describe.

You end up leaving strides of 9 empty entries between valid position stores in each array.

Try moving the incrementing of `positionFillLength` and `index` to the bottom, outside of the `foreach` loop.

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


title: unity webgl not working on server

text:
# Question
Title: unity webgl not working on server
I own the servers of hokuco.com, I am wondering why my test build(not a development build) is not working in webgl I tried a test run as a .exe and it works fine. here is the url to my webgl project, can you determine what is wrong? http://hokuco.com/test/index.html (no files on my server are blocked, feel free to view the .htacess, js and other files) the screen is black and nothing is happening. .htacess:

```
Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTP:Accept-encoding} gzip
RewriteRule (.*)Release(.*)\.js $1Compressed$2\.jsgz [L]
RewriteRule (.*)Release(.*)\.data $1Compressed$2\.datagz [L]
RewriteRule (.*)Release(.*)\.mem $1Compressed$2\.memgz [L]
RewriteRule (.*)Release(.*)\.unity3d $1Compressed$2\.unity3dgz [L]
AddEncoding gzip .jsgz
AddEncoding gzip .datagz
AddEncoding gzip .memgz
AddEncoding gzip .unity3dgz
```

all my js files seem to be blocked.(but not jsgz...)

# Answer
> -1 votes
just simply delete the .htacess file

---
Tags: webgl
---


title: Tile collision detection

text:
# Question
Title: Tile collision detection
Right. So I was making this simple game. The player is two tiles wide, and four tiles high. My current code is really buggy (it was better before my rewrite)

Here it is:

```
    float newx = position.x + velocity.x;
    float newy = position.y + velocity.y;

    int tx = (int) newx;
    int ty = (int) newy;

    Tile tile = WorldHandler.currentWorld.getTile(tx, ty);
    Tile ground = WorldHandler.currentWorld.getTile((int) position.x, (int) position.y-1);

    if (tile.type == 0) {
        position.x = newx;
        position.y = newy;
    }
    if (ground.type != 0) {
        grounded = true;
        //position.y = Math.round(position.y);
    }

    if (grounded) {
        velocity.x = 0.0f;
        velocity.y = 0.0f;
        //position.y = Math.round(position.y);
    } else {
        velocity.x = velocity.x * (1.0f - Math.min(0.1f, 1.0f));
        velocity.y += 0.0f;
    }

```

it basically uses the indices for performance.

But I need a decent collision detection system that wouldn't be painful to implement, would AARBs be of use here? Also, the game loop is a tick based one, it runs at 30 ticks/s.

# Answer
It is not clear what shape your tiles are. If they are all rectangles, just use the *contains* method. Check for collisions in your *running* or *present* methods (whichever to call the ongoing loop).

If you have different shaped tiles, you could try using methods like the following:

```
public static boolean overlapCircles(MyCircle c1, MyCircle c2) {
    float distance = c1.center.distSquared(c2.center);
    float radiusSum = c1.radius + c2.radius;
    return distance <= radiusSum * radiusSum;
}

public static boolean overlapRectangles(MyRect r1, MyRect r2) {
    if(r1.lowerLeft.x < r2.lowerLeft.x + r2.width &&
            r1.lowerLeft.x + r1.width > r2.lowerLeft.x &&
            r1.lowerLeft.y < r2.lowerLeft.y + r2.height &&
            r1.lowerLeft.y + r1.height > r2.lowerLeft.y)
        return true;
    else
        return false;
}

public static boolean overlapCircleRectangle(MyCircle c, MyRect r) {
    float closestX = c.center.x;
    float closestY = c.center.y;
    Log.i("in overlap tester", "");

    if(c.center.x < r.lowerLeft.x){
        closestX = r.lowerLeft.x;
        Log.i("in x", "");
    }
    else if(c.center.x > r.lowerLeft.x + r.width){
        closestX = r.lowerLeft.x + r.width;
    }

    if(c.center.y < r.lowerLeft.y){
        closestY = r.lowerLeft.y;
    }
    else if(c.center.y > r.lowerLeft.y + r.height){
        closestY = r.lowerLeft.y + r.height;
    }

    return c.center.distSquared(closestX, closestY) < c.radius * c.radius;
}

```

In the main part of the game I called them using:

```
private boolean collideWithEnemy() {
    boolean hit = false;
    MyCircle playerCir = new MyCircle(player.pPos[0], player.pPos[1], 5);
    MyCircle en1Cir = new MyCircle(en1.pos[0], en1.pos[1], 10);
    hit = OverlapTester.overlapCircles(playerCir, en1Cir);

    //If the hit was true for en1 without the if it would turn it false.
    if (!hit) {
        MyCircle en2Cir = new MyCircle(en2.pos[0], en2.pos[1], 10);
        hit = OverlapTester.overlapCircles(playerCir, en2Cir);
        if(!hit) {
            MyRect en3Rect = new MyRect(en3.pos[0], en3.pos[1], 20, 20);
            hit = OverlapTester.overlapCircleRectangle(playerCir, en3Rect);
            if(hit) {
                en3.pos[0] = -20;
            }
        }
    }
    return hit;
}

```
> 1 votes

---
Tags: java, 2d, lwjgl, tilemap, platformer
---


# Question
Title: How To Destroy Instantiated GameObjects Using A Coroutine?
So I am making a Super Mario Bros. Clone and I am in the process of adding the mechanic of when the player hits the bottom of a block a coin instantiates directly above the block, waits for a second or two, then destroys itself and adds the value of that coin to the score.

With this script, everything is working besides the coroutine destroying the instantiated gameObject.

```
   using UnityEngine;
   using System.Collections;

public class BrickBlock : MonoBehaviour
{

    public GameObject CoinPrefab;
    public GameObject spawnPoint;
    public int CoinCount = 1;

    IEnumerator OnTriggerEnter2D()
    {
            if (CoinCount != 0)
            {
                Instantiate(CoinPrefab, spawnPoint.transform.position, spawnPoint.transform.rotation);
                yield return new WaitForSeconds(2);

                Destroy(CoinPrefab);
                CoinCount--;
                ScoreManager.score += Coin.CoinValue;

            }

            if (CoinCount == 0)
            {
                print("Bitch you're breaking me!");

            }
        }
    }

```

I recieve an error "Destroying assets is not permitted to avoid data loss. If you really want to remove an asset use DestroyImmediate (theObject, true); UnityEngine.Object:Destroy(Object) c\__Iterator0:MoveNext() (at Assets/Scripts/BrickBlock.cs:18)" but doing this simply destroys my prefab all together.

In the past, numerous of my questions have received thumbs down with little to no explanation why. If my question does not meet the standards of this forum or fails to provide enough information Please inform me. My problem may seem premature to some of you, but I am truly unable to solve this problem with my current frame of view. Your help is much appreciated.... Thank you:)

# Answer
A small concept, often not clear to the people.

Man your `CoinPrefab` is only a public reference (a blueprint) of an object, you can create a new object through this, but cannot pick that new object directly through this public reference.

What are you doing which is wrong,

* You are instantiating an object using `CoinPrefab` but didn't assign to any variable.
* You are destroying `CoinPrefab` which is actually never created.

What you should do,

* Instantiate object and assign that in any new variable so you can keep the record.
* Destroy with that new reference.

```
........
GameObject coin = Instantiate(CoinPrefab, spawnPoint.transform.position, spawnPoint.transform.rotation) as GameObject;
yield return new WaitForSeconds(2);

Destroy(coin);
..........

```
> 3 votes

---
Tags: unity
---


title: Camera bounds on different resolutions

text:
# Question
Title: Camera bounds on different resolutions
I tried to search different solutions but also due to the lack of knowledge in camera handling I found none fitting my needs.

The situation is the following.

I have a 2d game structured in rectangular rooms and I want the camera to always have the whole room visible in the screen despite the screen resolution and the room bounds.

Any clue?

Edit: Sorry for really bad painting, this is what I'd like to achieve somehow.

The camera viewport is where, inside the screen, the game will flow. everything else will be static, like a GUI frame with general informations and commands.

# Answer
You can't restrict the camera to a rectangular area in all resolutions/aspect ratios without either distorting the image.. or cropping out the area around it.

If cropping is the way you are looking to go, take a look at:

http://www.jgallant.com/restricting-2d-camera-zoom-and-movement-to-an-image-in-unity-csharp/
> 1 votes

---
Tags: unity, camera, unityscript
---


# Question
Title: Unity Editor Scene View does not match built executable
I'm trying to make my game resolution independent. I'm using Unity's 4.6 UI, and I've got custom resolutions defined at 1280 x 720, 1600 x 900, and 1920 x 1080. In-editor, if I swap between any of these resolutions, the observed scene doesn't change. It looks like this:

I then build an executable (set to only allow 16x9 resolutions), and run this scene. On 1280 x 720 (as selected from the resolution dialog), I get this:

While on 1920 x 1080 (as selected from the resolution dialog), I get this:

Which matches the editor view. (Ignore the character sprites; those are in worldspace on a separate camera and aren't relevant to this question).

What is it about the executable that causes lower resolutions to be "zoomed in" like this, even if that lower resolution is the Reference Resolution for the Canvas Scaler?

# Answer
> 1 votes
This appears to be a bug specific to the version of Unity I was using (5.3.1f1.).

After updating, the scaling began working as expected.

---
Tags: unity, resolution, ui-design
---


# Question
Title: How to determine size of art assets for Unity UI?
Previously when I made games, I used ui assets from the asset store. Working with those assets was easy as the backgrounds were plain. However, I'm now working on a game where custom graphics are used for UI. So, I need to specify size of backgrounds,icons etc to the art team. I understand how aspect ratio works with regards to unity camera, but having trouble understanding the relation between camera size and Canvas. For example, for a camera size of 4.6, an image size of 517X920 will cover the whole screen in 9:16 aspect. However, the same image is considerably larger when used as UI image under the Canvas. Can someone please help me understand how Canvas deals with image sizes?

# Answer
Ok. First I had to chose a screen size I'm designing for. I chose 768X1024. Gave artists this as reference, and they created all elements wrt this size. Next, in Unity, I set 768X1024 as reference resolution for Canvas. So, everything looked just like the artists had designed.
> 1 votes

---
Tags: unity
---


title: 2D sunrise in Unity

text:
# Question
Title: 2D sunrise in Unity
I see a lot of guides on how to create sunrise in 3D space, but I can't find much information on how to do it in 2D. In 3D, you rotate a lightsource around itself, but in 2D, I need to move the object from the bottom of the screen to the top of the screen and reset it.

I can make a day cycle and position the sun sprite at the top right corner like this:

```
using UnityEngine;
using System.Collections;

public class SunController : MonoBehaviour {

    [Range(0, 1)]
    public float currentTimeOfDay = 0;

    private Vector3 initialPosition;

    void Start ()
    {
        // Set initial position
        initialPosition = new Vector3 (.9f, .9f, 10 /* camera is at -10 */);
        transform.position = Camera.main.ViewportToWorldPoint(initialPosition);
    }

    void Update () {

        currentTimeOfDay += (Time.deltaTime / 120) * 1;

        if (currentTimeOfDay >= 1)
            currentTimeOfDay = 0;
    }
}

```

When the timer hits 1, a day is completed.

I somehow need to map this to the top and bottom of the screen so when the timer is at ~0.5f (remember: it ranges from 0 to 1, but as a float with 7 decimals = 0.0000000 -\> 0.5709517 -\> 1.0000000), the sprite should be half way up the screen etc.

How would I go about doing this? I figure Mathf.Clamp might work here, but I can't get my head around it for this case.

Screenshot:

# Answer
I'd suggest using a sine or cosine curve to determine the position at the particular time. This would produce an output like,

Where the zero line is assumed to be ground level (so when the sun is below the ground it is not visible).

This also makes it relatively easy to adjust how much time is spent in night or day. Use

```
GetSunHeight(){
    currentTimeOfDay += Time.deltaTime;
    float dayFrequency = 1/dayLength;
    sunHeight = Mathf.Sin(currentTimeOfDay * 2 * Mathf.pi * dayFrequency);

}

```

This allows you to set the length per cycle. I.e. if `dayLength = 120` then a full day-night cycle should take 120 s.
> 3 votes

---
Tags: unity, 2d, physics, mathematics, viewport
---


# Question
Title: In the Unity Editor, how do I find prefabs containing a specific component?
I want to find all prefabs in the project that contain a specific `Component`?

I only need this in-editor; no need at runtime.

If they are in added to the `Scene`, I can right-click and *Find References in Scene*. However, this is entirely unhelpful since I have a lot of prefabs in the project which *aren't* added to the `Scene` and I'd need to search those too…

# Answer
Type this in the Project search bar and replace "MyBehaviour.cs" with the file name of your Component:

```
ref:Scripts/MyBehaviour.cs

```

WARNING: This search is slow, so it can take a very long time to find all of the objects. Be prepared to wait several seconds, minutes, perhaps even hours if you have a huge amount of prefabs.
> 4 votes

# Answer
LVBen is right, but there's another way that can be faster if you use the command line.

If Unity is set to store assets as text with metadata in .meta files, each script has a corresponding .meta file. At the top of this file is a GUID. Every scene/prefab/material/whatever that references that script contains that GUID somewhere in its text, so a full text search of assets will find all the objects that script is attached to.

This trick also works for other types, like textures and audio clips--it will find where they are linked in a serialized script field. You can make the search faster by narrowing it down to the specific file type you're interested in--for instance, only search \*.prefab and ignore scene files.

Note: I've occasionally seen this trick fail. Somehow Unity left old GUID text referring to scripts that had already been removed. Still, it's a big time safer if you're comfortable quickly finding files, seeing the contents, and doing full text searches through your project.
> 2 votes

---
Tags: unity
---


# Question
Title: Libgdx box2d bodies go through other bodies
I'm developing a game using libGDX and box2d. I am facing a problem that bodies go through each other... I'm moving the body using a TouchPad by setTransform. I think the problem is that I use setTransform.

# Answer
You have to use forces and impulses (physics) and the bodies will collide properly. I suggest you to do this like this:

```
body.applyForceToCenter(force.x*pad.getKnobPercentX(),force.y*pad.getKnobPercentY());

```
> -1 votes

# Answer
I can't add a comment, so I'm posting this as an answer. You should've provided some code. I had a similar issue, I was moving box2d bodies with `.setTransform`. When using box2d, it's recommended that you move bodies applying forces. I don't know if that's your problem, so you might want to check how you're moving the bodies in your game. This can be due to several other problems, I can't tell without any code. I'm just sharing a similar issue that I had.
> 0 votes

---
Tags: 2d, android, libgdx, box2d
---


# Question
Title: LibGDX Box2D texture on dynamic generated body
I'm creating a game that is similar to hill climb racing. I've generated the ground and now I want to add texture to the ground. Here is a screenshot of a game

Here is my code (I create ground using triginometry)

```
public class MyGdxGame extends ApplicationAdapter {
    private OrthographicCamera camera;
    private Box2DDebugRenderer renderer;
    private World world;
    private static final float width = 40;
    private static final float height = 30;
    private static final float camSpeed = 3.8f;
    private static final float SLICE_WIDTH = 2;
    private Body groundBody;
    private Body aa;
    private static final int PPM = 100;

    private EdgeShape slicePoly;
    private FixtureDef sliceFixture = new FixtureDef();

    float needToCreateStuff;

    private Car car;

    private QueryCallback deleteStuff = new QueryCallback() {
        @Override
        public boolean reportFixture(Fixture fixture) {
            final Body tmpBody = fixture.getBody();
            if (tmpBody == groundBody){
                groundBody.destroyFixture(fixture);
            }
            return true;
        }
    };

    @Override
    public void create() {
        renderer = new Box2DDebugRenderer();
        camera = new OrthographicCamera(width, height);
        camera.position.set(width / 2, 0, 0);
        camera.update();

        createPhysics();
    }

    @Override
    public void render() {
        update(Gdx.graphics.getDeltaTime());

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        renderer.render(world, camera.combined);
    }

    private void update(float delta) {
        handleInput(delta);

        world.step(delta, 6, 2);

        final float posX = camera.position.x - width / 1.5f;
        final float posY = camera.position.y;
        world.QueryAABB(deleteStuff, posX, posY - height / 2f, posX + SLICE_WIDTH, posY + height / 2f);
    }

    private void handleInput(float dt){
        float cameraMovement = camSpeed * dt;
        camera.position.x += cameraMovement*1f;
        //camera.position.x = car.getBodyX() * dt;

        generateStuff(cameraMovement, true);
        if(Gdx.input.isKeyPressed(Input.Keys.Z)){
            camera.zoom += .01;
        } else if(Gdx.input.isKeyPressed(Input.Keys.X)){
            generateStuff(cameraMovement, false);
            camera.zoom -= .01;
        }
        //camera.update();
    }

    private void generateStuff(float cameraMovement, boolean direction){
        if(direction){
            needToCreateStuff += cameraMovement;
            if (needToCreateStuff > SLICE_WIDTH) {
                needToCreateStuff -= SLICE_WIDTH;
                createSlice(camera.position.x + width / 2f - needToCreateStuff);
            }
        }
        camera.update();
    }

    private void createPhysics() {
        world = new World(new Vector2(0, -8.91f), true);
        BodyDef bodyDef = new BodyDef();
        groundBody = world.createBody(bodyDef);

        aa = world.createBody(bodyDef);
        slicePoly = new EdgeShape();

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.density = 5;
        fixtureDef.restitution = .3f;

        FixtureDef wheelFixtureDef = new FixtureDef();
        wheelFixtureDef.density = fixtureDef.density * 5.5f;
        wheelFixtureDef.friction = 0;
        wheelFixtureDef.restitution = .4f;

        car = new Car(world, fixtureDef, wheelFixtureDef, 0, 3, 3, 1.5f);
        Gdx.input.setInputProcessor(new InputMultiplexer(new InputAdapter(){}, car));

        for (float x = 0; x <= width; x += SLICE_WIDTH){
            createSlice(x);
        }
    }

    private float nextY;

    private void createSlice(float x) {
        float y = nextY;
        int high = 5;
        float nelygumas = 2 * x;
        float interval = 10 * x;
        nextY = 4f * MathUtils.sinDeg(nelygumas) + high * MathUtils.sinDeg(interval) * 1f;
        slicePoly.set(x, y, x + SLICE_WIDTH, nextY);
        sliceFixture.shape = slicePoly;
        sliceFixture.friction = 10;
        groundBody.createFixture(sliceFixture);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void dispose() {
        slicePoly.dispose();
        world.dispose();
    }

    @Override
    public void resize(int width, int height) {
    }
}

```

EDIT: I need to use this texture

# Answer
> 1 votes
I think I found a way to do it ...but I'm sure there is a more efficent way to do it! 1) You draw the texture all over the things you see on the screen ( only where the camera points at.

2) Then you iterate trough each point of the fixture of the ground and generate a Polygonshape made of the first point , the point that comes after it, and two points which have the same x coordinates but higher y coordinates. At the end you'll have a lot of polygons which you can contain in an array.

3) you render all the shapes with a shaperenderer black so you cover the texture that is not drawn on the ground!

ps. Do this passages only for the things which are seen on the screen to gain efficency,processor time and to prevent from nullpointerexceptions!!!!!! You could do this by checking each time you generate a polygon if the first points x coordinate is inside the screen if it isnt you simply break out the loop!

Hope I was helpful and ask for more explanations if you need some help!

---
Tags: libgdx, box2d, terrain-rendering
---


title: Character stuck on box collider 2.5D

text:
# Question
Title: Character stuck on box collider 2.5D
I'm having trouble with my character on a 2.5D platformer. The character get stuck if it collides without reaching the platform's top. Here is a gif showing it: http://i.imgur.com/jmZ6O1K.gifv

Both colliders (platform and character) has a physics material with no friction (or minimum). So I don't know why is this happening.

Character Collider

Physic Material

# Answer
This is just the way the physics engine works. You don't want to use physics for your character's control. Use the CharacterController instead.

An alternative (but messy) solution is to add a secondary/tertiary collider on the side of each platform and to make it frictionless. This can have unwanted side effects, extra work, and make you feel dirty.

My personal solution is to use Prime31's character controller for 2D, but if you are in 2.5D, I don't think this will work for you.

The reason this is happening is...well, I could make some assumptions, but that's all they would be. So I'll refrain. But imagine if you took a rubber ball and moved it up and towards a wall. It wouldn't just slide up. Anyways, the above solutions should work.
> 1 votes

---
Tags: unity, platformer, character, 2.5d
---


# Question
Title: Switched from immediate mode to VBOs, game runs slower
I'm trying to improve the draw performance on my `c++`, `OpenGL`, `SDL` game.

Back in school we mostly learned immediate mode, so that's how my drawing was originally implemented. When I started reading up online about improving performance, I read about `VBOs` and how they are 'so much better' and use the graphics card memory, etc.

So I took a couple of nights and converted to them. When I tested the game, it actually ran slower (draw method went from ~7 to ~10 ticks).

Did I do something wrong or are VBOs only more efficient in certain situations?

Here's my class for tessellated polygons after adding VBOs (my game draws a lot of flat 2D shapes in a 3D world, sort of papermario-style)

```
#include "Tesselator.h"

Tesselator::Tesselator(std::vector<b2Vec2> vertices, Gradient* gradient) {
    this->vertices = vertices;
    this->gradient = gradient;
    tesselator = gluNewTess();
    gluTessCallback(tesselator, GLU_TESS_BEGIN_DATA, (void(CALLBACK*)())beginCallback);
    gluTessCallback(tesselator, GLU_TESS_VERTEX_DATA, (void(CALLBACK*)())vertexCallback);
    gluTessCallback(tesselator, GLU_TESS_END, (void(CALLBACK*)())endCallback);
    int vertcount = (int)vertices.size();
    GLdouble vertarray[vertcount][3];
    for (int i = 0; i < vertices.size(); i++) {
        vertarray[i][0] = vertices[i].x;
        vertarray[i][1] = vertices[i].y;
        vertarray[i][2] = 0;
    }
    gluTessBeginPolygon(tesselator, this);
    gluTessBeginContour(tesselator);
    for (int i = 0; i < vertices.size(); i++) {
        gluTessVertex(tesselator, vertarray[i], vertarray[i]);
    }
    gluTessEndContour(tesselator);
    gluTessEndPolygon(tesselator);
    gluDeleteTess(tesselator);
    for (int i = 0; i < triangles.size(); i++) {
        triangleVBOs.push_back(new VertexBufferObject(triangles[i]));
    }
    for (int i = 0; i < trianglefans.size(); i++) {
        triangleFanVBOs.push_back(new VertexBufferObject(trianglefans[i]));
    }
    for (int i = 0; i < trianglestrips.size(); i++) {
        triangleStripVBOs.push_back(new VertexBufferObject(trianglestrips[i]));
    }
}
Tesselator::~Tesselator() {
    for (int i = 0; i < triangleVBOs.size(); i++) {
        delete triangleVBOs[i];
    }
    for (int i = 0; i < triangleFanVBOs.size(); i++) {
        delete triangleFanVBOs[i];
    }
    for (int i = 0; i < triangleStripVBOs.size(); i++) {
        delete triangleStripVBOs[i];
    }
    triangleVBOs.clear();
    triangleFanVBOs.clear();
    triangleStripVBOs.clear();
}
void Tesselator::draw(float z) {
    Drawing::applyZTranslation(z);
    for (int i = 0; i < triangleVBOs.size(); i++) {
        triangleVBOs[i]->draw(GL_TRIANGLES);
    }
    for (int i = 0; i < triangleFanVBOs.size(); i++) {
        triangleFanVBOs[i]->draw(GL_TRIANGLE_FAN);
    }
    for (int i = 0; i < triangleStripVBOs.size(); i++) {
        triangleStripVBOs[i]->draw(GL_TRIANGLE_STRIP);
    }
    Drawing::applyZTranslation(-z);
}
void Tesselator::addTriangle() {
    std::vector<b2Vec2> triangleVertices;
    triangles.push_back(triangleVertices);
}
void Tesselator::addTriangleFan() {
    std::vector<b2Vec2> triangleFanVertices;
    trianglefans.push_back(triangleFanVertices);
}
void Tesselator::addTriangleStrip() {
    std::vector<b2Vec2> triangleStripVertices;
    trianglestrips.push_back(triangleStripVertices);
}
void Tesselator::addVertex(b2Vec2 vertex) {
    if (currentType == GL_TRIANGLES) {
        triangles.back().push_back(b2Vec2(vertex.x, vertex.y));
    }
    else if (currentType == GL_TRIANGLE_FAN) {
        trianglefans.back().push_back(b2Vec2(vertex.x, vertex.y));
    }
    else if (currentType == GL_TRIANGLE_STRIP) {
        trianglestrips.back().push_back(b2Vec2(vertex.x, vertex.y));
    }
}
void CALLBACK Tesselator::beginCallback(GLenum type, GLvoid * tessdata) {
    Tesselator* tess = (Tesselator*) tessdata;
    tess->currentType = type;
    if (type == GL_TRIANGLES) {
        tess->addTriangle();
    }
    else if (type == GL_TRIANGLE_FAN) {
        tess->addTriangleFan();
    }
    else if (type == GL_TRIANGLE_STRIP) {
        tess->addTriangleStrip();
    }
}
void CALLBACK Tesselator::vertexCallback(GLdouble* vertex, GLvoid* tessdata) {
    Tesselator* tess = (Tesselator*) tessdata;
    tess->addVertex(b2Vec2(*(vertex), *(vertex + 1)));
}
void CALLBACK Tesselator::endCallback() {
}

```

and here is my vertex buffer object class

```
#include "VertexBufferObject.h"

VertexBufferObject::VertexBufferObject(std::vector<b2Vec2> shapeVertices) {
    numberOfCoordinateValues = 0;
    for (int i = 0; i < shapeVertices.size(); i++) {
        numberOfCoordinateValues = numberOfCoordinateValues + 2;
    }
    float coordinateValues[numberOfCoordinateValues];
    int coordinateValueArrayIndex = 0;
    for (int i = 0; i < shapeVertices.size(); i++) {
        coordinateValues[coordinateValueArrayIndex] = shapeVertices[i].x;
        coordinateValueArrayIndex++;
        coordinateValues[coordinateValueArrayIndex] = shapeVertices[i].y;
        coordinateValueArrayIndex++;
    }
    glGenBuffers(1, &id);
    glBindBuffer(GL_ARRAY_BUFFER, id);
    glBufferData(GL_ARRAY_BUFFER, sizeof(coordinateValues),     coordinateValues, GL_STATIC_DRAW);
}
VertexBufferObject::~VertexBufferObject() {
    glDeleteBuffers(1, &id);
}
void VertexBufferObject::draw(GLenum mode) {
    glBindBuffer(GL_ARRAY_BUFFER, id);
    glVertexPointer(2, GL_FLOAT, 0, NULL);
    glEnableClientState(GL_VERTEX_ARRAY);
    glDrawArrays(mode, 0, numberOfCoordinateValues/2);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

```

and heres what the draw method for Tesselator used to look like before adding VBOs

```
void Tesselator::draw(float z) {
    for (int i = 0; i < triangles.size(); i++) {
        Drawing::drawTriangles(triangles[i], z, gradient);
    }
    for (int i = 0; i < trianglefans.size(); i++) {
        Drawing::drawTriangleFan(trianglefans[i], z, gradient);
    }
    for (int i = 0; i < trianglestrips.size(); i++) {
        Drawing::drawTriangleStrip(trianglestrips[i], z, gradient);
    }
}

```

and in Drawing.cpp:

```
void Drawing::drawTriangles(std::vector<b2Vec2> vertices, float z, Gradient* gradient) {
    glBegin(GL_TRIANGLES);
    for (int i = 0; i < vertices.size(); i++) {
        addVertex(vertices[i].x, vertices[i].y, z, gradient);
    }
    glEnd();
}
void Drawing::drawTriangleFan(std::vector<b2Vec2> vertices, float z, Gradient* gradient) {
    glBegin(GL_TRIANGLE_FAN);
    for (int i = 0; i < vertices.size(); i++) {
        addVertex(vertices[i].x, vertices[i].y, z, gradient);
    }
    glEnd();
}
void Drawing::drawTriangleStrip(std::vector<b2Vec2> vertices, float z, Gradient* gradient) {
    glBegin(GL_TRIANGLE_STRIP);
    for (int i = 0; i < vertices.size(); i++) {
        addVertex(vertices[i].x, vertices[i].y, z, gradient);
    }
    glEnd();
}

```

# Answer
> -1 votes
> glBegin(GL\_TRIANGLES);

You ar still using old school glBegin/glEnd for drawing, this is not going to be faster.

You need to bind the buffer, push data to the VBO after changing it, and then draw with said buffer. This will most likely decrease your drawtime. Also, try and find geometry that does not change and create a static VBO for all that data, push it to the gpu. Now you only need to bind the buffer and draw it.

\[1\] - https://en.wikipedia.org/wiki/Vertex\_Buffer\_Object

# Answer
> -1 votes
A lot of people think, that every aspect of the VBOs are fast, that's not really true. Binding a VBO is very slow. Always make sure, you bind VBOs one time, then render the same model multiple times with different position, rotation, etc.

---
Tags: opengl, c++, optimization, vbo, hardware-acceleration
---


title: How to visually represent a time span?

text:
# Question
Title: How to visually represent a time span?
I am making a puzzle game. The puzzle in question needs to be solved in advance, with the final solution being given as a series of commands which will instruct an object to navigate a maze.

This means I need to be able to provide all the clues necessary in advance, as pure trial-and-error will be tedious for the player.

When it comes to rotation and distance, this is no problem. Rotation is visually obvious, and I can use regularly sized and evenly spaced blocks/objects for the player to count to work out distance.

However - my problem is finding a similar visual representation for time. At one point, the player will ride a lift/platform to 'a place', where the destination will be X seconds away. The player needs to wait this X seconds before continuing forward.

How can I communicate that time delay in an interesting/thought provoking way? I don't want signs next to each lift that simply state the time it will take.

# Answer
If I understand correctly, the player needs to 'program' a course through a level. The program will be executed once the player has plotted the entire course (basically the solution to the level).

My solution would be to make a 'wait' command that is context sensitive. Having the player guess the time seems not what you want, since they would end up finding the solution by process of elimination. So you instead you could provide the solution right there: either tell the player exactly how long it will take, or simply take that out of the equation.

So either context sensitive action near/on a platform like "wait for arrival," or have the player 'connect' the wait command to a triggering event:

* Connect to a platform and mark a spot.
* Connect to a guard and wait for the guard to be in a certain spot.
* Connect to a button that calls the elevator.
* And so on...
> 3 votes

# Answer
Just pop out flash-and-fade countdown numbers to the screen. So you keep player's attention for a little more time while he is waiting.

These numbers are not necessarily should be huge and centered, you can simply show numbers at right-top, or whatever you want actually.
> 0 votes

---
Tags: game-design, puzzle
---


# Question
Title: How can I pool objects with differing properties?
My game requires a 2D GameObject to be spawned every second until they fill the whole screen and the game ends (around 60 objects total). On Android I see some performance spikes whenever a GameObject is spawned, so I'd like to use object pooling to help alleviate this. However, some of my objects have random properties like a second sprite, different tag, particle effect, and so on, so I don't think it's possible to save them for object pooling.

Is there any way for me to pool objects that have variable properties?

# Answer
> 2 votes
This is how I pool objects in Unity.There are other techniques, and I am sure you can probably find an asset in the unity store, however, this is my preferred method up to now.

First, we need a Pool class, that will allow us to fetch/return/manage our pooled objects:

```
using System.Collections.Generic;

public class Pool<T> where T : new()
{
    public struct Node
    {
        internal int Index;
        public T Item;
    }

    private Node[] pool;
    private bool[] active;
    private Queue<int> available;

    public int AvailableCount
    {
        get { return available.Count; }
    }

    public int ActiveCount
    {
        get { return pool.Length - available.Count; }
    }

    public int Count
    {
        get { return pool.Length; }
    }

    public Node[] Nodes
    {
        get { return pool; }
    }

    public Pool(int capacity)
    {
        if (capacity <= 0)
        {
            return;
        }

        pool = new Node[capacity];
        active = new bool[capacity];
        available = new Queue<int>(capacity);

        for (int i = 0; i < capacity; i++)
        {
            pool[i] = new Node();
            pool[i].Index = i;
            pool[i].Item = new T();

            active[i] = false;
            available.Enqueue(i);
        }
    }

    public Node Get()
    {
        int index = available.Dequeue();
        active[index] = true;
        return pool[index];
    }

    public void Return(Node item)
    {
        if ((item.Index < 0) || (item.Index > pool.Length))
            return;

        if (!active[item.Index])
            return;

        active[item.Index] = false;
        available.Enqueue(item.Index);
    }

    public bool IsActive(int index)
    {
        if (active[index])
            return true;
        else
            return false;
    }
}

```

I like to store the GameObject inside of a none-MonoBehaviour class. The reason is that it allows you to adjust a GameObject without having to have an active GameObject present.

This class will manage an individual pooled GameObject.You are going to need one of these for each Prefab that you want to pool.

```
using UnityEngine;

public class PoolableGameObject
{
    public GameObject GameObject;

    private SpriteRenderer Background;
    private SpriteRenderer Foreground;

    public PoolableGameObject()
    {
    }

    public void Initialize()
    {
        GameObject = GameObject.Instantiate(Resources.Load("PrefabName")) as GameObject;

        Background = GameObject.transform.Find("Background").GetComponent<SpriteRenderer>();
        Foreground = GameObject.transform.Find("Foreground").GetComponent<SpriteRenderer>();
    }

    public void Set(Color foregroundColor, Color backgroundColor, float width, float height, Vector2 position)
    {
        GameObject.transform.position = position;
        GameObject.transform.localScale = new Vector2(width, height);

        Background.color = backgroundColor;
        Foreground.color = foregroundColor;

        GameObject.SetActive(true);
    }

    public void Return()
    {
        GameObject.SetActive(false);
    }
}

```

A usage example, you would first need to initialize your Pool.This pre-instantiates your GameObjects.You will want to do this during the loading phase of your game.

```
Pool<PoolableGameObject> PooledObjects;

private void InitPooledObjects()
{
    // Initialize a Pool with specified number of objects
    PooledObjects = new Pool<PoolableGameObject>(5000);

    // Pre-initialize each object (common properties)
    foreach (Pool<PoolableGameObject>.Node node in PooledObjects.Nodes)
    {
        node.Item.Initialize();
    }
}

```

Then, to use the GameObjects in your scene, you simply grab one from the pool, and set it:

```
// If a object is availabe, get one
if (PooledObjects.AvailableCount > 0)
{
    Pool<PoolableGameObject>.Node node = PooledObjects.Get();

    // Post-init special properties
    node.Item.Set((foregroundColor, backgroundColor, width, height, position);
}

```

To get rid of a Pooled object, you return it to the Pool for later use:

```
// Return to pool
node.Item.Return();
PooledObjects.Return(node.Item);

```

---
Tags: unity
---


# Question
Title: How do I deal with scale of the universe when generating a simulated universe?
I have a dataset of 100,000 actual stars. I wish to create a game where I can fly between the stars and fly up to them and click on them etc. How do I go about dealing with the problem of the scaling of the universe, even If I were to allow fast as light travel it would be too vast. Should I cluster my data and then implement a subtle sort of scaling to move around? Sorry for the broad question but I'm rather stuck at the moment.

# Answer
The only real problem you'll be fighting is floating point precision; only 6 digits. When you accumulate floating point error over astronomical distances, you get astronomical inaccuracy. This causes distant bodies to rapidly alternate between two or more places from frame to frame.

It's likely you'll have two coordinate systems and, in most cases, you'll need to avoid multiplying to move from the least-precise system to the greater.

USpace = universal scale - ok for fixed star coordinates; precision will be lost once during loading
CSpace = "in-system" scale - arbitrary

NO:
CSpacePosition = USpacePosition * ConversionFactor

YES:
USpacePosition = CSpacePosition / ConversionFactor

In other words, don't move your camera around the universe by light-years at a time and attempt to render the changes at a larger scale.

A large change in CSpace is a small, accurate, change in USpace:

**Re: comment:**
The ViewMatrix is actually just the camera's WorldMatrix, inverted. That means that whichever shader you are currently applying the ViewMatrix in, is already "un-moving" the objects (on the GPU). This is more efficient when you are rendering 1000's of objects with 1000's of WorldMatrices. For a relatively few number of high-detail models, you can afford to "un-apply" the camera's relative movement directly to the objects' WorldMatrix on the CPU, instead of applying it to the ViewMatrix, to be applied later, on the GPU. I'm not sure if there's a name for the technique, but you're really just storing/updating the high-detail models, pre-transformed in View/Camera-Space.

In the first pass, you'll feed in pre-View-Transformed spheres and they'll be rendered normally using whatever shaders are required (tess, glow, particle, etc.).

The second pass will feed the star coordinates loaded from your dataset directly to the shader (all 100k). This pass uses the same ViewMatrix with the (0,0) translation component replaced by the camera's USpace-position. The starfield shader *does* apply the ViewMatrix on the GPU, so the full list only needs to be uploaded once. ViewSpace is centered on the camera at (0,0) so, after the ViewMatrix is applied by the shader, each vertex becomes a direction away from the camera. You can, then, scale each direction vector down so their lengths are just inside the view frustum.

Starfield extra credit:
I doubt a 100k pointlist is going to give your GPU much trouble but, you may be able to increase performance using the GeometryShader. After applying the View matrix, scaling to the farplane, and applying the Projection matrix, all visible stars will have coordinates in the range of -1 to 1, depth 0 to 1. Emit vertices that fall inside those ranges and skip the rest. That's called GPU culling and should allow you to push your vertex count beyond rediculous.

**Edit2:**
> 8 votes

# Answer
Maybe you could divide your universe to allow travel at different levels and then "zoom" in to a more detailed level. I am thinking of concepts like quadrants and sectors or maybe areas of ownership. You could then apply different speed/time implementations for the travel. In a single player game/universe you can speed up time without any difficulties. If this is a multiplayer game then you would probably need to use FTL travel or implement gateways/jumpgates to provide instantaneous travel.
> 2 votes

# Answer
Nothing stops you from allowing players to go faster than the speed of light. Take a look at Space Engine(free) or Universe Sandbox to see how they do it.
> -2 votes

# Answer
Allow faster than light travel, or increase the speed of time during travel sections.
> -3 votes

---
Tags: unity, game-design, architecture
---


# Question
Title: Hybrid App - Game Encyclopedia Image Asset
An in-game encyclopedia usually consists of entries and images for things related to the game. For example, pokemon's pokedex. Image of Pokemon, text description and so on.

I've happen to encounter a road block of sorts making a game with an "encyclopedia". From my database, each row is one object with several columns as the different property of the objects. (I know that might sound like redundant information to some devs. Don't kill me pls. I'm just trying to be clear.)

It goes somewhere along the lines of:

```
Name | Rarity | Pattern | Collected
Ramen | Rarity 1 | 1 | Yes
Ramen | Rarity 1 | 2 | Yes
Ramen | Rarity 2 | 3 | Yes
Udon  | Rarity 5 | 1 | No

```

**So the issue here is this:** Game Encyclopedias tend to have a black silhouette for items you have yet to collect and it's colored in after you've collected it. Each item can have a 'pattern' on it, making it either differently colored or sparkling. Though, the shape remains constant.

Basically, the silhouettes can just be repeated for each item that is of the same type, for example, all "Ramen" items have the same silhouette so if they aren't collected yet, reuse same image. **I thought I could probably *tint* the images and have a base image (light gray of sort), but if I did that, the entire image tints, even the parts I wouldn't want it to**, which includes but is not limited to: white spaces (or transparent), the "bowl" part of the ramen image, possibly added on "sparkle effects" for even rarer items.

I'm currently attempting to achieve this in a game using the Ionic Framework because I recently got into hybrid apps; I think they are pretty fun to develop! And has since learnt angularjs and js in general. No idea the exact process that Cordova (phonegap) uses to convert all of this into android and iOS so I'm sort of looking out for three things:

1) How to link/pair/associate my database with my image asset? 2) How do I specifically tint certain parts of an object/Or overlay two objects over each other, one tinted and one base coloured. 3) Does it work on the mobile platform AFTER it compiles from js to Java. (Only working on android at the moment).

# Answer
> 1 votes
The first issue, if I understand it, is easy. Make transparent item tiles. If an item has been collected, your program draws the black silhouette. If it hasn't been collected draw a coloured image. Any patterns can be placed over the top. It is a lot simpler, and uses less processing power, to have separate images, rather than render them using different configurations. Just store these in a two-dimensional array. The patterns that are going to overlay the tiles can be stored separately ready to use -- just draw the pattern in the same place as the original tile. Your later questions are too broad. You need to say what framework/language you want to use and post some sample code

---
Tags: 2d, android, javascript, image
---


# Question
Title: How would I create a save function to my random generated game?
I'm making a 2D Tower Defense and currently looking into making a save feature. The problem is that my game is procedural generated (based on the rogue-like tutorial posted by Unity):

At runtime I generate a random amount (approx 7k) tiles of treasures, obstacles and different enemies at random locations. Some tiles will also be destructible and not exist when destroyed.

What should I do to save the position of each tile and values such as "Level" and "Gold"?

This is a list of what I need to be saved:

* Player value (position, gold, level, health, inventory)
* Building values (Tower/Building positions, health value etc)
* Wave values (wave\_level)
* Board values (all tile positions such as obstacles, treasures etc)

NOTE: Every tile is a GameObject.

# Answer
> -1 votes
Random numbers in computing, in most cases, aren't actually that random, they are technically pseudo-random. What this means is that the random number generator starts with what is called a "seed". The seed determines the random numbers that are generated with each call to random, and given the same seed, you'll get the same random numbers for each call to random(), assuming you call it the same number of times after the seed.

If there are no other things that would make your application run differently (other than the random numbers), then by saving the seed used to initialize the random number generator, you'll get the same random numbers.

Normally, the random number generator will be seeded by something that is different for each user by default, something like the number of milliseconds since the device was booted. Instead, you can make sure that before you start generating random numbers you set the seed to something (and it can be something like the number of milliseconds since the device booted).

You can save that seed, and then re-generate all the same random numbers, which means you don't need to save them.

Another alternative would be to wrap the random call with something of your own that calls to random, and in that wrapped function, you can save the random number that was generated and play them back.

To see a bit more about how this works, search for srand(), which is the C function to set the seed for the random number generator. That documentation may help put you down the right path.

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