# Question
Title: How would I go about making a movement system like Mario Party?
## Main question

How would I go about getting a movement system similar to the one they have in Mario Party only minus the dice roll?

## Things I have researched

I have been studying the uses for \****arrays ,lists, for loops,onmousebuttondown\**** but I want to make a movement system where the player has a limited amount of spaces, clicks a tile, and then moves to it. I kind of have a vague idea of how to go about this and I kind of know what I need......and I kind of don't....basically my brain isnt working and kind of hit a road block... Thus far all I have is the board it self... I understand how to make the highlights work when the cursor moves over the tile ..... but the major thing I can't figure out is how I should actually get the player to move after I click on the tile with the mouse button and have the player only move in a limited range.

## Summary of things I'm looking for

Movement system kind of like mario party but minus the dice roll and instead of game board it would be on a grid

Players would only be able to move x amount of spaces both horizontally and vertically

Strictly for unity and **please put any code in c#**

Not looking for you to do my work but an example would be nice or at the very least point me in the right direction

Also, the board would be in a top down view but in 3d

I pretty much have an idea know what i need i just dont know the how to

**Im not looking for a way to highlight the board just the turn based movement system itself. I thought I was clear with my question but maybe not as clear as I thought I was\***

Picture of the grid on unity and an example of the turnbased movement system im looking for

```
using UnityEngine;
using System.Collections;

public class GridScript : MonoBehaviour {

    public Transform cellPrefab;
    public Vector3 Size;
    // Use this for initialization
    void Start () {
        CreatGrid ();

    }

    void CreatGrid (){

    for (int x = 0; x< Size.x; x++) {
        for (int z = 0; z< Size.x; z++) {
                Transform newCell;
            newCell = (Transform)Instantiate (cellPrefab, new Vector3 (x, 0, z), Quaternion.identity);
                newCell.name = string.Format ("({1},0,{1})",x,z);
                newCell.parent =transform;
                }
            }
        }
}

```

# Answer
> 1 votes
*Preface*

Ok, I feel like this question has two main parts; one to do with code design and one to do with code implementation. It is important to understand that what you want is pretty much an entire gameplay loop and so will require a fair bit of code (more than a single script). I will try to help you with the design of the code but I think that help with the implementation will require other more focussed questions.

*Different Scripts*

I think this would require several scripts and I would split the behaviour into the following,

1. `GameManager` \- this guy is in charge of the game, he says whose turn it is and what happens (e.g. gold pick-ups, events etc),
2. `BoardManager` \- this guy knows everything about the board, he knows the positions of all the tiles and how they translate to game space, as well as the positions of all the players (probably most complicated script here),
3. `Player` \- this is the player and includes all their information e.g. health, gold etc,
4. `Mover` \- this is the script which actually moves the player from `A` to `B`, he will get the path from the `BoardManager` then move the player,
5. `Inputs` \- this gets the inputs from the player and passes it to the other scripts.

*A Single Turn*

This is what I would want to happen in a single turn,

1. `BoardManager` calls function `StartTurn()` this
    * Tells `Inputs` that it is allowed to take inputs from the player,
2. `Inputs` then gets the input from the player, on a click it calls `GetMousePosition` now this
    * gets the position of the mouse and sends it to `BoardManager`
3. `BoardManager` uses this position to determine which tile the player is trying to move to. It then checks if the move is allowed,
    * if the move is allowed it tells the `BoardManager` the player is moving and `Mover` how to move the player,
    * if the move is not allowed it reports back the `Inputs` that it wasn't valid, GoTo 2.
4. `GameManager` now knows the player is moving and tells `Inputs` to stop getting inputs from the player. `Mover` uses the directions from `BoardManager` to move the player around the board, once it finishes it tells the `GameManager`,
5. `GameManager` knows the player has stopped moving, the players turn is now over and the `GameManager` calls `EndTurn()` this,
    * tells `Inputs` which player it now controls,
    * calls `StartTurn()` GoTo 1.

This is how I would design the gameplay loop along with the main scripts and some of their functions I would use. I hope this helps you with your game as well as pointing out the broad scope of your question. If you want any clarification on parts of my question feel free to ask and I can add more information.

# Answer
> 0 votes
Actually this is like any tile based movement from a turn based strategy game.

You can simply flood fill the tiles from the selected character to find which should be highlighted.

Psuedo code:

```
Set<Tile> getTilesInRange(Character character, int range){

    Set<Tile> highlighted;
    highlighted.add (character.tile);
    Set<Tile> waveFront;
    waveFront.add (character.tile);
    for(int i = 0; i < range; i++){
        Set<Tile> nextWave;
        foreach(Tile tile in waveFront){
            foreach(Tile neightbour in tile.getNeighbours()){
                if(neightbour in highlighted) continue;

                highlighted.add(neighbour);
                nextWave.add(neighbour);
            }
        }
        waveFront = nextWave;
    }
    return highlighted;
}

```

# Answer
> -1 votes
1) Use Breadth First Search (BFS) to calculate the path http://en.m.wikipedia.org/wiki/Breadth-first\_search

2) Highlight path

3) Move the object

Pathfinding: http://theory.stanford.edu/~amitp/GameProgramming/AStarComparison.html

---
Tags: c#, unity, movement, grid, turn-based-strategy
---


# Question
Title: Having trouble with grouping in 3D Studio Max
I'm using 3D Studio Max 2012. I've got a simple mesh and several other polygons and I want to group everything all together. But the option is greyed out, I can't actually select 'Group' under the menus.

I've tried exploding and collapsing the mesh but nothing seems to work.

How can I group them together, what things can I do to try to diagnose the problem?

EDIT: My object hierarchy looks weird:

```
scene root:
 . object 1
model:
 - object 2 ... 99

```

# Answer
> 2 votes
3D Studio Max has issues when trying to group objects with different parents. In a way, it makes sense that objects with different hierarchies shouldn't be allowed to group together. However, from an unwary user's perspective, this is a frustrating, wtf, kind of "gotcha".

To fix it, simply correct the hierarchy.

# Answer
> 3 votes
select the objects you want to group. hit the unlink selection button (the broken chain icon) And than you can group.

# Answer
> 2 votes
Another workaround if you are in a rush, just highlight all the objects and create a 'selection set' this helps enough for me. Of course it depends what you intend to use them for once they are grouped...

---
Tags: 3dsmax
---


# Question
Title: What is best method for 2D pathfinding in procedural world?
I have been researching path-finding for 2D games and would like to create a system that allows A\* to perform as best as possible over a near infinite world. This system is intended to manage not only the player's character but other AI that would wander the world in search of resources.

So far I have made grid based A\* that I then modified into Theta\* to smooth out the path. But I would like to change that to use navmeshes so I can reduce as many nodes as possible. I have looked in to delaunay triangulation and fortune's algorithm for voronoi but am unsure how that works on a large scale where I would want to generate more navmesh as the world is explored.

I have also considered quadtrees but they seem slower then navmeshes.

So my main question is, what would work on a near infinite procedurally generated world? And what is fastest quadtrees or navmeshes? If navmeshes are faster, are polygons better than triangles?

Thanks for any help!

# Answer
> 8 votes
As you shall see, the spirit of this answer is that, in game programming, there is rarely a dead-on answer like A is always better than B. But let's dive a bit more into the details.

> So my main question is, what would work on a near infinite procedurally generated world?

Any would work. It depends on many other characteristics of your game, for example (but not exhaustively): will it have big open areas or will it be always packed with obstacles? Do you need information about the traversal cost of terrains everywhere or nowhere at all? As you see, that question is way too general to be answered.

> And what is fastest quadtrees or navmeshes?

First things first: quadtrees are not a specific path-finding search space type. They are, in your context, a spatial partitioning technique. It means, in your tile-based search space type, they allow you to group similar tiles into greater areas, to reduce the number of similar tiles.

So, whether searching trough quadtrees of nodes or navmeshes will be faster, it depends on how much reduction of the search space the quadtrees will achieve in your particualr types of maps. I.e. which will leave you with fewer nodes in the graph where path will be searched for. In practice, **in my experience**, it will be very rare that quadtrees will end up with fewer nodes than navmeshes, because where quadtrees offer their biggest advantage over simple tile-maps, i.e. open areas, is precisely where nvameshes excel too.

However, in the case of a procedural map where navmeshes have to be built on the fly, you have to also consider the cost of building it. That is particularly important because you will be erasing parts of the map from memory when they are out of scope and rebuilding them again when player gets closer. Which means, you will be generating and probably regenerating the path-finding maps (no matter if using tiles or navmeshes) all the time.

In that regard, quadtrees are much faster, no doubt. It will be much faster to construct the quadtree of tiles in the new map areas being generated than it will be to calculate the navmesh for such new area. That means, you have to take both things into account: the time it takes to build each solution on the fly and the time it takes to use each solution when finding paths. Both things can become a bottle-neck.

Which means that, ultimately, there is no a priori answer to that. It both depends on how the characteristics of your maps, so as always, you will have to try both and profile. Always profile! That is the only way you can be assure of what works best for *your specific game*.

> If navmeshes are faster, are polygons better than triangles?

If you are storing only the center triangles/polygons, than polygons will give you much smaller search spaces (i.e. faster to traverse when searching for a path) than triangle-based navmeshes. However, when storing just the centers, it becomes harder to smooth the path after searching the path (like Theta\* does in relation to A\*).

So, often other points are stored, like the vertices of triangles/polygons and even the middle point of triangles/polygons' edges. In these cases, it becomes unclear whether polygon-based navmeshes will still give you the desired less nodes than polygon-based navmeshes. It begins to depend on the characteristics of your map again. **My personal experience** is that, if you are storing vertices, middle-edges and centers of the triangles/polygons, than the narrower are the walkable areas, the better the navmeshes become. Conversely, the broader these areas are, the better the polygon based become.

But in general, polygon-based nvmeshes end up giving less nodes (i.e. being faster to serach for paths). On the other hand, again, in a procedually generated map, you can't forget the cost of bulding the navmesh. And it is much faster to generate triangle-based navmeshes than polygon-based.

> I would want to generate more navmesh as the world is explored

This will be particularly harder to implement with navmeshes than with tiles and quadtrees. Because than it becomes not only a problem of generating navmesh, but of updating dynamically the navmeshes that were already generated. It is feasible, but not easy to program (for instance, Unity's and Unreal's navmesh system do not come with the possibility of dynamic updates).

> I am unsure how that works on a large scale where I would want to generate more navmesh as the world is explored

No matter which technique you end up choosing, you will likely end up needing to implement it hierarchically. I mean, when maps currently on screen get bigger, the better way of making it faster to find a path is to give the algorithm less area to search. Take a look at this similar question and at its answers: What is the most appropriate path-finding solution for a very large proceduraly generated environment?

---
Tags: 2d, path-finding, procedural-generation, navmesh
---


# Question
Title: Is it possible to convert this if-else chain to switch-case? - Unity C#
Here is the code:

```
    if (Input.GetMouseButtonDown(leftMouseButton))
    {
        OnLeftMouseButtonDown();
    }
    else if (Input.GetMouseButton(leftMouseButton))
    {
        OnLeftMouseButtonHold();
    }
    else if (Input.GetMouseButtonUp(leftMouseButton))
    {
        OnLeftMouseButtonUp();
    }
    else if (Input.GetMouseButtonDown(rightMouseButton))
    {
        OnRightMouseButtonDown();
    }
    else if (Input.GetMouseButtonUp(rightMouseButton))
    {
        OnRightMouseButtonUp();
    }

```

So is it possible to convert this big chain to switch-case?

Thanks in advance.

# Answer
> 2 votes
Not really, no. Given what you are trying to do, your code looks OK to me.

Anything is possible really, but it would be pretty convoluted and ultimately be a silly thing to do. :)

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


# Question
Title: How to display multiple textures with OpenGL without a texture atlas
I tried to dig into OpenGL a bit to use in 2D games (mainly because of shaders). There are multiple tutorials out there showcasing how to display and blend textures, and that's fine. But i haven't found a single one that would teach how to display multiple textures at once. Now, I know that one of the popular methods is using a texture atlas and then, provided you have a well-done atlas, it's just a matter of assigning proper UVs to objects using the texture in vertices sent to a buffer array. However, how would one go about it if he didn't want to use a texture atlas. Modern OpenGL offers at least 70something texture units if my memory serves me right, that's something, but then you would have to bind different textures (and possibly end up with an outrageous amount of samplers) which would waste a lot of GPU's computing power. Let's consider the following screen, assuming that everything, including clouds, is a separate object using it's own texture

How, in pseudocode, should I handle displaying that "the proper way" without a texture atlas to get an effect like that? I experimented with rebinding textures etc. but none of that helped. Also, how shaders should look like because i don't think that having a sampler for every object is a way to go as well. Maybe something with a TEXTURE\_2D\_ARRAY, but if yes then how to use it properly? Again, what I'm looking at is just a list of steps i need to take to get an image like that written in a pseudocode. Thanks in advance!

# Answer
> 2 votes
For simple 2D games such as this it generally really isn't a big issue to keep rebinding individual textures. If it is starting to become an issue, you could do some simple sorting so that the renderer will bind each required texture once and draw all tiles that use that texture before continuing on to the next, effectively removing all redundant texture switches. Since most maps use one texture very often (look in the photo, most tiles in game are really just that generic blue sky texture and the ground textures).

Samplers aren't an issue either. Really, in the case above, you could create one sampler object and keep it bound.

I'm not really sure why you don't want to use a texture atlas, as they're pretty efficient, and require little-no texture switches. The only issue I can see would be floating point precision issues, which wouldn't really be a problem unless you have a ridiculous amount of tiles in one texture.

Here is a wiki page describing array textures: https://www.opengl.org/wiki/Array\_Texture

# Answer
> 0 votes
You just use separate texture images and use texture id's to associate them with your 2d models (or tiles not sure how that works in 2d opengl, i'm used to 3d opengl). And in your render pass you loop over each model and before drawing them you just bind the correct texture unit to the sampler.

---
Tags: opengl, 2d, textures
---


# Question
Title: Attack vs Defence and who is the winner?
I am in the process of creating a new simple game in mobile and I've spent several days on the following part.

For simplicity, let's say that I have two fighters. The only attribute of them is Attack and Defence. When the first attacks, the only thing that matters is the attack of him and the defence of the opponent. And vice versa.

They don't have equipment, items, stamina or health. Just Attack vs Defence.

**Example:**

* Fighter 1:

Attack:50, Defence: 35
* Fighter 2:

Attack 20, Defence: 80

The fighting process will be just a single attack which will determine the winner. So, no multiple attacks or rounds. I don't want to make it deterministic, but add a light version of unexpected. A fighter with lower attack will be able to win another fighter with higher defence (but of course not every time)

My first idea was to make it linear and call a uniform random number generator.

```
If Random() < att1 / (att1 + def2) {
    winner = fighter1
} else {
    winner = fighter2
}

```

Example with attack 50 and defence 80, the attacking fighter will have about 38% to win. However, it seems to me that the unexpected is too far and worst fighters will win a lot.

I was wondering how you have worked on similar situations.

P.S. I searched a lot in this QnA and other sources and I found similar questions mentioned as too broad for SE. But those have had many attributes, weapons, items, classes etc that could make it too complicated. I think my version is far simpler to fit it in the QnA style of the SE.

# Answer
If you want your fight results to be more predictable but not completely deterministic, have a *best of n* system.

Repeat the fight `n` times (where `n` should be an uneven number) and declare the combatant the winner who won more often. The larger your value for `n` the less surprise wins and losses you will have.

```
const int FIGHT_REPETITONS = 5 // best 3 of 5. Adjust to taste.

int fighter1wins = 0;
int fighter2wins = 0;

for (int i = 0; I < FIGHT_REPETITONS; I++) {

    If (Random() < att1 / (att1 + def2)) {
        fighter1wins++;
    } else {
        fighter2wins++;
    }

}

If (fighter1wins > fighter2wins) {
    winner = fighter1
} else {
    winner = fighter2
}

```

This system only works in the special case where a fight is a simple binary result of win or lose. When a combat has more complex results, like when the winner still loses some hit points depending on how close the win was, this approach doesn't work anymore. A more general solution is to change the way you generate random numbers. When you generate multiple random numbers and then take the average, the results will cluster near the center of the range and more extreme results will be more rare. For example:

```
double averagedRandom3() {
    return (Random() + Random() + Random()) / 3.0;
}

```

will have a distribution curve like this:

(picture courtesy of anydice \- a really useful tool for designing game mechanic formulas which involve randomness, not just for tabletop games)

In my current project I am using a helper-function which allows to set an arbitrary sample size:

```
double averagedRandom(int averageness) {
     double result = 0.0;
     for (var i = 0; i < averageness; i++) {
         result += Random();
     }
     return result / (double)averageness;
}

```
> 24 votes

# Answer
This is what I used to determine the winner of a battle in my Lords of Conquest Imitator applet. In this game, similar to your situation, there is just an attack value and a defense value. The probability that the attacker wins is greater the more points the attacker has, and less the more points the defense has, with equal values evaluating to a 50% chance of the attack succeeding.

# Algorithm

1. Flip a random coin.

1a. Heads: defense loses a point.

1b. Tails: heads loses a point.
2. If both defense and attacker still have points, go back to step 1.
3. Whoever is down to 0 points loses the battle.

3a. Attacker down to 0: Attack fails.

3b. Defense down to 0: Attack succeeds.

I wrote it in Java, but it should be easily translatable to other languages.

```
Random rnd = new Random();
while (att > 0 && def > 0)
{
    if (rnd.nextDouble() < 0.5)
        def--;
    else
        att--;
}
boolean attackSucceeds = att > 0;

```

# An Example

For example, let's say that att = 2 and def = 2, just to make sure that the probability is 50%.

The battle will be decided in a maximum of `n = att + def - 1` coin flips, or 3 in this example (it's essentially a best of 3 here). There are 2n possible combinations of coin flips. Here, "W" means the attacker won the coin flip, and "L" means the attacker lost the coin flip.

```
L,L,L - Attacker loses
L,L,W - Attacker loses
L,W,L - Attacker loses
L,W,W - Attacker wins
W,L,L - Attacker loses
W,L,W - Attacker wins
W,W,L - Attacker wins
W,W,W - Attacker wins

```

The attacker wins in 4/8, or 50% of the cases.

# The Math

The mathematical probabilities arising from this simple algorithm are more complicated than the algorithm itself.

The number of combinations where there exactly *x* Ls is given by the combination function:

```
C(n, x) = n! / (x! * (n - x)!)

```

The attacker wins when there are between `0` and `att - 1` Ls. The number of winning combinations is equal to the sum of combinations from `0` through `att - 1`, a cumulative binomial distribution:

```
    (att - 1)
w =     Σ     C(n, x)
      x = 0

```

The probability of the attacker winning is *w* divided by 2n, a cumulative binomial probability:

```
p = w / 2^n

```

Here is the code in Java to compute this probability for arbitrary `att` and `def` values:

```
/**
 * Returns the probability of the attacker winning.
 * @param att The attacker's points.
 * @param def The defense's points.
 * @return The probability of the attacker winning, between 0.0 and 1.0.
 */
public static double probWin(int att, int def)
{
    long w = 0;
    int n = att + def - 1;
    if (n < 0)
        return Double.NaN;
    for (int i = 0; i < att; i++)
        w += combination(n, i);

    return (double) w / (1 << n);
}

/**
 * Computes C(n, k) = n! / (k! * (n - k)!)
 * @param n The number of possibilities.
 * @param k The number of choices.
 * @return The combination.
 */
public static long combination(int n, int k)
{
    long c = 1;
    for (long i = n; i > n - k; i--)
        c *= i;
    for (long i = 2; i <= k; i++)
        c /= i;
    return c;
}

```

Testing code:

```
public static void main(String[] args)
{
    for (int n = 0; n < 10; n++)
        for (int k = 0; k <= n; k++)
            System.out.println("C(" + n + ", " + k + ") = " + combination(n, k));

    for (int att = 0; att < 5; att++)
        for (int def = 0; def < 10; def++)
            System.out.println("att: " + att + ", def: " + def + "; prob: " + probWin(att, def));
}

```

Output:

```
att: 0, def: 0; prob: NaN
att: 0, def: 1; prob: 0.0
att: 0, def: 2; prob: 0.0
att: 0, def: 3; prob: 0.0
att: 0, def: 4; prob: 0.0
att: 1, def: 0; prob: 1.0
att: 1, def: 1; prob: 0.5
att: 1, def: 2; prob: 0.25
att: 1, def: 3; prob: 0.125
att: 1, def: 4; prob: 0.0625
att: 1, def: 5; prob: 0.03125
att: 2, def: 0; prob: 1.0
att: 2, def: 1; prob: 0.75
att: 2, def: 2; prob: 0.5
att: 2, def: 3; prob: 0.3125
att: 2, def: 4; prob: 0.1875
att: 2, def: 5; prob: 0.109375
att: 2, def: 6; prob: 0.0625
att: 3, def: 0; prob: 1.0
att: 3, def: 1; prob: 0.875
att: 3, def: 2; prob: 0.6875
att: 3, def: 3; prob: 0.5
att: 3, def: 4; prob: 0.34375
att: 3, def: 5; prob: 0.2265625
att: 3, def: 6; prob: 0.14453125
att: 3, def: 7; prob: 0.08984375
att: 4, def: 0; prob: 1.0
att: 4, def: 1; prob: 0.9375
att: 4, def: 2; prob: 0.8125
att: 4, def: 3; prob: 0.65625
att: 4, def: 4; prob: 0.5
att: 4, def: 5; prob: 0.36328125
att: 4, def: 6; prob: 0.25390625
att: 4, def: 7; prob: 0.171875
att: 4, def: 8; prob: 0.11328125

```

# Observations

The probabilities are `0.0` if the attacker has `0` points, `1.0` if the attacker has points but the defense has `0` points, `0.5` if the points are equal, less than `0.5` if the attacker has less points than the defense, and greater than `0.5` if the attacker has more points than the defense.

Taking `att = 50` and `def = 80`, I needed to switch to `BigDecimal`s to avoid overflow, but I get a probability of about 0.0040.

You can make the probability closer to 0.5 by changing the `att` value to be the average of the `att` and `def` values. Att = 50, Def = 80 becomes (65, 80), which yields a probability of 0.1056.
> 8 votes

# Answer
You could modify the attack by a random number sampled from a normal distribution. This way most of the time the result will be what you expect, but occasionally a higher attack will lose against a lower defense or a lower attack will win against a higher defense. The probability of this happening will get smaller as the difference between attack and defense increases.

```
if (att1 + norm(0, sigma) - def2 > 0) {
  winner = fighter1;
}
else {
  winner = fighter2;
}

```

The function `norm(x0, sigma)` returns a float sampled from a normal distribution centered at x0, with standard deviation sigma. Most programming languages provide a library with such a function, but if you want to make it yourself have a look at this question. You would have to adjust sigma such that it 'feels right', but a value of 10-20 might be a good place to start.

For a few sigma values, the probability of victory for a given `att1 - def2` looks like this:
> 5 votes

---
Tags: mathematics, game-design, game-mechanics
---


title: C++: from LWJGL to C++ with OpenGL

text:
# Question
Title: C++: from LWJGL to C++ with OpenGL
I've been trying my best on porting my 3D game from Java to C++, but to no avail. I use only LWJGL with OpenGL but I cannot find any other library in C++ that supports as much as LWJGL does for Java. Especially on the math part.

For instance. I'm trying to port this TransformationMatrix maker to C++.

```
public static Matrix4f createTransformMatrix(Vector3f translation, float rx, float ry, float rz, float scale){

    Matrix4f newMatrix = new Matrix4f();
    newMatrix.setIdentity();
    Matrix4f.translate(translation, newMatrix, newMatrix);
    Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), newMatrix, newMatrix);
    Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), newMatrix, newMatrix);
    Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), newMatrix, newMatrix);
    Matrix4f.scale(new Vector3f(scale,scale,scale), newMatrix, newMatrix);

    return newMatrix;
}

```

I've tried using Eigen and GLM, but none of them work the same like LWJGL. Now I wouldn't mind this, but the lack of actual 3D tutorials on OpenGL in C++ is just abysmal.

Any tips or help with even converting this piece of code would be greatly appreciated.

# Answer
> 2 votes
You should check out this site: http://learnopengl.com/ That is how i transitioned from LWJGL to C++ You just use GLEW for the OpenGL functions, GLFW as windowing system and GLM as math library which is awesome. Any chance you started out with ThinMatrix's tutorials? That code looks familiar.

I'm also using Microsoft Visual Studio Community Edition as editor btw (its free).

As for your function, this code should work:

```
glm::mat4 transformationMatrix;

transformationMatrix = glm::translate(transformationMatrix, entity.getPosition());
transformationMatrix = glm::rotate(transformationMatrix, glm::radians(entity.getRotation().x),
            glm::vec3(1.0f, 0.0f, 0.0f));
transformationMatrix = glm::rotate(transformationMatrix, glm::radians(entity.getRotation().y),
            glm::vec3(0.0f, 1.0f, 0.0f));
transformationMatrix = glm::rotate(transformationMatrix, glm::radians(entity.getRotation().z),
            glm::vec3(0.0f, 0.0f, 1.0f));
transformationMatrix = glm::scale(transformationMatrix, entity.getScale());

shader->loadTransformationMatrix(transformationMatrix);

```

---
Tags: opengl, c++, java, mathematics, lwjgl
---


# Question
Title: OpenGL Applications Bring computer to halt
Whenever I run any application that utilizes the OpenGL interface, my entire computer comes to a halt, but it doesn't do this when it utilizes the DirectX interface. I run both Linux (Ubuntu 15.10) and Windows 10 so this isn't exactly caused by the operating system. I'm running the latest drivers from NVidia and both OS's are completely up to date. This is happening on a Dell Precision M6300 laptop (Core 2 Dou 2.5ghz, NVidia Quadro FX 1600M, 4gb ram) and although it's a bit old it should be completely capable of rendering a blank OpenGL window using GLFW, however it slows down my entire computer (every application starts freezing to where it becomes unusable until the application is closed). This happens in games like Left4Dead, Half-life 2, etc., but also in my own OpenGL programs. The same programs and games do not have the same effect on my desktop (although much better hardware, a blank OpenGL window shouldn't matter). Any help would be greatly appreciated, thank you. Also; my apologies if I left out any vital information or made a confusing question. Just ask me to clarify or add something and I shall.

; Added the code for the blank OpenGL window in question

```
#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
using namespace glm;

int main(int argc, char* argv[]) {
if ( !glfwInit() ) {
    fprintf(stderr, "Failed to initialize GLFW\n");
    return -1;
}

glfwWindowHint(GLFW_SAMPLES, 4); // 4x AA
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // GL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

GLFWwindow* window;
window = glfwCreateWindow(1024, 768, "OpenGL Tutorial", NULL, NULL);
if (window == NULL) {
    fprintf(stderr, "Failed to create OpenGL Window.");
    return -1;
}
glfwMakeContextCurrent(window);
glewExperimental=true;
if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initiate the glew context!");
    return -1;
}

glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

do {

    glfwSwapBuffers(window);
    glfwPollEvents();
} while (glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
    glfwWindowShouldClose(window) == 0);
}

```

# Answer
Some laptop's have 2 GPU's, one for applications that do not use much gpu functionality and one for games etc... This is for better power management. In my case my laptop has a GPU from Intel: Intel HD Graphics 3000 and one from Nvidia: Geforce GT 630M

For most applications it uses the intel one and for games it uses the nvidia one.

You can see if your laptop has this functionality if you right click on an application shortcut and have the option "run with graphics processor": \- "High performance NVIDIA processor" \- "Integrated graphics (default)"

The problem is that when you launch your opengl application in your editor (eclipse, microsoft visual studio, ...), those editor programs have been launched with the default integrated graphics which have a much lower OpenGL version. Normally this should cause your GLFW context creation to fail because it can't make one with version 3.3. Since it doesn't crash and just slows down your computer it's possible it's a whole other problem, but its worth looking into this and trying to make sure your editor program in which you run your code is using your fastest GPU.
> 1 votes

---
Tags: opengl, performance, windows, linux, lag
---


# Question
Title: Modern OpenGL project in c++ .obj loader
I want to create a class in c++ that loads a model with the obj format.The model gets generated from Blender(3D modeling program).When i try do draw something on the screen without the class(all the code is in main) it works fine.But somehow my class doesnt work.It only shows a black screen.Heres my code:

main.cpp

```
#include "global.h"

using namespace std;

int main()
{
    glewExperimental = GL_TRUE;
    glewInit();
    glViewport(0,0,800,800);
    mesh.loadMesh("models/1/cube.obj");
    shaders.push_back(Shader("shaders/default/default.vert", "shaders/default/default.frag"));

    while (window.isOpen())
    {
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        while (window.pollEvent(Event))
        {
            if (Event.type == sf::Event::Closed)
                window.close();
        }
        mesh.draw(shaders[0]);
        window.display();
    }
    return 0;
}

```

vertex shader

```
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texCoord;

void main()
{
    gl_Position = vec4(position.x, position.y, position.z, 1.0f);
}

```

fragment shader

```
#version 330 core

out vec4 color;

void main()
{
    color = vec4(1.0,0.0,0.0,1.0);
}

```

As you can see i dont use the normals and the textures yet..all i want for now is to draw something red on the screen.

The shader class its a class that i dowloaded from learnopengl.com .It just uses OpenGL standard fuctions to create a shader.Since my program works when i put everything in main,the shader class is not the problem.

and now the mesh class mesh.h

```
#ifndef MESH_H
#define MESH_H

#include "Includes.h"
#include "Shader.h"

struct Vertex
{
    glm::vec3 position;
    glm::vec3 normal;
    glm::vec2 texCoords;
    Vertex(glm::vec3 p,glm::vec3 n,glm::vec2 t)
    {
        position=p;
        normal=n;
        texCoords=t;
    }
};

struct Texture
{
    GLuint id;
    string type;
    string path;
};

class Mesh
{
    public:
        void draw(Shader &shader);
        void loadMesh(const char* fileName);
        void loadMaterials(const char* fileName);
    private:
        GLuint VAO, VBO, EBO;
        vector<Vertex> vertex;
        vector<GLuint> indices;
        vector<Texture> texture;
        void setupMesh();
};
#endif // MESH_H

```

and mesh.cpp

```
void Mesh::loadMesh(const char* fileName)
{
    int i,nrObj=-1,nr=0,number,number1,number2,number3;
    char text[256],matName[256];

    ifstream fin(fileName);

    vector<string>line;
    vector<glm::vec3>position;
    vector<glm::vec3>normal;
    vector<glm::vec2>texCoord;

    while(!fin.eof())
    {
        fin.getline(text,256);
        line.push_back(text);
    }
    //loadMaterials(line[2].c_str());

    glm::vec3 v;
    glm::vec2 t;

    for(i=4;line[i][0]=='v'&& line[i][1]==' ';i++)
    {
        sscanf(line[i].c_str(),"v %f %f %f",&v.x,&v.y,&v.z);
        position.push_back(v);
    }
    for(;line[i][0]=='v'&& line[i][1]=='t';i++)
    {
        sscanf(line[i].c_str(),"vt %f %f",&t.x,&t.y);
        texCoord.push_back(t);
    }
    for(;line[i][0]=='v'&& line[i][1]=='n';i++)
    {
        sscanf(line[i].c_str(),"vn %f %f %f",&v.x,&v.y,&v.z);
        normal.push_back(v);
    }
    for(;i<line.size();i++)
    {
        if(line[i][0]=='u'&&line[i][1]=='s'&&line[i][2]=='e')
            sscanf(line[i].c_str(),"usemtl %s",&matName);
        i++;
        if(line[i][0]=='s'&&line[i][1]==' ')
            i++;
        for(i;line[i][0]=='f'&&line[i][1]==' ';i++)
        {
            indices.resize(indices.size()+3);
            sscanf(line[i].c_str(),"f %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d",&number1,&number,&number,&number2,&number,&number,&number3,&number,&number);
            indices[nr*3]=number1-1;
            indices[nr*3+1]=number2-1;
            indices[nr*3+2]=number3-1;
            nr++;
        }
    }
    for(i=0;i<position.size();i++)
        vertex.push_back(Vertex(position[i],glm::vec3(0,0,0),glm::vec2(0,0)));
    setupMesh();
    fin.close();
}

void Mesh::loadMaterials(const char* fileName)
{

}

void Mesh::setupMesh()
{
    glGenVertexArrays(1, &this->VAO);
    glGenBuffers(1, &this->VBO);
    glGenBuffers(1, &this->EBO);

    glBindVertexArray(this->VAO);

    glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
    glBufferData(GL_ARRAY_BUFFER, this->vertex.size() * sizeof(Vertex), &this->vertex[0], GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0], GL_STATIC_DRAW);
    // Set the vertex attribute pointers
    // Vertex Positions
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)0);
    // Vertex Normals
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal));
    // Vertex Texture Coords
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, texCoords));

    glBindVertexArray(0);

}

void Mesh::draw(Shader &shader)
{
    shader.Use();
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

```

I checked to see if my class reads corectly the obj file and it does. Pls tell me whats wrong.

# Answer
> 1 votes
In your draw call:

```
void Mesh::draw(Shader &shader)
{
    shader.Use();
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

```

You are only specifying 6 elements to draw, it should be

```
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);

```

Unless you have hardcoded this on purpose if you are sure your model is only specifying 6 incides for testing purposes.

And by the way, you shouldn't actually store these:

```
vector<Vertex> vertex;
vector<GLuint> indices;

```

in your class members, once you setup your mesh the model data is copied into gpu memory there is no need to store them in your mesh object (which is in your ram). And you access this data via your VAO.

You can just create those std::vectors in your load mesh function and pass them as reference to your setup mesh function. After you called your setup mesh in the load mesh function, the load mesh function will end and the vectors will go out of scope and get automatically deleted.

glBufferData: https://www.opengl.org/sdk/docs/man/html/glBufferData.xhtml

data - Specifies a pointer to data that will be copied into the data store for initialization, or NULL if no data is to be copied.

However you will still need an:

```
GLuint indexCount;

```

member in your mesh class and store the indices.size() in it. And change draw elements to:

```
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);

```

# Answer
> 0 votes
I think you're missing a bind to your index buffer. It's been a while, but I believe binding the VertexArray only affects the vertex data, not the index data. If I remove the glBindBuffer(GL\_ELEMEN\_ARRAY\_BUFFER...) from my code, i get a black screen.

```
glBindVertexArray(VAO);
**glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);**
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);

```

EDIT: I have to retract that statement. The ELEMENT\_ARRAY\_BUFFER should be part of the VAO state. However, on my Mac Book Pro late 2014, I have to bind my ELEMENT\_ARRAY\_BUFFER.

---
Tags: opengl, c++, shaders, blender
---


# Question
Title: OpenGL Arc-Ball Camera Yaw Pitch GLM::Rotate
I'm currently working on a small Voxel-Editor Project. In the editor, I plan on using an Arc-Ball camera which rotate around the model. My camera is currently working but in an odd way. I can't seem to be able to move around the Z-Axis on my model which cause my camera angle to get smaller as I reach one side. For example, if I go to the left side of my ball, I wont be able to turn around it completly.

Here is my code which update my current View-Matrix into the updated one.

```
void t_Math::CreateLookAt(glm::mat4& InMatrix, sf::Vector3f pointToFix,   GLfloat InPitch, GLfloat InYaw, GLfloat valueToScale)
{

    glm::mat4 rotationMatrix = glm::mat4(1.0);

    const GLfloat FinalPitchDegree = InPitch / 57.2958;
    const GLfloat FinalYawDegree = InYaw / 57.2958;

    rotationMatrix = glm::rotate(rotationMatrix, FinalPitchDegree,                               glm::vec3(1.0, 0.0, 0.0));
    rotationMatrix = glm::rotate(rotationMatrix, FinalYawDegree, glm::vec3(0.0, 1.0, 0.0));

    const glm::vec4 cameraPosition4 =  rotationMatrix * glm::vec4(1.0);
    const glm::vec3 cameraPositionFinal = valueToScale * glm::vec3(cameraPosition4);

    const glm::vec3 constObjetMiddle = glm::vec3(pointToFix.x, pointToFix.y, pointToFix.z);

    InMatrix = glm::lookAt(cameraPositionFinal, constObjetMiddle,         glm::vec3(0.0, 1.0, 0.0));
}

```

Here is what I believe my code do.

The function receive a View Matrix, The model Center Coords, The Pitch, The Yaw and finally the Scalar (The zoom). Note: My Pitch and Yaw are simple GLFloat which mean they don't have limits and can go from -R to +R.

Now for the code. -We first create a base Matrix 4 -We Divide the Pitch and Yaw by 57.2958 (a radian) because GLM::rotate works with radian and I want it to be precise so in degree. -We then rotate the base Matrix on their respective Axis using the proper Pitch and Yaw -We then calculate the position of the Camera by using the ROTATED matrix which we transform into a Vec4 -We calculate the final Camera position by multiplying by the Scaling Vector (The Zoom) and we transform this Vector4 into a Vec3 -We create another Vec3 which is the Camera Target by using the value received by the function -We use all we collected to create a new lookAt matrix and we apply it to the view matrix.

I think I might be missing the Z-Axis rotation but how am I suppose to calculate it ? Should I use the Pitch or the Yaw ? Since i'm using (W-A-S-D) to move around here is what my keys does.

W: Increase Pitch S: Decrease Pitch D: Increase Yaw A: Decrease Yaw

Do I need to put the Roll into this and which keys should increase and decrease it ?

# Answer
> 1 votes
There are a few issues that are preventing your code from behaving like you expect.

First of all, your pitch and yaw rotations are applied in the wrong order. Remember non-coplanar 3D rotations are non-commutative, so euler angle (yaw/pitch/roll) rotations need to be applied in the proper order. So your rotation matrix should be constructed like this:

```
rotationMatrix = glm::rotate(rotationMatrix, FinalYawDegree, glm::vec3(0.0, 1.0, 0.0));
rotationMatrix = glm::rotate(rotationMatrix, FinalPitchDegree, glm::vec3(1.0, 0.0, 0.0));

```

Note that you used the X and Y axes for pitch and yaw. That means roll is a rotation around the Z axis, which means the camera is "looking down" the Z axis. So if yaw and pitch are 0 (ie. the rotation matrix is the identity matrix), the camera's position should be on the Z axis. But in your code, it ends up being at `(1, 1, 1)`:

```
// vec4(1.0) is equivalent to vec4(1.0, 1.0, 1.0, 1.0)
const glm::vec4 cameraPosition4 =  rotationMatrix * glm::vec4(1.0);

```

What you want is something like this:

```
const glm::vec4 cameraPosition4 =  rotationMatrix * glm::vec4(0.0, 0.0, 1.0, 1.0);

```

Finally if your intent is for the camera to "orbit" the target position, then your code will only work like this when the target position is the origin. Otherwise the camera will orbit the origin, but look off at something else. You probably want:

```
cameraPositionFinal += constObjetMiddle; // what's an objet?
InMatrix = glm::lookAt(cameraPositionFinal, constObjetMiddle, glm::vec3(0.0, 1.0, 0.0));

```

After these changes your code will mostly work. Since you're using `glm::lookAt` with a fixed `up` vector, you're not going to be able to add roll to the camera, except by creating a separate rotation matrix for it and combining it with the result of `lookAt` by multiplication. It's not clear whether or not this is something that you wanted or not. Another consequence of using `lookAt` is that when the pitch causes the camera to cross the `up` vector "poles" the view will appear to flip.

There are also a variety of code quality issues which may or may not be important, depending on where this project fits on a continuum from "really rough prototype" to "production-ready library".

* Consider using `glm::radians` and `glm::degrees` instead of magic literal constants. This makes your intent much clearer, in addition to being less error prone and often more accurate. Note also that older versions of GLM's `GTC_matrix_transform` took angles in degrees by default, but newer versions expect radians by default throughout the entire library.
* `glm::lookAt` isn't the most efficient way to generate a view matrix in situations like yours, where you're just generating the camera position from the target position (or vice-versa). It would be more efficient and clearer to just compose the view matrix directly. GLM's `GTX_euler_angles` provides convenient methods for this. For example:

```
glm::mat4 view = glm::translate(glm::mat4(), glm::vec3(0, 0, -10.f))
        * glm::eulerAngleXY(pitch_in_radians, yaw_in_radians)

```
* Try to use a consistent naming scheme. This is often more difficult in C++ than other popular languages where libraries have mostly standardized on a single style, but it's still good practice to be consistent in your own code. You have some parameters and variables in `PascalCase`, while others are in `camelCase`. Try to avoid naming functions, variables, and parameters with `PascalCase`. Outside of C# (and Pascal, of course) capitalized identifiers are usually reserved for types. Additionally `InMatrix` is a confusing name, considering this is what would be known as an out-parameter in C#. In C++ it's typical not to clutter up names with such metadata. Instead just assume that if a function takes a non-`const` reference-type parameter `T& param`, it plans to modify it.

---
Tags: opengl, camera, matrix, glm, trigonometry
---


# Question
Title: Are hard coded "rooms" better than dynamically generated on a smart phone, from performance point of view
This question pertains to a type of platform/maze game (made with Unity 5) for typical smartphones (iOS/Android).

This game has following characteristics: 1. an upper limit (about 100) on the amount of rooms 2. 3-5 different "levels", each with a different amount of rooms 3. the shape and type of the "ground" in each room is dynamically generated 4. each room has some items that are dynamically placed in the room but are generated from a prefab

A rough idea on the rooms in this game is given in below screen shot.

In that image only the platforms (black and white tiles) and the ground (light brown) would be shaped by an algorithm. The other objects shown in the image are prefabs that would be located somewhere in the room by an algorithm.

But considering that this game would not exactly be an infinite runner, and since it should run on smart phones, would it be better from performance perspective, to create 100 hard coded rooms instead?

# Answer
> 1 votes
It wouldn't be that much of a performance drag. The user would have to wait in order for the level to generate, but other than that it should perform the same as a pre-made level.

100 custom made levels on the other hand would load faster but would take up more storage.

# Answer
> 0 votes
What I would do in these situations with the new Unity 5.3.3 patch with the new Scene Management is to create a level editor and save the rooms as scenes. It is fairly easy to create editor functions, you can learn here.

If you are worried with storage, you can make a level editor that converts and store the levels as a .txt file but that would be as asshes999 say, trivial. But I would say the scene approach is better.

Other advantages of making a level editor, is you can extend the level editor functions and make unit tests.

---
Tags: algorithm, performance, unity
---


# Question
Title: Get vector3 position of Cursor on a fixed 2D plane within a 3D scene
How is it possible to get a cursors X and Y Location relative to the scene planes rather than using co-ordinates based upon pixels of screen height and width?

I have the start of a very basic game, picture with a few physical aids shown below.

I want to find out how far away the cursor is on the X and Y axis from an object in the scene. The Z axis is irrelevant due to the nature and orientation of the game, so `z = 0`. (Note that in Unity, the Y axis is vertical)

Basically, the distance of the cursor from the cube on the X Axis upon clicking will define the `power` of an action.

Because of this. I want to get the cursor X position relative to the 0 point of the scene ( or the object ), not relative to the bottom left corner of the screen.

I could then use `Vector3.Magnitude()` to get the distance.

How is this possible?

# Answer
> 1 votes
Since you're aiming at a known constant plane, you can do this without physics raycasting.

```
Vector3 GetCursorPositionOnScenePlane(float zValue = 0f)
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    float depth = zValue - ray.origin.z;
    float zDirection = ray.direction.z;

    if(Mathf.Approximately(zDirection, 0f) // Ray parallel to XY plane.
       || depth * zDirection < 0f)         // Ray looking away from plane.
    {
        // Error - this ray can't see the plane!
        // This won't happen if your camera is looking at the scene plane.
        return new Vector3(float.NaN, float.NaN, float.NaN);
    }

    // Calculate how many times we need to travel along the direction vector
    // from the ray's origin before hitting our desired zValue:
    float scale = depth/zDirection;

    return ray.origin + scale * ray.direction;
}

```

Note that this differs from Camera.ScreenToWorldPoint in that the `zValue` here is a z position in world space, so your outputs are always in a world-XY-aligned plane. `ScreenToWorldPoint`'s `z` is a distance from the camera, so if the camera is rotated then the plane of its outputs may be tilted relative to the world XY plane.

# Answer
> 1 votes
It is possible and Unity documentation is *very* helpful in this matter. First you need a ray to raycast from mouse position, the documentation for mouse position provides an example how to get a ray from mouse position:

```
public class ExampleClass : MonoBehaviour {
    void Update() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    }
}

```

because you are not interested in *all* of the objects(just the plane\*), following to documentation of Physics.Raycast will tell you all possible overloads, one of them having a layer mask. You are also interested in position, so choosing an overlaod with `RaycastHit` and following documentation to RaycastHit tells you there is a ".position":

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        int maskOfPlane = 1 << planeLayer;
        if (Physics.Raycast(ray, out hit, maskOfPlane)) {
            //one of coordiantes being always zero for aligned plane
            var position = hit.position;//this is relative to 0,0,0
            var relativePosition = other.transform.position - position; //relative to a gameObject other
        }
    }
}

```

\*literally place an invisible plane in the world aligned with your games logical plane and move it to a custom layer, you will need to set the mask against it.

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


title: csfml wait event

text:
# Question
Title: csfml wait event
I would like to spawn a separate thread to deal with inputs using c and sfml. I made a prototype that waits for input in main() and it works fine. I made a prototype that spawns a new thread and waits for input and no input is received.

Here is the second prototype: http://pastebin.com/S4EmPTBL

Can I have some help to get this going?

# Answer
I found the answer in annother thread

"As for the problem, you'll have to handle the events in the same thread as you've created the window - at least that's the case in SFML 2" -eXpl0it3r
> 1 votes

---
Tags: sfml, c
---


# Question
Title: How can I handle multiple force in Unity?
I'm trying to get my character to perform a "dash" where their x velocity increases rapidly and then falls over time. However, I'm also maintaining a constant x velocity so the character appears to be running at all times. The problem is trying to figure out when the dash should be considered finished. It can't be finished when the x velocity is equal to the running speed again, because other forces may be acting on the character.

It feels like all the information I need to figure this out is gone because it's all been calculated into the velocity vector, and the actual forces and where they come from are thrown out.

I've considered the following:

```
final = run + dash + other forces

```

But this means I couldn't use Unity's forces because I don't know what they're meant to act on(for example should a force pushing me down while I jump be applied to the jump velocity or the not?).

How can I determine how much force my dash should do and how much it should "undo" with the information given by Unity?

# Answer
> 1 votes
How much force should apply, it depends totally on your environment. What are the factors, I don't know.

But your **undo** thing can be achieve by `Mathf.Clamp`.

Suppose you have constant horizontal velocity of 5, then you can do something like,

```
....
Rigidbody _rb = GetComponent<Rigidbody> ();
....
_rb.velocity = new Vector3 (Mathf.Clamp (_rb.velocity.x, 5, 10000), 0, 0);

```

Here you can specify the minimum force, which is your constant force, and max, it is up to you, my recommendation is to keep this value high as 10000. By this you can apply `AddForce` and you character will be able to get back to your constant velocity.

---
Tags: unity, physics
---


# Question
Title: Issues with importing bezier curve animation (curve does not distort?)
Hi guys i'm pretty new to unity and having a frustrating issue; I've created a spear gun with an animation using a bezier curve grouped to the main gun shaft and distorted using a bone (bone relative) in blender. It works fine in blender, however when I export it into unity 5, the bezier curve does not distort and simple moves forward and back. I imported the blender model as a blender file.

I have tried pairing the model components in all the ways i can think of to see if that was the problem? I have attached the blender views and animations and what it looks like in Unity.

Is it an issue with unity being unable to animate bezier curve animations or the type of bone pairing i used??

unity animation, see the besiel curve simple moves forward and back instead of bending/distorting to look like a rubber fitted on a real gun!

# Answer
have you tried setting Animation Compression under Animation inspector to Off?
> 1 votes

---
Tags: unity, animation, blender
---


title: Unexpected quaternion rotation behavior

text:
# Question
Title: Unexpected quaternion rotation behavior
First off let me apologize for the vague title but I really couldn't think of a more descriptive one (maybe after reading this a more advanced user might be able to edit it).

Alright, so I have been putting together a three.js example that shows a different animated texture on a billboard when the camera rotates around it (just like oldschool doom and build engine games). After having the initial concept explained to me (Doom-style 2.5D Movement Animations) I managed to get something up and working.

Everything works fine. You can move the camera around the object and the correct animations play for the angle you are currently seeing the object. However...as soon as you change the rotation of the object (the mesh object associated with the billboard not the camera), even by the slightest amount, the theta value that is calculated to determine the angle becomes skewed.

I'm not sure if I need to use another method to calculate which animation should be displayed or if there is something simple I'm just over looking. The source is located below as well as on github: https://github.com/commanderZiltoid/threejs-2.5d-fps.

A working example can be found here: https://stashcube.com/stackexamples/rotate/

When you first browse to that page the billboard object will not be rotated. You can pan around it and see everything work. If you press the enter button the billboard object will be rotated and you can see what I have explained.

```
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="/css/custom.css" media="all"/>
    </head>
    <body>
        <div id="blocker">
            <div id="instructions">
                <span style="font-size:40px">Basic WASD/Mouse Movement</span>
                <br/>
                <span style="font-size:30px">Click to start</span>
                <br />
                (W, A, S, D = Move, SPACE = Jump, MOUSE = Look around)
            </div>
        </div>

        <script src="/libs/three.js"></script>
        <script src="/libs/PointerLockControls.js"></script>

        <script src="/src/verify_pointerlock.js"></script>
        <script src="/src/TextureAnimator.js"></script>
        <script>
                var camera,
                    scene,
                    renderer,
                    geometry,
                    material,
                    mesh,
                    controls,
                    blocker = document.getElementById( 'blocker' ),
                    instructions = document.getElementById( 'instructions' ),
                    controlsEnabled = false,
                    moveForward = false,
                    moveBackward = false,
                    moveLeft = false,
                    moveRight = false,
                    canJump = false,
                    prevTime = performance.now(),
                    velocity = new THREE.Vector3(),
                    clock = new THREE.Clock();

                camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);

                scene = new THREE.Scene();
                scene.fog = new THREE.Fog(0xffffff, 0, 750);

                var light = new THREE.HemisphereLight(0xeeeeff, 0x777788, 0.75);
                light.position.set(0.5, 1, 0.75);
                scene.add(light);

                controls = new THREE.PointerLockControls(camera);
                scene.add(controls.getObject());

                //FLOOR
                geometry = new THREE.PlaneGeometry( 2000, 2000, 100, 100 );
                geometry.rotateX( - Math.PI / 2 );
                for (var i = 0, l = geometry.vertices.length; i < l; i ++) {
                        var vertex = geometry.vertices[ i ];
                        vertex.x += Math.random() * 20 - 10;
                        vertex.y += Math.random() * 2;
                        vertex.z += Math.random() * 20 - 10;
                }
                for (var i = 0, l = geometry.faces.length; i < l; i ++) {
                        var face = geometry.faces[ i ];
                        face.vertexColors[ 0 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
                        face.vertexColors[ 1 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
                        face.vertexColors[ 2 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
                }
                material = new THREE.MeshBasicMaterial({vertexColors: THREE.VertexColors});
                mesh = new THREE.Mesh(geometry, material);
                scene.add(mesh);
                //END FLOOR

                var players = [];
                function add_player(x,y,z){

                    var i = players.length;

                    players.push({id:'player_' + i});

                    players[i].textures = {
                        s:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/s.png'),
                        se:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/se.png'),
                        e:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/e.png'),
                        ne:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/ne.png'),
                        n:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/n.png'),
                        nw:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/nw.png'),
                        w:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/w.png'),
                        sw:new THREE.ImageUtils.loadTexture('/assets/textures/' + players[i].id + '/sw.png')
                    };

                    players[i].animations = {
                        s:new TextureAnimator(players[i].textures.s, 4, 1, 4, 160),
                        se:new TextureAnimator(players[i].textures.se, 4, 1, 4, 160),
                        e:new TextureAnimator(players[i].textures.e, 4, 1, 4, 160),
                        ne:new TextureAnimator(players[i].textures.ne, 4, 1, 4, 160),
                        n:new TextureAnimator(players[i].textures.n, 4, 1, 4, 160),
                        nw:new TextureAnimator(players[i].textures.nw, 4, 1, 4, 160),
                        w:new TextureAnimator(players[i].textures.w, 4, 1, 4, 160),
                        sw:new TextureAnimator(players[i].textures.sw, 4, 1, 4, 160)
                    };

                    players[i].billboard_mat = new THREE.MeshBasicMaterial({map: players[i].textures.n,  transparent:true});
                    players[i].billboard_geom = new THREE.PlaneGeometry(14, 14, 1, 1);
                    players[i].billboard = new THREE.Mesh(players[i].billboard_geom, players[i].billboard_mat);

                    players[i].material = new THREE.MeshBasicMaterial({transparent:true, opacity:0.0});
                    players[i].geometry = new THREE.PlaneGeometry(14, 14, 1, 1);
                    players[i].mesh = new THREE.Mesh(players[i].geometry, players[i].material);

                    players[i].billboard.position.set(x,y,z);
                    scene.add(players[i].billboard);

                    players[i].mesh.position.set(x,y,z);
                    scene.add(players[i].mesh);

                }

                add_player(-100,10,0);
                //add_player(-200,10,100);

                renderer = new THREE.WebGLRenderer();
                renderer.setClearColor(0xffffff);
                renderer.setPixelRatio(window.devicePixelRatio);
                renderer.setSize(window.innerWidth, window.innerHeight);
                document.body.appendChild(renderer.domElement);

                animate();

                function animate() {

                    var delta = 1000 * clock.getDelta();

                    //find the position each player is facing relative to
                    //the current player camera position and display the
                    //correct texture on the player billboard, animate texture
                    for(var i = 0; i < players.length; i++){

                        var a = new THREE.Vector3();
                        a.subVectors(controls.getObject().position, players[i].mesh.position);
                        a.normalize();

                        var b = new THREE.Vector3(0,0,1);
                        b.applyQuaternion(players[i].mesh.quaternion);
                        b.normalize();

                        var theta = Math.acos(a.dot(b)) * (180/Math.PI);
                        if(a.x * a.z < 0){
                            theta = 360.0 - theta;
                        }

                        if((theta > 0 && theta <= 22.5) || (theta > 337.5 && theta <= 359.99)){//south
                            players[i].billboard.material.map = players[i].textures.s;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.s.update(delta);
                        }
                        else if(theta > 292.5 && theta <= 337.5){//south east
                            players[i].billboard.material.map = players[i].textures.se;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.se.update(delta);
                        }
                        else if((theta < 292.5 && theta >= 270) || (theta > 90 && theta <= 112.5)){//east
                            players[i].billboard.material.map = players[i].textures.e;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.e.update(delta);
                        }
                        else if(theta > 112.5 && theta <= 157.5){//northeast
                            players[i].billboard.material.map = players[i].textures.ne;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.ne.update(delta);
                        }
                        else if(theta > 157.5 && theta <= 202.5){//north
                            players[i].billboard.material.map = players[i].textures.n;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.n.update(delta);
                        }
                        else if(theta > 202.5 && theta <= 247.5){//northwest
                            players[i].billboard.material.map = players[i].textures.nw;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.nw.update(delta);
                        }
                        else if((theta > 67.5 && theta <= 89.99) || (theta > 247.5 && theta <= 269.99)){//west
                            players[i].billboard.material.map = players[i].textures.w;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.w.update(delta);
                        }
                        else if(theta > 22.5 && theta <= 67.5){//southwest
                            players[i].billboard.material.map = players[i].textures.sw;
                            players[i].billboard.needsUpdate = true;
                            players[i].animations.sw.update(delta);
                        }

                        players[i].billboard.lookAt(controls.getObject().position);

                    }

                    requestAnimationFrame(animate);
                    if (controlsEnabled) {

                        var time = performance.now();
                        var delta = ( time - prevTime ) / 1000;

                        velocity.x -= velocity.x * 10.0 * delta;
                        velocity.z -= velocity.z * 10.0 * delta;
                        velocity.y -= 9.8 * 100.0 * delta; // 100.0 = mass

                        if ( moveForward ) velocity.z -= 400.0 * delta;
                        if ( moveBackward ) velocity.z += 400.0 * delta;
                        if ( moveLeft ) velocity.x -= 400.0 * delta;
                        if ( moveRight ) velocity.x += 400.0 * delta;

                        controls.getObject().translateX( velocity.x * delta );
                        controls.getObject().translateY( velocity.y * delta );
                        controls.getObject().translateZ( velocity.z * delta );

                        if ( controls.getObject().position.y < 10 ) {
                                velocity.y = 0;
                                controls.getObject().position.y = 10;
                                canJump = true;
                        }

                        prevTime = time;

                    }

                    renderer.render(scene, camera);

                }

                //keydown event
                document.addEventListener('keydown', function(event){
                    switch (event.keyCode){
                        case 38: // up
                        case 87: // w
                                moveForward = true;
                                break;
                        case 37: // left
                        case 65: // a
                                moveLeft = true; break;
                        case 40: // down
                        case 83: // s
                                moveBackward = true;
                                break;
                        case 39: // right
                        case 68: // d
                                moveRight = true;
                                break;
                        case 32: // space
                                if ( canJump === true ) velocity.y += 350;
                                canJump = false;
                                break;
                        }
                }, false);

                //keyup event
                document.addEventListener('keyup', function(event){
                    switch(event.keyCode) {
                        case 38: // up
                        case 87: // w
                                moveForward = false;
                                break;
                        case 37: // left
                        case 65: // a
                                moveLeft = false;
                                break;
                        case 40: // down
                        case 83: // s
                                moveBackward = false;
                                break;
                        case 39: // right
                        case 68: // d
                                moveRight = false;
                                break;
                        }
                }, false);

                //Window resize event
                window.addEventListener('resize', function(){
                    camera.aspect = window.innerWidth / window.innerHeight;
                    camera.updateProjectionMatrix();
                    renderer.setSize(window.innerWidth, window.innerHeight);
                }, false );

        </script>
    </body>
</html>

```

# Answer
I'm not well-versed in three.js, but it looks like you should be able to do it like this...

```
var view = new THREE.Vector3();
view.subVectors(controls.getObject().position, players[i].mesh.position);

var inverse = players[i].mesh.quaternion.clone();
inverse.inverse();

view.applyQuaternion(inverse);

// view is now a direction in the object's local space.

var angle = Math.Round(Math.atan2(view.x, view.z) * 4/Math.PI);

// Now do your animation selection based on this angle:
// (If I've gotten the coordinate handedness right)

// ±4: toward viewer
//  3: toward-right
//  2: right
//  1: away-right
//  0: away
// -1: away-left
// -2: left
// -3: toward-left

```
> 1 votes

---
Tags: rotation, quaternion, webgl, angles, three.js
---


# Question
Title: Movement appears to be frame rate dependent, despite use of Time.deltaTime
I have the following code to calculate the translation required to move a game object in Unity, which is called in `LateUpdate`. From what I understand, my use of `Time.deltaTime` should make the final translation frame rate independent (please note `CollisionDetection.Move()` is just performing raycasts).

```
public IMovementModel Move(IMovementModel model) {
    this.model = model;

    targetSpeed = (model.HorizontalInput + model.VerticalInput) * model.Speed;

    model.CurrentSpeed = accelerateSpeed(model.CurrentSpeed, targetSpeed,
        model.Accel);

    if (model.IsJumping) {
        model.AmountToMove = new Vector3(model.AmountToMove.x,
            model.AmountToMove.y);
    } else if (CollisionDetection.OnGround) {
        model.AmountToMove = new Vector3(model.AmountToMove.x, 0);
    }

    model.FlipAnim = flipAnimation(targetSpeed);
    // If we're ignoring gravity, then just use the vertical input.
    // if it's 0, then we'll just float.
    gravity = model.IgnoreGravity ? model.VerticalInput : 40f;

    model.AmountToMove = new Vector3(model.CurrentSpeed, model.AmountToMove.y - gravity * Time.deltaTime);

    model.FinalTransform =
        CollisionDetection.Move(model.AmountToMove * Time.deltaTime,
            model.BoxCollider.gameObject, model.IgnorePlayerLayer);
    // Prevent the entity from moving too fast on the y-axis.
    model.FinalTransform = new Vector3(model.FinalTransform.x,
        Mathf.Clamp(model.FinalTransform.y, -1.0f, 1.0f),
        model.FinalTransform.z);

    return model;
}

private float accelerateSpeed(float currSpeed, float target, float accel) {
    if (currSpeed == target) {
        return currSpeed;
    }
    // Must currSpeed be increased or decreased to get closer to target
    float dir = Mathf.Sign(target - currSpeed);
    currSpeed += accel * Time.deltaTime * dir;
    // If currSpeed has now passed Target then return Target, otherwise return currSpeed
    return (dir == Mathf.Sign(target - currSpeed)) ? currSpeed : target;
}

private void OnMovementCalculated(IMovementModel model) {
    transform.Translate(model.FinalTransform);
}

```

If I lock the game's framerate to 60FPS, my objects move as expected. However, if I unlock it (`Application.targetFrameRate = -1;`), some objects will move at a much slower rate then I would expect when achieving ~200FPS on a 144hz monitor. This only seems to happen in a standalone build, and not within the Unity editor.

GIF of object movement within the editor, unlocked FPS

http://gfycat.com/SmugAnnualFugu

GIF of object movement within the standalone build, unlocked FPS

http://gfycat.com/OldAmpleJuliabutterfly

# Answer
Frame based simulations will experience errors when updates fail to compensate for non-linear rates of change.

For example consider an object starting with position and velocity values of zero experiencing a constant acceleration of one.

If we apply this update logic:

```
velocity += acceleration * elapsedTime
position += velocity * elapsedTime

```

We can expect these results under differing frame rates:

The error is caused by treating the final velocity as though it applied for the entire frame. This is similar to a Right Riemann Sum and the amount of error varies with frame rate (illustrated on a different function):

As MichaelS points out, this error will be halved when frame duration is halved, and may become inconsequential at high frame rates. On the other hand any games that experience performance spikes or long running frames may find this produces unpredictable behaviour.

---

Luckily kinematics allows us to accurately calculate the displacement caused by linear acceleration:

```
d =  vᵢ*t + (a*t²)/2

where:
  d  = displacement
  vᵢ = initial velocity
  a  = acceleration
  t  = elapsed time

breakdown:
  vᵢ*t     = movement due to the initial velocity
  (a*t²)/2 = change in movement due to acceleration throughout the frame

```

So if we apply this update logic:

```
position += (velocity * elapsedTime) + (acceleration * elapsedTime * elapsedTime / 2)
velocity += acceleration * elapsedTime

```

We will have the following results:
> 31 votes

# Answer
It depends on where you're calling your step from. If you're calling it from Update, your movement will indeed be framerate independent if you scale with Time.deltaTime, but if you're calling it from FixedUpdate, you need to scale with Time.fixedDeltaTime. I figure you're calling your step from FixedUpdate, but scaling with Time.deltaTime, which would result in decreased apparent speed when Unity's fixed step is slower than the main loop, which is what's happening in your standalone build. When the fixed step is slow, fixedDeltaTime is large.
> 6 votes

---
Tags: unity, movement, frame-rate, timestep
---


title: How to make illusion of round world?

text:
# Question
Title: How to make illusion of round world?
I want to make a flat world, but i want to split it into pieces which will load in segments (for better optimization), and when you are at the end of map it will start loading segments from the beginning again. And I want to make an illusion of roundness (only optical effect if possible). For example, when you watch ships on the horizon, you see their masts first.

I'm asking only for theoretical ideas, so you don't need to send any scripts.

# Answer
You can do this purely in a vertex shader. You'd want to apply this shader to everything you render.

One trick though that you can do is weight it so that the nearby objects are flat out to say 100 meters. I'd recommend this because in an FPS game the distortion on objects requires you to change things. (Players will aim at things wrong). If you keep the nearby regions flat then start the curve at a distance it'll look the same without having interaction problems.

Here's an image to understand. (I don't have the code at the moment on this machine, but it's only a few lines if I remember correctly).

Since you asked for code. I can't vet this code 100%, but I did see images of it working. (I wrote pseudocode for a friend who converted it to HLSL and the images showed it working).

```
cbuffer matrix_buffer
{
  matrix world;
  matrix view;
  matrix projection;
};

struct vertex_input_type
{
  float4 position : POSITION;
  float3 normal : NORMAL;
};

struct pixel_input_type
{
  float4 position : SV_POSITION;
  float3 normal : NORMAL;
};

pixel_input_type vertex_shader(vertex_input_type input)
{
  pixel_input_type output;

  input.position.w = 1.0f;

#if 0
  output.position = mul(world, input.position);
  output.position = mul(view, output.position);
  output.position = mul(projection, output.position);
#else
  float4 viewPosition = float4(0, 20.0, 0, 1);
  float seaLevel = 0.0;
  float4 vertex = input.position;
  matrix model = world;
  float radius = 900.0;

  vertex = mul(model, vertex);
  float2 diff = vertex.xz - viewPosition.xz;
  float angleX = -length(diff) / radius;
  float angleY = atan2(diff.x, diff.y);
  float3x3 rotateX =
  {
    1, 0, 0,
    0, cos(angleX), -sin(angleX),
    0, sin(angleX), cos(angleX)
  };
  float3x3 rotateY =
  {
    cos(angleY), 0, sin(angleY),
    0, 1, 0,
    -sin(angleY), 0, cos(angleY)
  };
  vertex = float4(mul(rotateY, mul(rotateX, float3(0, radius + vertex.y - seaLevel, 0))) + float3(0, -radius, 0), 1);
  vertex = mul(projection, mul(view, vertex));
  output.position = vertex;
#endif

  output.normal = input.normal;

  return output;
}

```
> 10 votes

---
Tags: optimization, world-design
---


title: How to do one-way collision?

text:
# Question
Title: How to do one-way collision?
I would like to know how can I do one way collision. It's the collision common in mario's games and many platforms. I try to do an code but I cannot post because it's part of a paid game. Basically I have two rectangles like this:

```
struct Rect {
  int x, y; // positions in the world
  int w, h; // width and height
};

```

The rect A moves and the rect B is fixed with the world. Someone has a idea of how to do this?

# Answer
Assuming that you have functional 2-way collision, all you need to do is check that the bottom of Rect A is above the surface of Rect B, and that the y velocity of Rect A is negative/down. Roughly:

```
void OnCollide(a, b)
{
    if(a.y - a.h * .5 > b.y + .5 * b.h && a.yvel < 0)
    {
        // do collide
    }
    else
    {
       // pass through
    }
}

```
> 1 votes

# Answer
You can use a Platform Effector on the game object that has the collider:

This provides a One-Way collision detection for platforms.

http://docs.unity3d.com/Manual/class-PlatformEffector2D.html
> 0 votes

# Answer
A solution may consist in deactivating all fixed colliders above your character and activating the ones under your character
> 0 votes

# Answer
I solved the problem. I just deactivate the collision detection in axis X and hold the detection in axis Y. Thank you people.
> 0 votes

---
Tags: collision-detection
---


title: Darkness, and a candle

text:
# Question
Title: Darkness, and a candle
My game has a Pokemon-type movement mechanic.

I would like my level was a pitch black level, but the player having a candle can lighten a circular area, and so walk without being able to see more than some near steps beyond him. I.e. not being able to see the whole map.

How can I acheve that in Gamemaker Studio?

Elements in my game:

* A character, moving squarely tile by tile.
* A wall. Just a wall.
* A background for the floor.

The game is not about Pokemon, but think as if I'm using the same mechanics for movement. It also happens to be the same concept as the *flash* HM in a cave.

# Answer
> 3 votes
Assuming the camera follows the character, you should be able to use an image to black out all of the screen except around the character. If your game window is 800x600 for example, create a fully-black sprite that's also 800x600, find the center point of the sprite, then clear out a transparent circle around that point.

Been a while since I've used GameMaker, but IIRC, you need to use the "Draw" event. You should have a line of code inside the "Draw" event which constantly repositions the darkness sprite to the character's position. Another option would be to reposition the sprite every time the character moves.

# Answer
> 1 votes
The best way to do this is to draw a surface across the entire screen (I usually draw it to the view, since it's more efficient and less hard on resources), and then use an image\_blend in the draw event of your player character to draw the faded circle Peter posted centred at objPlayer.x, objPlayer.y, which will grant you greater control over the radius of light and allow you to add certain effects, such as flickering and radius changes, and change the colour of it easily without having to resprite it every time. The alternate is instead of having a sprite, you could just straight up use

> draw\_set\_blend\_mode(bm\_add or bm\_subtract, whichever one you want)
>
> draw\_set\_colour(whatever colour you want)
>
> draw\_circle(arguments)
>
> draw\_set\_blend\_mode(bm\_normal)

---
Tags: game-maker
---


# Question
Title: How can I support retina/high-DPI/high-res graphics in libgdx?
I'm not sure if I'm missing it somewhere or if this just doesn't exist, but I'd like to support "retina" graphics on desktop displays that support them (like the newer MacBook Pro), but I can't find a way to change the density of the LWJGL canvas in Libgdx.

Is this possible? How can I do it?

# Answer
I know this post is old, but I found it when having the same issue. I luckily found this option after:

```
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useHDPI = true;

```

Maybe this was not available at the time, but it did solve my problem! Now my textures look super sharp.
> 3 votes

# Answer
Retina Graphics is just a fancy word for high pixel density. What makes your game support high density displays is the resolution of your assets, not the engine.
> 2 votes

# Answer
I may be way off the mark here but this comes from my experience with PlayN (which seems very similar to libGDX).

Though Retina means double resolution you treat it as if the resolution were the same as a non-retina device. Apples core libraries will even tell you that the screen if half the size as it actually is!

When you load an image asset, say "Sprites.png", iOS will actually first look for a file called "Sprites@2x.png" and use that file instead.

When coding for iOS you're are no longer working in pixels - but in points - and its up to iOS how big a point is depending on the context.

So all you need to do is provide versions of all of your image assets at twice the resolution with a slightly different file name e.g. "Sprites.png" and "Sprites@2x.png". The iOS will do the rest :D

I hope that makes sense... I didn't get much sleep last night :)
> 2 votes

# Answer
If you use an OrthographicCamera to display the scene, it has a zoom option, have you tried looking into it?
> 0 votes

# Answer
It's a problem with JAVA apps being scaled twice by retina displays. I presume your talking about the desktop version right? I currently have the same issue, it's super blurry. The solution is to turn off retina scaling for java apps, currently trying to figure this out.
> 0 votes

---
Tags: java, libgdx, macos
---


title: Maya/Unity - See through models

text:
# Question
Title: Maya/Unity - See through models
I've recently modeled my character inside Maya; here's an image. The first thing I noticed whilst creating my model is that the models could be seen through *source 1*, after doing a little research people stated that it was a graphical bug in Maya. However, once imported into Unity the same effect occurs.

**Therefore, my Question is: How can I fix this inside Maya or Unity?**

To prove that my UV map doesn't contain a low opacity texture see the second image below:

# Answer
**I FINALLY FIXED IT**

Being a scrub to the Maya Hyper-shade panel. I did a load of research and found out it was due to my file type of the texture; I used a PNG and it caused the model to conflict with it's alpha opacity causing it to, well, be translucent. Thank you for all the feedback and I hope this solves anyone else's problems in Maya.

All opaque \<3
> 1 votes

---
Tags: unity, textures, maya, rigging
---


# Question
Title: How can I refer to Android assets in other directories?
My project was initially not meant for Android, and its assets are organised along the following directory structure (I hope the ASCII art renders reasonably well):

```
/
+- engine/
 |    +- src/
 |     |      enginefile1.cpp
 |     |      ...
 |     `- textures/
 |            texture1.tex
 |            ...
+- game/
 |    +- src/
 |     |      gamefile1.cpp
 |     |      ...
 |    +- textures/
 |     |      gametexture1.tex
 |     |      ...
 |    +- ios/
 |     |      [various iOS-specific files]
 |     `- android/
 |           | build.xml
 |           | AndroidManifest.xml
 |           +- jni/
 |           |     Android.mk
 |           +- assets/
 |             [other Android-specific files]
 `- othergame/

```

My `game/android/jni` directory is almost empty because `Android.mk` points to the relative paths of the source files in `engine/src` and `game/src`. Actually, it even includes the proper `Makefile`s so that I never have to modify `Android.mk` when I add or remove a source file to the project.

Both `engine` and `game` provide assets that need to be shipped with the Android build. I would like `build.xml` to refer to these assets without having to manually copy them. A rule that copies the assets at build time then deletes them would be acceptable, but of course I would prefer a zero copy solution. Does this make sense? How did others solve this cross-platform build problem?

# Answer
> 1 votes
Yes, you can absolutely use files in other directories. Place the assets you have in to the `assets` directory (sibling to the `res` directory), and use the `AssetManager` to access them.

To load bitmaps, you'll want the `BitmapFactory`, and you'll have to do some extra work if you intend to load resolution dependent images.

Be careful about loading Bitmaps more than once. Because you will be dealing with raw file handles, you'll probably want to implement some resource/memory manager that allows you ot quickly look up references to existing Bitmap objects and the like. Depending on your architecture, you may need to do this with `WeakReferences` so you don't end up with the entire game data in memory. (With normal android resources, the `ResourceManager` handles all of this for you.)

# Answer
> 1 votes
Ant build property "asset.dir" is responsible for providing name of assets directory. It's "assets" by default, but you can change it to something like "../assets". This changes path of entire directory, but if you have Android-specific resources, you can still use "res" directory.

# Answer
> 1 votes
How strange that the other answers here do not answer your question...they all assume you want only one assets directory, or refer to res/ instead of assets/.

I also need more than one assets directory.

I fought with the `<aapt>` ant module for hours and hours and finally gave up and realized there's a much easier way.

I copied the `<target name="-package-resources"...>` tag from the master build file that `ant` uses, `android_sdk_dir/tools/ant/build.xml`, and pasted the tag into my project `build.xml` (you must paste the tag right before the master `build.xml` is included, as the comments at the end of the pre-made project `build.xml` explain), then added a second section to simply exec `zip` to add the assets to the .ap\_ file (which is `${out.absolute.dir}/${resource.package.file.name}` at that point in the ant file):

```
    <target name="-package-resources" depends="-crunch">
        <!-- only package resources if *not* a library project -->
        <do-only-if-not-library elseText="Library project: do not package resources..." >
            <aapt executable="${aapt}"
                    command="package"
                    versioncode="${version.code}"
                    versionname="${version.name}"
                    debug="${build.is.packaging.debug}"
                    manifest="${out.manifest.abs.file}"
                    assets="${asset.absolute.dir}"
                    androidjar="${project.target.android.jar}"
                    apkfolder="${out.absolute.dir}"
                    nocrunch="${build.packaging.nocrunch}"
                    resourcefilename="${resource.package.file.name}"
                    resourcefilter="${aapt.resource.filter}"
                    libraryResFolderPathRefid="project.library.res.folder.path"
                    libraryPackagesRefid="project.library.packages"
                    libraryRFileRefid="project.library.bin.r.file.path"
                    previousBuildType="${build.last.target}"
                    buildType="${build.target}"
                    ignoreAssets="${aapt.ignore.assets}">
                <res path="${out.res.absolute.dir}" />
                <res path="${resource.absolute.dir}" />
                <!-- <nocompress /> forces no compression on any files in assets or res/raw -->
                <!-- <nocompress extension="xml" /> forces no compression on specific file extensions in assets and res/raw -->
            </aapt>
<!--
NEW XML STARTS HERE
-->
            <exec executable="zip" failonerror="true">
                <arg value="-r" />
                <arg value="${out.absolute.dir}/${resource.package.file.name}" />
                <arg value="my_assets_directory_1" />
                <arg value="my_assets_directory_2" />
                <arg value="my_assets_directory_3" />
            </exec>
<!--
NEW XML ENDS HERE
-->
        </do-only-if-not-library>
    </target>

```

This method has the advantage that you are more free to define the directory structure of your assets in the source tree and in the apk (since you can `exec` `zip` multiple times with different arguments, and even wrap `zip` in a script that runs `zip` from multiple current directories in your source tree). You also have per-file control of compression (zip has a -0 option to suppress compression) and do not need to use the limited, per-extension-only nocompress tag.

Note this `ant` xml comes BEFORE zipalign in the ant build process, so we still get a "zip-compatible" archive that meets the alignment needs of APKs and Android Java.

In my case I have an NDK based app and I want to access these assets from C code only (where any apk path is OK). If you need to use the standard Android Java assets calls to access these items, I'm not sure whether or not they must be in a path inside the zip named assets/ or not. If so, you can adapt the trick above by `exec`ing a script that `cd`s to the relevant source tree folder, then runs `zip`.

# Answer
> 0 votes
Off the top of my head, I don't think you can use anything outside of res/, but if you're looking to avoid added cost to your dev cycle with a copy, you might try moving them instead or maybe even using a symlink...

# Answer
> 0 votes
If you were using a Maven project as opposed to an Ant project, you could easily redefine the res folder to be whatever you wanted via the resourceDirectory configuration option of the android:apk mojo in the android-maven-plugin.

```
  <plugin>
    <groupId>com.jayway.maven.plugins.android.generation2</groupId>
    <artifactId>android-maven-plugin</artifactId>
    <version>${android.maven.version}</version>
    <configuration>
      <resourceDirectory>${project.basedir}/res</resourceDirectory>
    </configuration>
    <extensions>true</extensions>
  </plugin>

```

Sadly, unless you were willing to migrate from using Ant to using Maven, this answer might not help you very much...

# Answer
> 0 votes
If you are on a unix OS you can hard-link them, and tell your version control to ignore the `res/` directory.

---
Tags: android, cross-platform, ndk, ant
---


title: Always operate at Time.timeScale = 1?

text:
# Question
Title: Always operate at Time.timeScale = 1?
How do I make a specific script always operate at `Time.timeScale = 1` **no matter what**? I want it to override even when another script calls `Time.timeScale = 0` for example.

# Answer
When you don't make use of rigidbody physics, just save a copy of the current timescale in a local variable and set Time.timeScale to 1 at the beginning of the method. At the end of the method, reset Time.timeScale to the backed up value.

```
void Update() {
     float oldTimeScale = Time.timeScale;
     Time.timeScale = 1.0f;

     // your code

     Time.timeScale = oldTimeScale;
}

```

Another caveat is that FixedUpdate will never be called when the time scale is 0.

You can also ditch Unity's timescale handling altogether and do your own by having an own timescale instance variable in every MonoBehavior and multiply it with Time.deltaTime whenever you use it. Again, this will not work with rigidbody physics because Unity controls these itself based on the global timescale.
> 2 votes

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