# Question
Title: How do I implement level generation based on graph grammars?
I'm looking to do some pseudo-random map generation using graph grammars (graph rewriting). However, most of what I can find online on this is purely academic and, while helpful, doesn't have any direct practical application.

For the uninitiated, the thousand-foot view of this is that say a dungeon room is generated, then based on a set of rules for that room, one rule is randomly chosen and applied adding more rooms. From there, another specified room may go through the same or a different set of rules for additional growth of the map.

For the practical side of things, I'm thinking of storing the possible rules as arrays containing data about what additional rooms it contains, what order they are in, and which might also end up having a rule applied to it. But then mapping this to 2D space, while it seems easy, may end up with some complications, such as what happens if rooms end up overlapping.

At any rate, I was hoping someone might have some insight into whether this might be done in a better fashion than an array for the rules.

The results from the rules will likely be added to a custom class that will hold the layout as it's built.

Thoughts? :)

# Answer
> 2 votes
Most instances I've seen of graph rewriting for map generation solve the collisions problem (I.E overlapping rooms) by restricting the graph nodes to regular, modular components. For instance, this example, taken from Procedural generation of dungeons uses rooms that are laid out on regular intervals:

# Answer
> 1 votes
The other approach I've seen is to use a generate & test (aka trial & error) approach. Basically, a rule is selected & if the result would be valid, it is applied. If the result is invalid (I.E. overlapping rooms) usually it is discarded & a new rule is attempted. Other times, it may be possible to modify the results.

In a sense, both of these happen a bit with Brogue's level generation; I.E. bridges are built "until we can't find nice places to build them" whereas with water "we knock down the boundaries between similar lakes where possible."

The more complex your rules, the more difficult it may be to get results with a no modifying generate & test approach. The trade off is it can generate things of greater complexity than the modular approach discussed on my other answer.

# Answer
> 1 votes
One approach I had heard, (I want to try this, haven't had the opportunity yet) is to Generate a graph that is a regular arrangement of nodes (similar to the picture Pikalek posted) then work backwards from there to the Rooms you want.

i.e. The first node has only one corridor/exit so you pick a room at random from your selection of dead-end rooms and put that at your starting position. then maybe your next room has 3 exits (north south and east) so you pick a room at random from those you have with exits on the north south and east, and place it adjacent to your current room so the exits align.

This approach needs you to have created a whole lot of rooms, but can give you a map that looks more hand crafted than a purely procedural approach. (Diablo 3 is an example of this type of map generation.)

You can expand on the tile options By combining two horizontal nodes together and picking one Tile that fits over both nodes as well.

---
Tags: c#, procedural-generation, maps
---


# Question
Title: SocketException: No connection could be made because the target machine actively refused it
I am working on connecting a client to a server using socket connection. I have a button, when I click on the button, it's giving the below exception in Unity.

**"SocketException: No connection could be made because the target machine actively refused it."**.

What will be the issue? Can anyboady help me out? Below is the code I have written for connecting to the server:

```
internal Boolean socketReady = false;
NetworkStream theStream;
StreamWriter writer;
StreamReader reader;
try{
        connect = new TcpClient (host, port);
        theStream = connect.GetStream ();
        writer = new StreamWriter (theStream);
        reader = new StreamReader (theStream);
        return true;
        //socketReady = true;
    }
    catch(ObjectDisposedException) {
        return false;
    }

```

# Answer
The target machine actively refusing the connection means that no one is listening on that port, so the target machine refused the connection.

You'll need to verify that the server software you are trying to run is actually running and accepting connections.
> 1 votes

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


# Question
Title: Unity2D - Horizontal Scaling to Support Various Aspect Ratios?
I am trying to work out how to support various resolutions for my Android game. I have come up with a solution, but do not know how to implement it.

Automatically, I am told that Unity vertically scales the screen to match the screen, leaving more room at the sides. How can I change this behaviour? I am hoping to shrunk the game down till it fits horizontally, and filling it the background above and below with more decorative features. How can I achieve this?

I'm sorry if there is an obvious answer, I'm quite new working with the Unity UI system.

If it makes it any easier, my game is heavily based on UI, and is locked in landscape.

BIG EDIT: I completely rephrased this question because it was so broad and messy.

# Answer
> 1 votes
Okay, so I think I've got this worked out, so I'm making my own reply. I attached this script to the main camera.

```
using UnityEngine;

public class AspectRatioController : MonoBehaviour
{
    public float targetWidth;

    void Start()
    {
        Camera camera = GetComponent<Camera>();
        camera.orthographicSize = (targetWidth / camera.aspect) / 2;
    }
}

```

In the Unity Editor, set the targetWidth as the width, in units, of your background. This will change the camera size until the background fits perfectly, leaving extra space at top and bottom depending on your aspect ratio.

As for the safe zone, I decided to make two scenes for every menu: one for wider screens, one for squarer screens. The wider screens have 3:2 backgrounds, with a 16:9 safe zone, while the squarer screens have 1:1 backgrounds with 4:3 safe zones.

I hope this can help other people.

---
Tags: unity, camera, aspect-ratio
---


# Question
Title: Unity/vuforia imagetarget - object not showing properly
I learn it from vuforia tutorial on youtube.

I add a white cube(or sphere) as the child of image target.

When the camera catches the image target, the screen turns to be totally white. It seems that the object target is too large to show on screen.

When I move away from the image target, the camera works again. I tried a new project and repeated my steps many times, and I do succeed sometimes. I don't why most times it just shows part of object and fills all screen.

# Answer
> 1 votes
My guess would be, that your camera "Clipping Planes" are not set up correctly. For most image targets you have to increase the "far" field. I set the far field most of the times to 10000 and everything works fine.

I hope, that that can fix your problems :)

# Answer
> -1 votes
Make sure you have pre-set the scale correctly. If necessary, please set the scale in your code.

---
Tags: unity, vuforia
---


# Question
Title: Change color of a texture in a specific matrix location
I have following bool matrix:

```
bool[,] centerPiece = new bool[,] { { false, true, false }, { true, true, true }, { false, true, false } };

```

Using a method, I put a texture down every time the boolean hits true. Is there a way for me to select an individual texture in the matrix and change it's color independently, without changing the others in the same matrix?

I'm aware I have to use the `Color` method to change the color, and that to select a specific point in my matrix the syntax is along the lines of `centerPiece[1,1]`, but the rest baffles me.

# Answer
Instead of having a boolean array, you are going to want to consider creating a Tile class that will deal with your drawable entity that you see on your screen.

```
public class Tile {

    public Color Color;

    void Update() {
       //update logic
    }

    void Draw() {
       //render
       //spriteBatch.Draw(use your Color);
    }
}

```

Then have a Tile based array:

```
Tile[,] Tiles = new Tile[Width, Height];

// init your tiles
for (int x = 0; x < Width; x++) {
    for (int y = 0; y < Height; y++) {
        Tile tile = new Tile();
        tile.Color = Color.Red;
        Tiles[x,y] = tile;
    }
}

```

Then you can just change a tile color by indexing it like:

```
Tiles[0, 1].Color = Color.Blue;

```
> 0 votes

---
Tags: c#, xna, visual-studio
---


# Question
Title: C++ alternative to vector for arbitrary number of objects using pointers
I'm working on a prototype 'life simulation' game which incorporates any number of objects / entities that may exist in the game.

Up until this point I had been working with vectors of the objects, with every object that gets instantiated gets automatically copied into a vector that allows for some very simple all encompassing functions like:

```
physics_manager()
{
    for(std::size_t i = 0; i < all_objects.size(); i++)
        all_objects[i].do_physics();
}

```

However, I've run into a problem when it comes to using pointers. Previously I used pointers to elements within vectors to interact with objects like this:

```
class object
{
    //Attributes of object
    object * other_object_to_interact_with;
    std::vector<object*> carried_objects
    //etc
}

```

I've now realised that changing the size of the vector (a frequent occurrence in this simulation) causes all pointers to elements within that vector to point to some random piece of memory.

I've considered using some form of unique ID for this (e.g. an int assigned to each object, then searching the vector for an object with that int to identify the right one), but this feels like an inefficient and ultimately wrong way to do things.

My question is, is there a container similar to the std::vector that:
a) can be iterated through easily for functions such as the above
b) can hold an arbitrary number of objects that changes during program running
c) is safe to use pointers to elements within it even if the container changes size

Alternatively, is there a way to use vectors to achieve the above without using pointers?

UPDATE: An additional thought - would the issue below be present if instead of vectors containing actual objects, I used vectors containing pointers to objects? Presumably then any pointers to objects outside of the vector would be to the objects themselves - how well would C++ memory manage this or would this lead me into new / delete territory?

FURTHER UPDATE: I migrated to lists rather than vectors, which was surprisingly easy. My most commonly used code snippet was:

```
for(std::size_t i = 0; i < vector.size(); i++)

```

This was very easily changed to:

```
for(auto & i : list)

```

With 'i' now pointing to an actual object of the list rather than an int that can be used to access the vector with vector\[i\]. No perceptible performance hit so far with approximately 20000 objects being iterated through.

Additionally, when there is a need to use an 'int' as a reference to one of the objects within the list, that's as simple as:

```
int j = 0;
for(auto & i : base_class_vector)
{
    if(j == desired_number)
    {
        //Do whatever's needed here
        break;
    }

    j++;
}

```

# Answer
> 0 votes
The simplest container that fulfills the requirements you stated is `std::list`.

In this particular case, you shouldn't be using vectors, not just because adding new elements may invalidate references and iterators, but (and I am surprised no one mentioned it in the comments) because as you insert new elements, you are repeatedly re-allocating memory for the whole vector, which is inefficient.

Please have a look here to learn more about `std::list`. In fact, I would recommend familiarising yourself with the remaining STL containers (`vector`, `list`, `set` and `map` is all you need to make "informed" choices when deciding on what container to use, other containers are either their variation or are fairly specialised).

# Answer
> 0 votes
http://en.cppreference.com/w/cpp/container/deque **std::deque**

You still **get a operator\[\] for random access**, and can do deque\[5\] without needing to search through your container.

Your pointers are **memory stable** (auto\* j = &deque\[5\]; deque.push\_back(); \*j; is always valid.)

**Memory linearity** is better then std::list, since it organizes in buckets rather then a pointer to every element.

At the end of the day, std::vector or even std::array is always going to be better performing.

So I do recommend trying to **vector.reserve(MAX\_OBJECTS);** if you have a max amount of objects.

By calling reserve, you will both have memory stable pointers to those objects until pushed over the limit and you'll only have one memory allocation.

---
Tags: c++, vector, storage
---


# Question
Title: Unity Random.Range not repeat same position
I have this code that generates blocks in random position and it works but some times it generates blocks at the same position ,how can I fix it?

```
 var dupeobject : GameObject;

 function Start(){
     yield WaitForSeconds(0);
     var position : Vector3 = Vector3(Random.Range(-50,10),Random.Range(-10,5),Random.Range(-100,20));
     Instantiate(dupeobject,position,Quaternion.identity);
     yield WaitForSeconds(0);
     //Destroy(gameObject);
 }

```

# Answer
Because of the nature of Random this will happen occasionally because in a random set there is always a chance of collision. The only real way to mitigate this is to keep a list of positions you've seen before and then ignore and positions that collide. For example:

```
import System.Collections.Generic;

var dedupeobject : GameObject
var positionsSeen : List.<Vector3>

function Start() {
    yield WaitForSeconds(0);
    var position : Vector3 = Vector3(Random.Range(-50,10),Random.Range(-10,5),Random.Range(-100,20));
    while (positionsSeen.Contains(position) {
        position = Vector3(Random.Range(-50,10),Random.Range(-10,5),Random.Range(-100,20));
   }

   positionsSeen.Add(position)
   Instantiate(dupeobject,position,Quaternion.identity);
   yield WaitForSeconds(0);
}

```

As an aside, this looks suspiciously like UnityScript, rather than C# (which is what the question is tagged as)
> 1 votes

# Answer
In general, if you do not want randoms throwing the same value twice, you implement a Shuffle Bag.

Here's the idea:

1. Generate every possible outcome and store them in a list.
2. Remove from list randomly until list runs out.
3. Repeat.

Unlike what hobnob suggested, this can be done once in `Awake()` or `Start()`, is more efficient as you do not need to iterate through the entire list to check if the value has already been used every time you want a new random value, and will allow you to get random values during runtime as well with little overhead.

Here's an example:

```
//Initialize 2 lists
List<Vector3> shuffleBag = new List<Vector3>();
List<Vector3> shuffleBagBackup;

void Start()
{
    //x,y,z range is define in these nested for loops
    for (int x = -50; x < 10; x++)
    {
        for (int y = -10; y < 5; y++)
        {
            for (int z = -100; z < 20; z++)
            {
                shuffleBag.Add(new Vector3(x, y, z));
            }
        }
    }

    shuffleBagBackup = shuffleBag;
}

```

And whenever you want to get a new random position within your range, call this:

```
Vector3 GetRandomPos()
{
    if (shuffleBag.Count == 1)
    {
        Vector3 pos = shuffleBag[0];

        shuffleBag = shuffleBagBackup;

        return pos;
    }

    int index = Random.Range(0, shuffleBag.Count);

    Vector3 position = shuffleBag[index];

    shuffleBag.RemoveAt(index);

    return position;
}

```

Looking at the code that you've provided, you may also consider making the list a singleton and the `GetRandomPos()` function static, should you need to access the random positions from multiple objects with this script.
> 4 votes

---
Tags: unity, javascript, unityscript, random
---


# Question
Title: Where to put SFML Window in GameStateManager
I have a Pong game using SFML organized after this tutorial.

This is the UML diagram from the tutorial.

Now I am not sure where I should put my SFML RenderWindow variable (and other things that might need to be shared between game states.

I have a PlayingGameState with a shared\_ptr to a GameStateManager. So the right place should be the GameStateManager class. Or should I put it into the DirectRenderingGameStateManager and change the shared\_ptr to DirectRenderingGameStateManager?

# Answer
> 0 votes
The instance of your `sf::RenderWindow` should go in your `DirectRenderingGameStateManager`. You have it marked as `<<interface>>` in your diagram but you've given it variables, so I'm assuming it's really an abstract (or concrete?) class. Either way, there's no reason for it to go in `GameStateManager` as that interface has no correlation to graphics.

Generally, place things as low as possible in your inheritance tree and as high as needed. That is: No reason for `GameStateManager` to know anything about the `RenderWindow`, but sharing it netween all your `Drawable`s is asking for trouble.

---
Tags: c++, sfml, game-state
---


# Question
Title: Why are floats not changing unless I've selected the prefab?
I am making a really simple game where you are a dot and you go around and shoot other dots. I have it set up so in the start menu you can spend points to upgrade your dots stats. (ie. make it shoot faster, move faster.) I am using a prefab `NumberHolder` object with a script on it to hold the numbers between scenes and I am having an issue. If I have the `NumberHolder` selected in the inspector the game works perfectly, but if I don't have it selected the numbers all change like normal while I am on the scene that adjusts the numbers, but when I go to the next scene which is the game the numbers seem to have a 50% of not updating to the player. Furthermore, if I select the `NumberHolder` at this point the numbers are all still at their starting stats. I used to have the `NumberHolder` located 3 folders deep, Assets/Prefabs/StatHolders and it didn't work at all unless it was selected. I have since moved it up to the Prefabs folder and it now works around 50% of the time. Do I have it to deep? If so is there a way to work with it that deep because I want to try and stay organized or is there a whole better way of doing what I am attempting to do here?

I am using Unity 5.4.0f3 and coding in C#.

# Answer
Prefabs are templates, the prefabs outside of a scene are not supposed to change at runtime. If you need to save player data between scenes there's a variety of options:

* Set a gameobject as don't destroy on load - it will persist between scene changes
* Use static variables
* Create a non-monobehaviour singleton
* Save data to playerprefs
* Use additive loading instead, so game objects naturally persist between scenes
> 0 votes

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


# Question
Title: Implementing an AI controller for Pacman
I'm currently implementing an AI controller class that is being used to determine the moves that ms.pacman should make to collect pills and avoid ghosts. In order to determine which is the best move to make in each state (configuration) of the game, I'm using Breadth-First Search to search the decision tree at each state. I've gotten the controller to work (at least somewhat) for Depth-First Search so I was trying to apply the same logic here.

The idea for DFS was to start with a "root" or driver function which would iterate through the possible moves ms. pacman could make at each state in the decision tree and then make a call to a recursive function that searches the tree to find the terminal state (point at which all pills have been eaten) with the highest value (e.g. highest score). This value is returned from the recursive function and stored in a variable in the root function. The root function the returns the move (out of possible moves) that had the highest value in the tree.

Since BFS is not recursive, I was thinking that it wouldn't be necessary to have a driver function like this, so I decided to put it all in one function. Based on DFS, I'm implementing BFS using a queue which stores all of the neighboring states of the current state and visits each state in FIFO order. Once a state is reached in which all pills have been eaten, the current Move should be returned. I'm not sure if this is the best approach, but its what I could come up with. The problem is that the code for the function takes too long to run and ms.Pacman immediately just goes left and runs into a wall. I'm assuming this is because the terminal state is never being found. Here is the function (in Java):

```
  public MOVE bfs(Game state){
        EnumMap<GHOST,MOVE> ghostMove = new EnumMap<>(GHOST.class);
        MOVE bestMove = MOVE.NEUTRAL;
        Queue<Game> q = new LinkedList<>();
        q.add(state.copy());
        while(!q.isEmpty()){
            Game current = q.peek();
            q.remove();
            for (MOVE move : current.getPossibleMoves (current.getPacmanCurrentNodeIndex())) {
                Game neighbor = state.copy();
                neighbor.advanceGame(move, ghostMove);
                q.add(neighbor);
                if ((current.getNumberOfActivePills() == 0) && (current.getNumberOfActivePowerPills() == 0)) {
                    return move;
                }

            }
        }
        return bestMove;
    }

```

**Is there anything wrong with the design of the algorithm that could be causing this problem?**

# Answer
> 1 votes
You are using brutal force to find the solution, so you can't expect that to run fast.

I'll list some improvements for you:

* Implement a fitness function which evaluates how good is a node.
* Sort the node list with the next formula: V = p\*f + (1-p)\*d. p is a constant between 0 and 1. f is the fitness function and d is the actual node depth(not the tree depth, the node depth).
* Be carefull about the fitness function, if you want it to find a solution, it should never evaluate better a worse node, and it should return 0 for a solution node. You can start for example with 1 for all the nodes and 0 for the solution ones, and then start thinking about some penalties to make a decision worse than another in every case by adding some values. For example, if a decision is a move which will kill the character, you can set that value to infinite. Another example, a move which take a ball is better than a move that doesn't take it. It is just a example, think about it and you will find more examples.
* You should also take in account that you will have invalid moves. For example if you are in front of a wall, you cant move forward.

It is just A\* algorithm, it will solve your problem easily.

Pseudo-code:

```
Node A_Star_Algorithm(Node initial)
{
    List open-nodes;
    List close-nodes;
    open-nodes.add(initial);
    Node actual;
    while(open-nodes is not empty)
    {
        actual = open-nodes[0];
        open-nodes.erase(0);
        close-nodes.add(actual);
        if(actual is solution)
        {
            return actual-node;
        }
        else
        {
            List new-nodes = getChilds(actual, open-nodes, close-nodes);
            open-nodes.addAll(new-nodes);
            sort(open-nodes, A_STAR_ECUATION); // we sort the open list placing first the smaller values
                                                // this will make that in our next iteration we will analize
                                                // first the best values

        }
    }
    return NULL;
}

const float p = 0.5f // Value between 0 and 1

bool A_STAR_ECUATION(Node A, Node B)
{
    float H_A = p*FITNESS_FUNCTION(Node A) + (1-p)*A.GetCost();
    float H_B = p*FITNESS_FUNCTION(Node B) + (1-p)*B.GetCost();
    return H_A < H_B;
}

List getChilds(Node actual, List open-nodes, List close-nodes)
{
    List childs = getPosibilities(actual);
    for(int i = 0;i<childs.size();i++)
    {
        for(int k = 0;k<open-nodes.size();k++)
        {
            if(open-nodes[k] == childs[i])
            {
                if(childs[i].GetCost() > open-nodes[k].GetCost())
                    childs.remove(i);
                break;
            }
        }
    }
    for(int i = 0;i<childs.size();i++)
    {
        for(int k = 0;k<close-nodes.size();k++)
        {
            if(close-nodes[k] == childs[i])
            {
                if(childs[i].GetCost() > close-nodes[k].GetCost())
                    childs.remove(i);
                break;
            }

        }
    }
    return childs;
}

```

The cost of a node is the number of moves required to reach it. The initial node for example is 0, and his childs have cost 1. The childs of this childs have cost 2....

The p value is for give more importance to the heuristic or to the cost of the node. In this case i chose to give equal importance, but if your heuristic is good, you can increase this value from 0.5f to 0.8f for example.

If your heuristic is admissible, which means that it doesn't give better values to nodes which are worse than anothers, it will find the best solution.

# Answer
> 0 votes
This algorithm assumes that the game state progresses unavoidably towards an end state. However, it is possible for ms pac-man to move around (e.g. in a circle); with ghosts chasing her, whilst no pills are being consumed. If this happens, the algorithm will not terminate.

So, I think you have to figure out a way to detect (or avoid) cycles. There are better ways to prevent cycles, but I think the simplest way is to limit the number of moves (doing something like the code below).

```
 ...
 while(!q.isEmpty()){
        Game current = q.peek();
        q.remove();
        if (q.moveCount() < MAX_MOVES) {
            for ...
 ...

```

If you want to consider a alternative way to tackle this problem, have a look at behaviour trees, and work in the A\* algorithm to aid behaviour decisions and improve behaviour actions.

---
Tags: java, ai, search
---


# Question
Title: Unity Android game all squashed in center of screen (portrait layout), help
I'm developing a demo for Android game in Unity with portrait layout. I used the ViewportHandler script found here (How do you handle aspect ratio differences with Unity 2D?) and it worked well. Yesterday I updated Unity (foolish move I know, two days before deliver of a project!!) to 5.4.2f2 (was using 5.4.1f1). I don't know if that is the reason but now I can in no way get my correct layout again. Sure, it is portrait but all squashed in the center and taking about one-third of the screen, rest just background camera-colour. Things looked well yesterday but now I'm in big trouble :(

Any help would be greatly appreciated!

# Answer
> 0 votes
Start downloading the older version and install it. Build it for every platform that you want it for once you have it working again.

As for the question is there any chance that you could give a screenshot (I know that will probably not be possible)? Try creating a new project then try the script with a very simple scene.

* If it works figure out what is different, keep in mind sometimes updates clear the settings that you have applied to scripts (values, references to GameObjects, etc.).
* If it doesn't work in the new project it's time to debug the code. Possibly look at the change logs and see if anything changes how the camera works or if the viewports are different.

I'm guessing that it is the former, I've had it happen a few times which meant that i had to go back and look at the version before in my version control to see what the scrips values used to be before they got reset.

Side note: I would have written this in the comment section but I hit the character limit... sorry :)

Hope this helps anyway.

---
Tags: unity
---


# Question
Title: MissingComponentException: There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it
When I run my program I keep getting: `MissingComponentException: There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it.`Even though I have attached it as you can see:

In the script I am trying to edit the text of the Text Mesh like this¨:

```
private int count;
public TextMesh countText;

// Use this for initialization
void Start () {

    count = 0;
    counterText = gameObject.GetComponent<TextMesh>();
    counterText.text = "Count: " + count.ToString();

}

```

What I want is to count the cans that have been shot, so what I do next is:

```
  void OnCollisionEnter(Collider other)
{
    if (other.gameObject.CompareTag("Can"))
    {
        other.gameObject.SetActive(false);
        count = count + 1;
        counterText.text = "Count: " + count.ToString();
    }
}

```

# Answer
One thing I notice is that you have a public TextMesh property called countText that is populated in the inspector in your screenshot... but that's not what you appear to be using in the script.

Instead you seem to be using a different count**er**Text variable which is initialized by getting a TextMesh component from the gameObject the Hit component is on (which it sounds like does not exist).

If your countText property is populated with the TextMesh you want to use like it seems, I would just remove the `counterText = gameObject.GetComponent<TextMesh>();` line and switch all the others from counterText to countText, which should make them use the one that you apply in the inspector without issue.
> 1 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: Determine the z coordinate of a deformed plane based on uv (xy) coordinates
I am using a formula to turn the following texture

into what looks like two 3 dimensional planes

The formula I am using for the texture deformation is

`float2 texUV = float2(uv.x / abs(uv.y), (1.0 / abs(uv.y)));`

Based on the deformation equation above, how can I work out a value for z on the surface of the plane at any given uv (xy) coordinate?

# Answer
> 5 votes
Your image can be interpreted a couple different ways so I will make a few assumptions up front:

* The "geometry" you are emulating is meant to look as if it has already been "projected" (if it was plane geometry and ran through MVP matrices it would produce similar output).
* The planes are flat and not angled.
* The planes are both 0.5 units away from the camera in the vertical z axis.
* Assume the viewport is perpendicular to both of the planes
* No scale, FOV, aspect ratio for the viewport is given. We assume some further down

These assumptions describe a simple version of your scene. We will look at breaking some of these assumptions throughout the answer but keep this in mind for now.

To demonstrate the different depth values, I made a similar image to your question.

```
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    //To recreate your picture
    vec2 screenUV = fragCoord.xy / iResolution.xy;
    vec2 uv = screenUV.xy * 2.0 - 1.0;

    vec2 texUV = vec2(uv.x / abs(uv.y), (1.0 / abs(uv.y)));
    vec4 color = texture2D(iChannel0, texUV);
    color = vec4(color.r, 0.0, color.ba);
    color = mix(vec4(0.0,0.0,0.0,1.0), color, abs(uv.y));

    fragColor = color;

    /*To render depth values
    fragColor = vec4(0.0, depth, 0.0, 1.0); //Just z
    fragColor = vec4(fragColor.r, depth, fragColor.ba); //With original textures

    will be shown in green!*/
}

```

You have `texUV.y` calculated which is over the range `[1, +Inf),(+Inf, 1]`. This is because `1.0/abs([-1.0,1.0]) == [1, +Inf),(+Inf, 1]`. This will be the basis for our depth value as it's what is used to create the planes that have the texture of unit length applied to them. To be a depth value we need to convert it to a \[0,1\] linear range. To do this we need to

1. Get rid of infinities by clip the original range at a near and far plane.
2. Apply a scale factor such that the planes are properly "projected" (one unit of texture is one unit of world space)

The near plane and far plane are based on your particular use case. I have chosen `0.001` and `100.0` for this example.

```
const float nearPlane = 0.001;//Depth of 0.0
const float farPlane = 100.0; //Depth of 1.0

```

The scale factor determines for every unit length of the the plane (which is delineated by one repetition of your texture), how many world space units should there exists. It would seem at first glance we could just choose a simple multiplier but remember we have a scene that's already been "projected". So, actual scale factor needs to reflect the "camera" that's viewing the scene.

If the planes were completely perpendicular to the camera before they were projected, the scale factor is based entirely on the slope of the bottom plane of the camera. We choose a fake FOV and aspect ratio for demonstration but you can use whatever values suit you for these.

```
const float PI = 3.141592;
const float camFOV = 80.0 * PI/180.0;
const float aspectRatio = 4.0/3.0;

const float camYSlope = tan(atan(aspectRatio * tan(camFOV/2.0))/2.0);

```

If the planes weren't completely perpendicular, a large value (for planes angled towards the camera) or a smaller value (for planes angled away from the camera couple be substituted for camYSlope. A different vertical z value adjustment would need to be used in the depth calculation as well (instead of the 0.5 assumtion)

The depth can then be calculated like so:

```
float depth = (clamp(
    (texUV.y-1.0)  //Shift by 1 backward ([0, +Inf) (+Inf, 0]
    *camYSlope    //Scale by some factor of world units / uv units, using fake camera values gives real output
    +0.5           //Add 0.5 to assume that an extra vertical distance for top and bottom plane fragment depth is included
    , nearPlane, farPlane) //Clamp to the near and far plane [nearPlane, farPlane]
    - nearPlane) //Remove the shift [0.0, farPlane - nearPlane]
    / (farPlane-nearPlane) //Remove the scale [0.0, 1.0]
    ;

```

Putting it all together we get

```
const float nearPlane = 0.001;//Depth of 0.0
const float farPlane = 100.0; //Depth of 1.0

const float PI = 3.141592;
const float camFOV = 80.0 * PI/180.0;
const float aspectRatio = 4.0/3.0;

const float camYSlope = tan(atan(aspectRatio * tan(camFOV/2.0))/2.0);

float depth = (clamp((texUV.y-1.0)*camYSlope+0.5, nearPlane, farPlane) - nearPlane) / (farPlane-nearPlane);

```

All of the above code can be played with at this shader toy. Changing the `nearPlane`, `farPlane`, `camFOV`, and `aspectRatio` and hitting `ALT + ENTER` will update the shader to show the various changes.

Using this final value equation and modulating the near and far plane we can easily change the desired depth values.

`nearPlane = 0.001; farPlane = 15.0; //A closer farPlane`

# Answer
> -1 votes
For this solution you are gonna need to know what is the normal of the botton and top plane. Lets say we have 2 planes defined by a normal N1 and N2 and a distance from the origen D1 and D2. We also have a XY point, P and a Z vector from this point V(0,0,1).

We will calculate Z1 (coordenate Z respect plane 1) and Z2 (coordenate Z respect plane 2)

```
t1 = -(P.Dot(N1) + D1) / V.Dot(N1)
Z1 = (P + t1*V).z

t2 = -(P.Dot(N2) + D2) / V.Dot(N2)
Z2 = (P + t2*V).z

```

You can choose for example the min(Z1,Z2) if it is what you want. If you dont know how to obtein D1 and D2, they are defined by:

```
D1 = N1.Dot(Any point on plane 1)
D2 = N2.Dot(Any point on plane 2)

```

If you dont know the normal of this planes but you know 3 points(we will call them P0 P1 and P2) of each plane you can calculate the normal by:

```
N = (P2 - P0).Cross(P1 - P0).Normalize()

```

Hope it helps

---
Tags: mathematics, rendering, hlsl, geometry
---


title: Count when object is destroyed

text:
# Question
Title: Count when object is destroyed
I've made a shooting game, where you shoot as many cans as possible. However, I faced a problem when counting the cans that are shot. I've tried using `void onDestroy()`, but it doesn't react when I shoot a can. Furthermore the *Text Mesh* I've set doesn't change. I've put the text mesh in the script correctly, in the editor.

What am I doing wrong?

# Answer
> 0 votes
Let's take a look at the Unity API:

> # MonoBehaviour.OnDestroy()
>
> ## Description
>
> This function is called when the MonoBehaviour will be destroyed.
> OnDestroy will only be called on game objects that have previously been active.
> <sup>**\- Unity Scripting API: MonoBehaviour.OnDestroy()**</sup>

---

You **must** call `OnDestroy()` for logic pertaining to when the object is destroyed. `onDestroy()` is an entirely differant method, with no explicit functionality.

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


# Question
Title: Setting up a draw class giving exceptions
I'm currently trying to set up a class to draw tiles for me in different shapes, but it's currently giving me a hard time, as it's giving me nullreferenceobject errors in my secondary class. My Game class:

```
public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Tile tl = new Tile();

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 960;
            //graphics.IsFullScreen = true;

        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

           base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Content.RootDirectory = "Content";
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        ///

        inputForm iForm = new inputForm();

        bool[,] centerPiece = new bool[,] { { false, true, false }, { true, true, true }, { false, true, false } };
        bool[,] cornerPiece = new bool[,] { { false, true, false }, { true, true, false }, { false, false, false } };
        bool[,] stairPiece = new bool[,] { { false, true, false }, { true, true, true }, { false, false, false } };
        bool[,] straightPiece = new bool[,] { { false, true, false }, { false, true, false }, { false, true, false } };
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            // Draw the sprite.
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

            //Draw centerPiece
            tl.centerPiece(spriteBatch, centerPiece);

            spriteBatch.End();

            base.Draw(gameTime);

            //iForm.Show();
        }
    }

```

And my tile class:

```
 public class Tile : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        public float spacing = 32f;
        public Texture2D squareTex;

        public Vector2 IMGCenter()
        {
            Vector2 imageCenter = new Vector2(4 / 2f, 4 / 2f);
            return imageCenter;
        }

        public Vector2 screenView()
        {
            Viewport viewport = GraphicsDevice.Viewport;
            Vector2 screenCenter = new Vector2(viewport.Width / 2f, viewport.Height / 2f);
            return screenCenter;
        }

        public Tile()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            squareTex = Content.Load<Texture2D>("square");
        }

        public void centerPiece(SpriteBatch batch, bool[,] squareCombo)
        {
            for (int x = 0; x < squareCombo.GetLength(0); x++)
            {
                for (int y = 0; y < squareCombo.GetLength(1); y++)
                {
                    if (squareCombo[x, y] == true)
                    {
                        Vector2 offset = new Vector2(x, y) * spacing;
                        Vector2 position = IMGCenter() + offset;

                        batch.Draw(squareTex, screenView(), null, Color.White, 0f, position, 1f, SpriteEffects.None, 0f);
                    }
                }
            }
        }
    }

```

EDIT2: My current error:

```
An unhandled exception of type 'Microsoft.Xna.Framework.Content.ContentLoadException' occured in Microsoft.Xna.Framework.Graphics.dll.
Additional information: Error loading 'square' GraphicsDevice component not found.

```

# Answer
The issue is how you try to load your content. This way your texture is never correctly initialized. There are a couple of ways to solve your issue.

First, note there is a Content Manager (it is the `Content` variable in the main class). This is not a global scope variable- you either need to pass it to other classes that need to load content, *or* you need to create a new Content Manager in the other class.

The easiest way to solve your issue is this:

Change your Tile constructor to this:

```
public Tile(ContentManager content)
    {
        squareTex = content.Load<Texture2D>("square");
    }

```

And pass the contentmanager when you create your tile:

```
Tile tl = new Tile(Content);

```

Since you need an initialized Content Manager for this, I suggest to create your tile in the `LoadContent()` method.

The Content Manager is quite smart, it won't load the content it already knows. So even if you create a new tile, the Content Manager will reference the same texture. Still there are other options that may help you in the long run.

1. Create an 'Assets' class, where you load all the content your game needs. Reference these textures in your object Draw methods.
2. Pass textures on creation of your object. This makes your objects reusable with a graphic variation (example a player's spaceship class could be instantiated with a red texture for player 1 and a blue texture for player 2).
> 0 votes

# Answer
Your class structure is not typical. There is no reason to have your `Tile` class inherit a `Game` class. This instantiates 2 `Game` objects. No need for that. Drop the inheritance. You only need one Game object. If you need to exchange data or use Game methods from the `Tile` class, provide the `Tile` class with a reference to the game class, but don't inherit from it.

Next, at the beginning of your `Game` class, declare a `Tile` object instead of "newing" one. Then "new" it in the load content class after the Game lass has had a chance to initialize its Graphics device & Content manager. Pass the Content Manager and Graphics Device to the `Tile` Class in a manner similar to how Felsir indicated.

Additional info: Your error is because it can't find the GrapicsDevice... not the content. The GraphicsDeviceManager you are creating in your Tile Class will not initiate unless a Game's Run() method is called. The Framework calls that internally for the main Game object but never for the Tile's inherited Game object which is the device being used to load... That's why your error is saying it can't find the GraphicsDevice, not the tile content.
> 0 votes

---
Tags: c#, xna, visual-studio
---


title: Get a camera's frame-buffer in Unity

text:
# Question
Title: Get a camera's frame-buffer in Unity
Is there a way to "record" the display of a camera instead of rendering it on screen?

For example, if I want to stream a camera's frame block to an external application.

# Answer
> 0 votes
This feature is also called Render-to-texture, or FBO rendering.

You can check how to do it on Unity here: https://docs.unity3d.com/Manual/class-RenderTexture.html

---
Tags: unity, frame-buffer, streaming
---


# Question
Title: What does glBlendFunc do when given an incorrect enumeration value?
In cocos2d-x, I am using particle system from plist with blend values: dst = 1, and src = 100 which is wrong enum for gl\_blend.

Although app logged "OpenGL error 0x0500" but it still run and showed a good blend effect. And i can not find the right pairs of dst and src to recreate that effect.

So i hope someone can tell me how BlendFunc / gl\_blend will work when it having bad src value. Base on that i hope i can recreate that effect without using wrong src value. Thanks

# Answer
It's unspecified.

What that means is that the GL implementation is pretty much free to do whatever it wants. It might change nothing, it might reset to the defaults, it might make a best guess, it might do something else entirely different, and which of these it chooses might depend on other state set elsewhere. Also, you can't depend on somebody else's hardware doing the same thing.
> 2 votes

# Answer
Setting aside for a moment the question over whether or not calling an OpenGL function with illegal parameters will have an effect or not, here's how to actually get the information you want:

```
GLint blendSrc;
GLint blendDst;
glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc);
glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst);

```

This code snippet will tell you what the current OpenGL src and dst blend states are. So if OpenGL's blending is behaving the way you want, this will tell you what values it's actually using.
> 1 votes

---
Tags: opengl, cocos2d-x, particles, blending
---


title: Reset Camera view - webgl

text:
# Question
Title: Reset Camera view - webgl
I have camera rotating by dragging mouse.
Im trying to add reset button that restart the scene to initial view.
The rotating camera works as expected but I can't figure out how to reset it.
The scene rotating in weird directions, not as expected.

I have 2 vars - `absX`, `absY` which hold the overall change angle value from the init mode.

when reset applied:

```
mat4.rotate(getRotationCameraMat, degToRad(-absX/10), [0, 1, 0]);
mat4.rotate(getRotationCameraMat, degToRad(-absY/10), [1, 0, 0]);
absX=0;
absY=0;

```

apply the rotate:

```
mat4.multiply(mvMatrix, cameraRotationMat);

```

the camera code:

```
var mouseDown = false;
var prevMouseX = null;
var prevMouseY = null;

var cameraRotationMat = mat4.create();
mat4.identity(cameraRotationMat);

function handleMouseDown(event){
    mouseDown = true;
    prevMouseX = event.clientX;
    prevMouseY = event.clientY;
}

function handleMouseUp(event){
    mouseDown = false;
}
var absX=0;
var absY=0;

function handleMouseMove(event){
    if (!mouseDown){
        return;
    }

    var currentX = event.clientX;
    var currentY = event.clientY;
    var deltaX = currentX - prevMouseX;
    absX+=deltaX;
    var newRotationMatrix = mat4.create();

    mat4.identity(newRotationMatrix);
    mat4.rotate(newRotationMatrix, degToRad(deltaX/10), [0, 1, 0]);

    var deltaY = currentY-prevMouseY;
    absY+=deltaY;
    mat4.rotate(newRotationMatrix, degToRad(deltaY/10), [1, 0, 0]);

    mat4.multiply(newRotationMatrix, cameraRotationMat,cameraRotationMat);

    prevMouseX = currentX;
    prevMouseY = currentY;

}

```

# Answer
You don't need to do anything like that. If your camefa had no rotation before the user started using the apl, then you can simply create an identity matrix and set the camera's view matrix to it, or set every value back to 0.

If your camera had an initial position, you should store it in an object

```
var initialPos = {
    position: pos.clone(),
    // Do the same with the rotation
    // Make sure you clone the vectors so you don't have reference problems
}

```

Then when you want to reset it to the original position, you just set everything back.

If you don't use positions and rotations, and you immedialitely apply the transformations to the matrix (which is a terrible idea btw), then you can just copy the matrix and store it somewhere, then use it later to change it back.
> 0 votes

---
Tags: opengl, 3d, javascript, graphics, webgl
---


# Question
Title: How do I make wasd controls for a top down game in unreal engine 4.13.1
I've been trying to make controls for a top down game in unreal engine 4 but I can't figure out how to make it and all the tutorials I've been seeing are outdated.

# Answer
The tutorials are perfectly fine for 4.12 and 4.13. If you are scared of incompatibility issues just download the version that is being used in the tutorial. The differences are subtle.

To your actual question. I recommend you watch these videos to learn about blueprints and input. https://docs.unrealengine.com/latest/INT/Videos/Blueprints/index.html

You will learn there abouth how the camera is set up in relation to the player through a thing called CameraBoom (SpringArm) component. And that if you translate the spring arm to the top of the player you will have the third person controls and the top down view you want to achieve.

This is the completest answer I can give since you have not defined your problem enough. Watch the tutorials for blueprints and make your game!
> 1 votes

# Answer
First of all, when the docs or other official guides are signed for precedent version of the engine this mean that these are still the same for the newer version of the engine.

When you create a new project on UE4 you can select a Template project (c++ / blueprint) where start to develop the game. You can select one of this template to see how the controller is implemented.

Try to read the documentation https://docs.unrealengine.com/latest/INT/Gameplay/Framework/Controller/PlayerController/

If you have other questions on UE4 this is the best place where to write https://forums.unrealengine.com/
> 0 votes

---
Tags: unreal-4, blueprints
---


# Question
Title: Verify if a circle is completely inside a rectangle or not?
I am a beginner in game development. I am using the libGDX library.

I'd like to know the best algorithm to verify if a circle is completely inside a rectangle. I tried using the the static method `overlaps()` of the `Intersector` class like this:

```
if(!Intersect.overlaps(ball.getBoundingCirle(), wall.getBoundingRectangle())) { // ball is a circle and wall is a rectangle
            ball.reset(midPointX, midPointY);
        }

```

but I won't be accurate. I have read a lot of algos for circle and rectangle collision what I want is to detect when the circle touches any of the side of the rectangle (while inside). I read this answer but it didn't help me.

# Answer
> 3 votes
Will the rectangle always be straight or can it sometimes be put at an angle? If it is straight(not at an angle), Then in the circle class you will have to define a radius and a center point and for the rectangle the top left and bottom right coordinates, then you could check if it goes outside as follows:

```
if(circle.getX()+radius>rectangle.getBottomRight().getX()){
    //it is outside of the rectangle on the right side
}
else if(circle.getX()-radius < rectangle.getTopLeft().getX()){
    //it is outside on the left side
}
if(circle.getY()+radius>rectangle.getBottomRight().getY()){
    //it is outside of the rectangle on the bottom side
}
else if(circle.getY()-radius < rectangle.getTopLeft().getY()){
    //it is outside on the top side
}

```

If it isn't straight then you should rotate it to align it with the axis and then also rotate the circle's center point. After that you can use the above calculations. (Thanks to Patrick Hughes for pointing that out)

---
Tags: java, 2d, collision-detection, libgdx
---


# Question
Title: How about fitting into gaming industry with Design and Development mindset and seeking for a masters degree?
Might be the question is a bit weird but that's what I'm focused on and want to discuss about obtaining a masters degree to fulfill my dreams to work as both designer and developer.

I work as a programmer with 5 years of experience and I code in C, C++, C#. Back home I design Application UX, Logo, Banners, Website graphics, Write small software for personal needs or friends and yes I like to play games.

Now, holding a bachelor degree in Computer science and professional experience I want to opt for a Masters degree abroad(probably in Europe) with focused subject(may be Game design/development). Now my problem is that I do not like to do a formal Computer science masters as it would be a traditional process of learning computer systems. As well as I don't like mathematics in dept, having said that I do use calculation and business logic a lot in my programs but I'm not very much fond of them. So basically I'm a design creativity guy with developer mindset. I developed quite a few windows applications on my own and some of them are live on Softpedia.

So I like to pursue my future with the mix of both. Is there any way for me to fit into game industry? If not what would be better for me rather than continue only programming job profile?

# Answer
It seems this is a two part question.

> Where could I fit into the gaming industry?

As the gaming industry is still quite new, I'd say it's still quite flexible as to how you would go about getting into it. There is a lot of tips on this if you do a google search. Basically tho, since the rise of indie development, there are two routes:

* Apply for a job at a company, these come in all sizes, from one to thousands of people. Sure a nice degree will help you, especially for the bigger companies, but the most important part I'd say is that you can showcase your skills through a portfolio or experience. If you are really good at something, you will be able to get a job, and this is especially true in the gaming industry.
* Go indie. i.e. start on your own and make games, or join others who are doing the same. This is a very popular route in the past years and very many people are doing it, thus there is a lot of competition, not to mention that finishing a game, getting it sold and running a company are huge challenges. It's become easier tho with easy to learn tools such as Unity and Unreal engine, and distribution platforms such as Steam and the appstore.

> What masters degree should I take to focus my game developer career?

I think this question is very country & university specific as you are a bit limited to where you are willing to study. Say you can study anywhere in the world. Looking through the whole worlds university programmes is quite a daunting taks, but I'd search for any schools offering game development bachelors and see what they offer in masters degrees.

Masters degrees tend to be a bit more specific tho, and I think you'd end up choosing a specialty that isn't really game specific, but rather computer engineering.

In the end tho, as I stated in the answer above, if you really want to get into the industry you should really just become really good at what your doing and build a portfolio and apply for jobs. I think that would help you a lot more than a degree.
> 0 votes

---
Tags: game-design, graphics, ui-design, education
---


# Question
Title: Trouble with LineRenderer with orthographic camera in Unity
When a weapon is fired, I want to draw a line for the bullet's trajectory.

I am using a LineRenderer to draw the trajectory with the code below:

```
    void FixedUpdate () {
        timer += Time.deltaTime;

        if (Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0) {
            Shoot ();
        }

        if (timer >= timeBetweenBullets * effectsDisplayTime) {
            DisableEffects ();
        }
    }

    void DisableEffects () {
        gunLine.enabled = false;
    }

    void Shoot () {
        timer = 0f;

        // Set first point
        gunLine.SetPosition (0, transform.position);

        shootRay.origin = transform.position;
        shootRay.direction = -transform.forward;

        gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
    }

```

I am using an orthographic camera in the scene. The line will show up but at certain rotations the line will partially render or be completely hidden. Oddly, the line will always render in the scene view-- the problem only exists in the game view.

Has anyone had this issue?

# Answer
I don't really have answers for your problem but that might help you a bit.

Which version of Unity3D are you using ? Unity 5.5 beta contains an improved line rendered so you could actually fix your issue just by upgrading Unity.

See https://blogs.unity3d.com/2016/08/30/get-the-unity-5-5-beta-now/

Or you could try some assets like "Volumetric Lines" from Johannes Unterguggenberger which is a more advanced line rendering system.
> 1 votes

---
Tags: unity
---


# Question
Title: Unity - protect MonoBehaviour-derived classes from instantiating via new in C#
When the class hierarchy grows and you deal with a lot of custom types in your project, it sometimes becomes hard to remember which types are allowed to be created via `new` and which types are derived from MonoBehaviour and therefore can't be created via `new` but must instead be attached to the GameObject as a Component.

Is it possible to have some safety-mechanism for this? The goal would be to have two base classes to control the ability to use `new` on a certain type. Ideally resulting in a compile-time error instead of an easy to miss warning in the console (*"You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. Blah blah."*).

My attempt to make the constructor protected, like this

```
public class UnCreatableBase : MonoBehaviour {
    protected UnCreatableBase() {
        // using new should be not allowed
    }

    public static T Create<T>() {
        // instead this method allows object creation
        return GameObject.Instantiate (Resources.Load ("Prefabs/" + typeof(T).Name) as GameObject).GetComponent<T>();
    }
}

public class CreatableBase {
    public CreatableBase() {
        // new is ok here
    }
}

```

still allows me to write:

```
var whyDoesThisWork = new UnCreatableBase();

```

I can access the protected constructor even from an outside scope.

Now, the obvious solution would be to make constructors of MonoBehaviour-derived classes private. Manually. All of them. Manually. I was wondering if there's a way of achieving the same in a more generic way.

# Answer
> 0 votes
The way I lay things out is to have items that exist in the world be Monobehaviours where as supporting processing functionality should be classes. This can further be deliminated by using a C prefix on all processing classes. I.e.

new CCaclualtor(); new CTracking(); new CDateParsing();

GameObject.Instantiate(MyPrefab);

That way, by the type, you know what you should be doing.

---
Tags: unity, c#, software-engineering
---


# Question
Title: How to draw and store a Zelda-like map in custom game engine?
I have a school assignment where I have to draw a 2D map from one of the first zelda games, along with some animated sprites. Now I got the sprites to work, Im having trouble drawing the map. This is what it should look like:

This is the TileSet that we have to use to draw the map (each tile is 32x32 pixels):

We work in a custom game engine that our teacher made for us.

To draw a bitmap we use this command: GAME\_ENGINE.DrawBitmap(\[Name\], x.cord (on the canvas), y.cord (on the canvas), x.cord(on the Tileset), y.cord(on the Tileset), amount of pixels you want to cut out of the Tileset (Width), amount of pixels you want to cut out of the Tileset (Height).

If I use this command I would draw the staircase tile (top left) on the canvas: GAME\_ENGINE.DrawBitmap(\[Name\], 200, 200, 0, 0, 32, 32);

So I found out that with a nested for loop you can draw a 2D map on the canvas, this is the code I used for that:

```
for (int y = 0; y < 10; y++)
{
    for (int x = 0; x < 16; x++)
    {
        GAME_ENGINE.DrawBitmap(Link_Level, 128 + (x * 32), 0 + (y * 32), 0, 0, 32, 32);
    }
}

```

But obviously then it draws a 16 x 10 map consisting of only one tile.

My question is: How can I use that same for loop but somehow let it know which tiles to draw on the correct position?

Any help would be appreciated!

# Answer
This is where your tilemap will come to use, you create an array of tiles, for example

```
int level[5][5] = {
    1, 1, 1, 1, 1
    1, 0, 0, 0, 1
    1, 0, 0, 0, 1
    1, 0, 0, 0, 1
    1, 1, 1, 1, 1
}

```

Where 0 could be grass, and 1 could be water:

Using your loop then:

```
for (int y = 0; y < 10; y++)
{
    for (int x = 0; x < 16; x++)
    {
       switch(level[y][x])
       {
       case 0: // Grass
            GAME_ENGINE.DrawBitmap(GRASS, 128 + (x * 32), 0 + (y * 32), 0, 0, 32, 32);
            break;
       case 1: // Water
            GAME_ENGINE.DrawBitmap(WATER, 128 + (x * 32), 0 + (y * 32), 0, 0, 32, 32);
            break;
       }
    }
}

```
> 3 votes

# Answer
I would recommend you to store tile data (in this case the id `0` for top left and `1` to the right and so on) in an array. Use the id to also determine which sprite will you use. For example:

```
int[,] map = new int[4, 5]{{ 0,  0,  0,  0, 0 },
                           { 0, 19, 19, 19, 0 },
                           { 0, 19, 19, 19, 0 },
                           { 0,  0,  0,  0, 0 }};

for (int y = 0; y < 4; y++) {
    for (int x = 0; x < 5; x++) {
        GAME_ENGINE.DrawBitmap(Link_Level, 128 + (x * 32), 0 + (y * 32), (map[y, x] % 12) * 32, (map[y, x] / 12) * 32, 32, 32);
    }
}

```

`12` comes from how many tiles do you have horizontally in your tileset. Code above should draw 5x4 map of stairs surrounding water.

EDIT: Though, i'm not really sure what is the "Link\_Level" name is.
> 6 votes

# Answer
A small addition to the answers provided: if you have very large maps *and* you don't have more than 256 types of tiles per map (including the empty tile), it might save you a lot of ram to use `byte` instead of `int` as the array type.

So instead of

```
int[,] map = new int[6400, 8000]

```

you would use

```
byte[,] map = new byte[6400, 8000]

```

But then if you have such huge maps, you might also look into loading map chunks into memory instead of the whole map. Another note: chunked loading may not work for you if there's stuff constantly going on over the whole map and you need to process all of it all the time. But that's a whole other topic for consideration when designing a tiled map game.

---

### On drawing large maps.

There may come a time when your framerate drops, and it's probably because you have a pretty big map and you're drawing it whole, with large portions of it going off-screen, but still using up your hardware resources. To avoid that, calculate the visibility rectangle and only draw the tiles, indexes of which correspond with the insides of that rectangle.
> 3 votes

# Answer
This depends on how flexible you need the system to be.

What most games do is that they store the map data in an external level data file. This might using a pre-existing level editor and its level file format (Tiled) or a custom editor (could be just a text editor) with a custom format, be that format XML, JSON or a custom one.

For loading the map data you would read trough the file and store the contents of the file in a 2D array that you can then access.

A simpler way for a small project would be to just hardcoded the map 2D array to the source code of the game.

Anyways, once you have your map data in a 2D array, all you need to do is to lookup the tile type at the tile you are currently rendering.

```
for (int y = 0; y < 10; y++)
{
    for (int x = 0; x < 16; x++)
    {
        int xTile = MapData[y][x].x * 32;
        int yTile = MapData[y][x].y * 32;
        GAME_ENGINE.DrawBitmap(Link_Level, 128 + (x * 32), 0 + (y * 32), xTile , yTile , 32, 32);
    }
}

```

Here `MapData` is a 2D array consisting of an object that has x and y members that define the 2-dimensional "index" of the tile in the tileset. Meaning that you would define a tile to be the fifth tile on the second row for an example.

Now, while this approach is quite simple, it might get a little tedious or repetitive. So you might want to define the tile types in a class (or just refer to the tiles as integers and calculate the correct tile position based on them). A simple utility class with fields such as `static global Vec2 StairCase = new Vec2(0, 0);` should make defining the map easier.

To summarize, for a small project like this hardcoding a 2D array that defines that map look should be just fine. If you plan to expand the game later, I would recommend using a external data file.
> 2 votes

---
Tags: c#
---


title: Terrain and Path Architecture

text:
# Question
Title: Terrain and Path Architecture
I am trying to figure out how to **not** break the SOLID principles with a collection of classes I am writing.

Currently, I have two stacks of classes that cater for editing and rendering Terrain and Paths.

`Terrain -> TerrainChunk -> TerrainTile`

`Path -> PathChunk -> PathTile`

The top level `Terrain` object exposes methods to add and remove `Tile`s which are then partitioned into `Chunk` objects forming part of a partitioned scene graph.

The `Chunk` objects themselves contain an array of `Tile`s and if something causes the tile or chunk to become dirty (terrain height is altered or a tile is added/removed) then the chunk “re-draws” itself which is as simple as looping through the `tiles` and calling `Render()`.

The implementation of both the `Terrain` and `Path` stack of classes are largely the same (adding, removing, partitioning into chunks etc) with only the `Render()` method really doing anything different, i.e.: rendering a simple path or a single terrain tile.

I am quite happy with this setup so far which has proven to be extensible enough for my needs to date. This is working as expected and (surprisingly) I haven't butchered my code enough to worry about breaking any of the SOLID principles. Yet.

However, the need has arisen for the `TerrainTile` to know about the `PathTile` and also the `PathTile` needs to know about the `TerrainTile`.

The reason I believe this is true is that I would like to be able to “cut away” the terrain where the path is and also add “tunnels” to the path though the terrain. In order to do this, both terrain and path need to know about each other to determine where the terrain should be drawn or cut away and which paths should have "tunnels" added to them.

Ideally, I would like to implement something similar to this capture from Theme Parkitect although the principle is most likely the same in any other simulation game with terraforming.

I’m not sure how to create the relationships between the two classes however without breaking at least 3 of the SOLID principles.

I could certainly go right at it and brute force this into my current implementation but that’s not very nice and would go against the lean and sane implementation I have strived for thus far.

Can anyone offer up any suggestions as to how I might inform one stack about the changes in another without introducing dependencies or hacking my code to pieces?

Perhaps I am barking up the wrong tree and the approach I have in mind isn't entirely suited for the job, in which case, are there any alternative options I could explore?

Note that I am not asking here about how to create either the terrain or the path tiles themselves but simply, how can I inform each of the appropriate parties of changes to each other without creating cyclical dependencies on each class.

If it matters, I am using Unity and C# but really this problem is both platform and language agnostic.

# Answer
> 2 votes
When experiencing friction like this when trying to add a new use case to an existing design it's a sign that the abstraction is in the wrong place.

In this case I think that you need a new class that knows about both TerrainTile and PathTile, and can do the modifications needed. My reasoning is that only a class with higher access than at the lowest level can make the appropriate choices.

Yes, you can add the actual modification to methods in the lower classes but leave it to the new class to organize those calls.

Personally I would put this new class at the Terrain layer as a place to start. At this layer the new class will know about the tiles and paths and can orchestrate the changes.

---
Tags: architecture, design-patterns
---


title: Countdown timer from 10 to 0 in Unity

text:
# Question
Title: Countdown timer from 10 to 0 in Unity
I'm trying to make a countdown timer in Unity, and I've been able to make the timer count down from 10. However, I can't stop it at 0. I've tried putting it in a while loop but it didn't help, it actually made the timer start at 0.

```
float counter = 10.0f;
public TextMesh countdown;

void Start () {
    countdown = gameObject.GetComponent<TextMesh>();
}

void Update () {
    counter -= Time.deltaTime;
    countdown.text = "Time Left:" + Mathf.Round(timeLeft);

    if (counter <= 0)
    {
        Debug.Log("Hello");
    }
}

```

# Answer
> 1 votes
Because the update is called constantly, you're always running through this;

```
counter -= Time.deltaTime;
countdown.text = "Time Left:" + Mathf.Round(timeLeft);

```

and never really stopping.

In order to stop, you could try something like a flag- something to tell your loop when to stop the countdown. Though because of the simplicity of your program, you could try this, which doesn't use a flag but rather outputs the time left based on your current condition:

```
float counter = 10.0f;

public TextMesh countdown;

    void Start ()
    {
        countdown = gameObject.GetComponent<TextMesh>();
    }

    void Update () {

        if(counter > 0)
        {
            counter -= Time.deltaTime;
            countdown.text = "Time Left:" + Mathf.Round(timeLeft);
        }
        else
        {
            Debug.Log("The counter has stopped.");
        }

}

```

# Answer
> 1 votes
Try with

```
void Update () {
    if (counter > 0) {
        counter -= Time.deltaTime;
        countdown.text = "Time Left:" + Mathf.Round(timeLeft);
    } else {
        Debug.Log("Hello");
    }

```

Note that this will print "Hello" in the console many time per seconds as soon as the counter reaches 0. This is what your code was doing, I don't know if it was on purpose.

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


# Question
Title: Change Shader on This Material Via Code?
How do I change this material to have the Toon/ Lit Outline shader via code at the Start of the scene?

Here is my code that I have as of now, that does not work:

```
 using UnityEngine;
 using System.Collections;

 public class MainMenuManager : MonoBehaviour
 {
     public Material hatMaterial;    //This is my character's hat shader - I set this in the Inspector

     private Shader toonShader;    //This is the Toon Shader with an Outline

     void Start ()
     {
         toonShader = GetComponent<Shader> ();

         toonShader = Shader.Find ("Toon/Lit Outline");

         hatMaterial = GetComponent<Material> ();

         hatMaterial.shader = toonShader;
     }
 }

```

# Answer
`GetComponent` retrieves Components, shader isn't a component (it doesn't inherit from component) so GetComponent won't work.

However, your code still looks fine (that first GetComponent line can be deleted).

It could be due to how you're assigning the `hatMaterial` \- did you drag it from the project view? If so that could be the problem because materials are instanced when the game starts so essentially you'd be modifying another material. If that is the case you'd need to fix it by dragging the specific material being used in the scene OR you could get a instance of a renderer, and use its sharedMaterial property to modify all instances of the material.
> 0 votes

---
Tags: unity, c#, shaders, rendering, materials
---


title: Upgrades in game with leaderboards?

text:
# Question
Title: Upgrades in game with leaderboards?
I am working on an endless mobile game right now and I'm currently in the designing phase. Most (or all) mobile games especially endless ones now have leaderboards and a player's position in the board is determined by their score. I want to implement a store from which people buy upgrades, new cool stuff **that help them gain more score. Will this cause an unfair leaderboards. Should I remove the upgrades and replace them with only customizations in the store like clothes that don't affect the score?**

Thanks in advance.

# Answer
> 0 votes
Generally any game where upgrades improve your progression of the game are classes as pay-to-win. This makes a lot of players avoid it like the plague, while others think it's great as they can get to the top of leaderboards without skill. I guess it depends a lot on what type of game you want to make, and specifically how you implement your upgrades. The most important part is making the game itself as fun and addicting as possible.

My advice is try to avoid a pay-to-win design, but find other ways where upgrades can help. Cosmetics is one big thing, but addition game "features" as paid upgrades are an option as well, statistics, metagame, or stuff that could indirectly help you achieve a highscore. Maybe a practice with checkpoints mode or something similar. Get creative.

# Answer
> 0 votes
I'm currently developing a 3d low poly strategy turn-based multiplayer game, which consists of each player maintaining four actors each. Each actor/unit has their own class(bard,priest,warrior,rogue,etc). I have already decided that upgradable loot would always be a part of the game. The players gain loot by raiding chests in the grid-based dungeon, making the items outside of battle using resources they collect in battle/destroying mineral veins, etc. The thing is though, the gear will not be overly-critical to victory. At most a sword may have +12% Strength on it. Granted that may seem like a lot in the grand scheme of comparatively not having it, but it really means nothing when it comes to the bonuses that actors receive by executing strategic placement and environmental hazard opportunities. What I'm really trying to say here is that your game should be ideally balanced. Two Warriors should have an equal chance of killing each other, regardless of the gear they wear. I have gear, but it is not an integral part of the gameplay.

---
Tags: android, game-design, ios, mobile, leaderboards
---


# Question
Title: Class Structure for upgrades that depend on other upgrades
This game involves making buildings that can be upgraded. Sometimes a building's upgrade isn't available until another building is either created or upgraded to some specific level.

For simplicity's sake, there are two buildings, A and B. Level 1 of both buildings can be built at the start.

Building B can be upgraded freely but building A can't be upgraded to level 2 until building B is at level 4.

As far as class structure, I don't know if there should be a **Building** class and then **BuildingA** and **BuildingB** classes that inherit from it. Or if there should just be a **Building** class and individual building types are instances of that class. This latter solution seems ugly because there is also the layer of individual instances of building a building type.

In either case, I don't know how to design the class structure to control dependencies like the example I gave. Other than hard coding it which isn't very clean or conducive to extending it to more buildings and nuanced dependencies.

# Answer
> Or if there should just be a Building class and individual building types are instances of that class.

This. Do *not* use your language's type system to enforce your game logic's taxonomy. That's the kind of bad object-oriented programming nonsense for which Java programmers get ridiculed. ;)

> This latter solution seems ugly because there is also the layer of individual instances of building a building type.

It's not ugly, at all. You're just confusing language types and instance with game archetypes and instances. They're different things.

The type system in your language is there to enforce interfaces. It's there to help you make sure that you don't accidentally try to draw a sound or animate a database record.

For game objects, think about the kinds of operations you have. For instance, you have an archetype of building called BuildingA. All BuildingA's look the same, have the same stats, or whatever it is your game requires. In other words, there's a bunch of properties that are shared by all BuildingA instances. Note now then that BuildingB has the same *set* of properties, just with different values. That is, both BuildingA and BuildingB have a sprite or mesh that is shared by all their instances but is of course different between the two building architectures.

This should sound familiar. All building archetypes have the same set of properties: that means that you can model building archetypes as a class! So instead of `class BuildingA` you instead have `class BuildingArchetype`. Your individual archetypes of buildings are object instances of that class.

```
auto city_hall = BuildingArchetype("City Hall", "/sprites/hall.png");
auto barracks = BuildingArchetype("Barracks", "/sprites/barracks.png");

```

This provides another benefit - your building archetypes, since they are just data values for a class rather than unique classes - can be defined in data files instead of code. You can allow designers or modders to add all new buildings without having to recompile your game.

You also have properties that are unique to each instance of a building archetype (any building), such as its location, or its construction completeness / hitpoints / whatever. Again, it doesn't matter which archetype a building instance uses - they *all* have these same sets of properties. Hence, a building instance is a second class.

```
class Building {
  BuildingArchetype* _archetype;
  Vector2f _position;

public:
  ... stuff ...
};

```

And hence each instance takes its archetype *as data* instead of using the language's type system, since the operations you can perform on instances of one building archetype are the same as another building archetype.

```
vector<Building> buildings;

buildings.emplace_back(city_hall, {1, 7}));
buildings.emplace_back(city_hall, {-5, 6}));
buildings.emplace_back(barracks, {4, 8}));

```

Note particularly here that all buildings - no matter the archetype - can now live in a single homogenous collection. This is pretty useful. You can just draw all buildings without having to care about what type they are, for example:

```
for (auto& building : buildings)
  draw_sprite(building.archetype().sprite(), building.position());

```

Of course, you might now be wondering about all the code bits that are in fact different for different kinds of buildings. That's the same application of this design, though. For instance, Barracks might produce Soldiers but City Hall produces clerk, and City Halls might also have a Take Loan option.

These don't need to be methods on a building class, though, and you don't want them to be - that would mean that you have to write differnet UI code for every building, and different AI code, and so on. Huge pain. Instead, a building archetype can contain a list of `Action` classes that define what sorts of things a building can do, and individual action sub-classes can define the logic of the action.

This is also composable as now you can reuse your actions on buildings, on units, on scenery, etc. You can make units that can make other units, or buildings that attack just like units do (e.g., guard towers can fire bullets just like soldiers can, without having to duplicate any code).

Note also the "composable" part. This is the crux of what leads into component-oriented design. Instead of hard-coding a complex game object into a single class in your code, allow your game object to be built out of many small components. There are plenty of resources online for you to Google if you're interested in that broader topic.
> 1 votes

---
Tags: architecture
---


title: Hemisphere Projection

text:
# Question
Title: Hemisphere Projection
I came across the following segment of code that is supposed to project an image on a hemisphere:

```
void main(void)
{
    vColor = aColor;
    vec4 pos = uModelViewMatrix * vertex;
    float lenxy = length(pos.xy);
    if(lenxy != 0.0)
    {
       float phi = atan(lenxy, -pos.z);
       pos.xy = normalize(pos.xy);
       // pos.xy is equal to (cos theta, sin theta)
       float r = phi / (PI/2.);
       // radius is less than or equal to 1.
       pos.xy *= r;
       // same theta, different radius
    }
    gl_Position = uProjectionMatrix * pos;
 }

```

The followings are what I need clarifications for:

1. Why would `r` be less than or equal to `1` by dividing `phi` by `PI/2.`?
2. Why are we multiplying `pos.xy` with `r`?
3. And, how does normalizing `pos.xy` give us cos theta and sin theta?

The followings are the accompanying images:

---

Thanks.

# Answer
> 2 votes
The value `r` will be between -1 and 1 because the `atan()` function returns a value between -π/2 and π/2. (Actually, that's probably the `atan2()` function since it takes 2 parameters.)

If you think back to basic trigonometry, sine and cosine functions are defined by the ratios of the radius of the circle to the length of either the horizontal or vertical sides of the right triangle they form. Or to put it more simply:

> sine(theta) = opposite / hypotenuse
>
> cosine(theta) = adjacent / hypotenuse

(The images in the Wikipedia article on sine explain it pretty well.)

In a unit circle, the hypotenuse is always a length of 1, by definition. So by normalizing the vector `pos`, its length becomes 1 and the x and y components of the vector become the lengths of the sides of the right triangle used to define sine and cosine (the opposite and adjacent sides in the above definitions). Like this:

As mentioned, `sine(theta) = opposite / hypotenuse`. Since this is a unit circle, the hypotenuse of that triangle has a length of 1. So `sine(theta) = opposite / 1.0` or just `opposite`. And `opposite` is a line from normalized (`pos.x`, `pos.y`) straight down to the y axis. So the length of `opposite` is (normalized) `pos.y`. Likewise, `cosine(theta) = adjacent / hypotenuse`, which is just `adjacent`, which has a length of (normalized) `pos.x`.

So if `r` is now a value between -1 and 1, and you multiply the normalized `pos` by it, you'll get a vector of length `r` pointing in the direction of `pos`.

---
Tags: opengl, mathematics, projection
---


# Question
Title: Why do I get glitchy graphics when drawing scene with scene2D?
I'm trying to display a simple text for a menu UI using scene2D, but for some reason nothing is being displayed here. The screen displays pure black.

```
public class ScreenMenu implements Screen {

MyGame myGame;
SpriteBatch batch;
Stage stage;
Label labelNewGame, labelContinue, labelCredits;

public ScreenMenu(MyGame myGame) {
    this.myGame = myGame;
}

@Override
public void show() {
    init();
    BitmapFont font = initFont();
    initLabels(font);
    initStage();
}

private void init() {
    batch = new SpriteBatch();
}

private BitmapFont initFont() {
    return new FontLoader().getMichroma();
}

private void initLabels(BitmapFont font) {
    Label.LabelStyle labelStyle = new Label.LabelStyle(font, Color.WHITE);
    labelNewGame = new Label("New Game", labelStyle);
    labelContinue = new Label("Continue", labelStyle);
    labelCredits = new Label("Credits", labelStyle);
}

private void initStage() {
    stage = new Stage(new ScreenViewport());
    Gdx.input.setInputProcessor(stage);
    stage.addActor(labelNewGame);
}

@Override
public void render(float delta) {
    GlHelper.clearScreen();
    stage.act(delta);
    stage.draw();
}

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height, true);
}

@Override
public void pause() {
}

@Override
public void resume() {
}

@Override
public void hide() {
    dispose();
}

@Override
public void dispose() {
    myGame.dispose();
    batch.dispose();
    stage.dispose();
}
}

```

The following class contains the `clearScreen` function. If I don't run it, the entire screen becomes super glitchy, **but** I can see the New Game text.

```
public class GlHelper {

public static void clearScreen() {
    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}

public static void clearScreen(float red, float green, float blue, float alpha) {
    Gdx.gl.glClearColor(red, green, blue, alpha);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
}

```

# Answer
> 1 votes
In the `FontLoader` implementation I set the `FreeTypeFontParameter` color to black. Apparently it overrides the `Color.WHITE` argument from `LabelStyle`.

---
Tags: libgdx, scene2d
---


# Question
Title: Streaming to VAO VertexBuffer using OpenGL Direct State Access for Instancing
How do i stream to a vertex buffer using Direct State Access? I want to update my vertex buffer of matrices every frame so i can use it in my Shader. This is how i specify my buffer. I do this once in my application when i initialize my VAO.

```
    glNamedBufferStorage(StaticModelData::instanceDataID, sizeof(InstanceData)*10, nullptr, 0);
    glMapNamedBufferRange(StaticModelData::instanceDataID, 0, sizeof(InstanceData) * 10, GL_MAP_UNSYNCHRONIZED_BIT);
    glVertexArrayVertexBuffer(StaticModelData::vaoID, 1, StaticModelData::instanceDataID, 0, 0);

    glVertexArrayAttribBinding(StaticModelData::vaoID, 3, 1);
    glVertexArrayAttribFormat(StaticModelData::vaoID, 3, 4, GL_FLOAT, GL_FALSE, 0);

    glVertexArrayAttribBinding(StaticModelData::vaoID, 4, 1);
    glVertexArrayAttribFormat(StaticModelData::vaoID, 4, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4);

    glVertexArrayAttribBinding(StaticModelData::vaoID, 5, 1);
    glVertexArrayAttribFormat(StaticModelData::vaoID, 5, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 8);

    glVertexArrayAttribBinding(StaticModelData::vaoID, 6, 1);
    glVertexArrayAttribFormat(StaticModelData::vaoID, 6, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 12);

    glVertexArrayBindingDivisor(StaticModelData::vaoID, 1, 1);

```

Every frame i do this to render

```
    instanceDatas = updateMatrices();
    updateShader();
    glBindVertexArray(StaticModelData::vaoID);
    glNamedBufferData(StaticModelData::instanceDataID, sizeof(InstanceData)*(instanceDatas.size()), &instanceDatas[0], 0);

    glBindTexture(GL_TEXTURE_2D, 1);//hardcoded

    glDrawElementsInstanced(GL_TRIANGLES, it->second.modelIndexNum, GL_UNSIGNED_INT, (void*)(sizeof(int)*(it->second.indexOffset)), it->second.instances.size());

```

# Answer
> 1 votes
Your question has nothing to do with direct state access. Your problems would still happen if you weren't using DSA functions.

> ```
> glNamedBufferStorage(StaticModelData::instanceDataID, sizeof(InstanceData)*10, nullptr, 0);
>
> ```

That last value tells OpenGL how you intend to access the storage from the CPU. By passing zero, you're saying that you're *not* going to access the storage from the CPU. *At all*. Since you made a promise not to access its storage from the CPU, OpenGL doesn't let you break that promise.

Furthermore, since you created immutable storage for this buffer, you cannot later call `glNamedBufferData` or `glNamedBufferStorage` on the buffer.

The general buffer streaming techniques don't change just because you're using DSA. Personally, since you're using immutable storage buffers anyway, I'd say that you should use persistent&coherent mapped memory with your buffers.

So you should create your buffer with `MAP_WRITE_BIT`, `PERSISTENT_BIT`, and `COHERENT_BIT`. You should map it once (with those bits too) and just keep the pointer around.

Now, you should still double-buffer your instances, so that you're not overwriting data that the GPU is still reading from.

---
Tags: opengl, instancing, vertex-buffer, vertex-arrays, vao
---


# Question
Title: Making my pipes face the correct direction
I am trying to dynamically generate a pipping system. I am using a very specific way to connect the pipes after generating them. The forward has to be pointing at the next pipe and the right has to be pointing at the previous pipe.

Is it possible to do something like

```
transform.right = prevPipe.transform.position - transform.position;
transform.forward = nextPipe.transform.position - transform.position;

```

Take effect at the same time instead of being 2 individual amendments?

# Answer
One would solve these kinds of rotation with Quaternions.

Unity has a quaternion function called SetLookRotation that allows you to specify the forward and up vectors at the same time.

Since in your case you only have forward and right, you can calculate the desired up vector by *crossing* the vectors of the two pipes.

```
Vector3 up = Vector3.Cross(nextPipe.transform.position - transform.position,
   prevPipe.transform.position - transform.position);

Quaternion newRot = new Quaternion();
newRot.SetLookRotation(nextPipe.transform.position - transform.position, up);

transform.rotation = newRot;

```

Hope that helps, Yong Woon :)
> 4 votes

---
Tags: unity, c#, rotation, procedural-generation
---


# Question
Title: When is the CheckResources() function called?
This question is asked in the context of image effect shader implementations in Unity.

Looking through the scripts for image effects in the standard assets package, I notice that initialization is generally done in the CheckResource() function.

The following is a snippet of code from the `BloomAndFlares` image effect.

```
public override bool CheckResources()
{
    CheckSupport(false);

    screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend);
    lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial);
    vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial);
    separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial);
    addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial);
    hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial);
    brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);

    if (!isSupported)
        ReportAutoDisable();
    return isSupported;
}

```

I am probably wrong in assuming that this is essentially the `Start()` or `Awake()` functions for `PoseEffectsBase`, but I decided to try implementing something simillar.

```
public override bool CheckResources()
{
    saturationPassMat = CheckShaderAndCreateMaterial(saturationPassFilter, saturationPassMat);

    if (!isSupported)
        ReportAutoDisable();
    return isSupported;
}

```

Unlike the standard asset scripts, `CheckResources()` does not seem to be called consistently for me. Unity console throws `UnassignedReferenceExceptions` every frame, for the object `saturationPassMat`.

When is the `CheckResources()` function called? Should it be used for initialization just like `Start()`?

# Answer
I looked through the PostEffectsBase class, and saw this.

```
protected void Start()
{
    CheckResources();
}

```

So... Yeah.

~~Kinda feel like an idiot now~~
> 0 votes

---
Tags: unity, shaders, image-effects
---


# Question
Title: AudioSource not working. Empty Exception
I'm trying to load and play an wav file that exists in my `Application.dataPath` but when the game gets to the line `_GoAudioSource.PlayOneShot(audioLoader.audioClip);` It justs throws a empty exception and no sound is played.

I've already checked if the path is correct and it is. I've also tried uploading this wav file to an FTP and loading it via `HTTP` instead of `File:///` but nothing changes.

This is my full code:

```
     private IEnumerator WriteResponseAudio(ResponseModel res)
     {
         File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME_RESPONSE), Convert.FromBase64String(res.intent.audio.content));
         string path = "file:///" + Application.dataPath + "/" + FILENAME_RESPONSE;
         WWW audioLoader = new WWW(path);
         yield return audioLoader;
         try
         {
             _GoAudioSource.PlayOneShot(audioLoader.audioClip);
         } catch (Exception ex)
         {
             Debug.LogError("Erro: " + ex.Message);
         }
     }

```

This is the version with HTTP request:

```
     private IEnumerator WriteResponseAudio(ResponseModel res)
     {
         File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME_RESPONSE), Convert.FromBase64String(res.intent.audio.content));
         string path = "http://www.raphaelrosa.com/response.wav";
         WWW audioLoader = new WWW(path);
         yield return audioLoader;
         try
         {
             _GoAudioSource.PlayOneShot(audioLoader.audioClip);
         } catch (Exception ex)
         {
             Debug.LogError("Erro: " + ex.Message);
         }
     }

```

This is the console:

# Answer
> 1 votes
I've managed to solve my problem converting my byte array directly in a AudioClip using the code posted by Jeff Kesselman in this topic http://answers.unity3d.com/questions/737002/wav-byte-to-audioclip.html

---
Tags: unity, c#, audio, file, http
---


# Question
Title: Unity fade all UI elements which belong to one Canvas
Like the question describes I want to fade out/in all UI-Elements belonging to a parent canvas.

So things I got are :

* A World-Canvas which contains multiple UI-Items
* A script which can fade one color depending how close my cursor comes to that item

Things I want :

* A script which can fade my whole canvas without attaching each single Element with a color property to it

Thoughts :

* This would most likely work with a script which searches all Text children and Image children of the canvas, but I think that would be rather poorly performing code

I'm totally fine if there is no better solution as the mentioned one, but I would be annoyed if I implement it that way and there is a simple trick I don't know about :)

# Answer
I think you can simply use a Canvas Group component on the top level canvas. It has an Alpha property that you can easily modify with a script.

https://docs.unity3d.com/Manual/class-CanvasGroup.html
> 2 votes

---
Tags: unity, gui, ui-design
---


# Question
Title: Detecting if ad is open, when user pressed "back" button
I am trying to reward a user a point whenever they watch/look at an ad. I give the user the reward whenever they watch the ad. However, the user earns a point even if they go to the ad and click back:

```
 mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                giveUserPoint();
                }
            }
        });

```

Is there a way I can see if the user clicked the back button **while** the ad was opened?

Maybe something like:

```
userBackClickListener(){
    if(adIsOpen){
     dontGiveUserPoint();
    }
}

```

How can I see if the ad was open while an action happened?

# Answer
> 1 votes
In onAdClosed() you need to check if the user has watched the ad.

```
public void onAdClosed() {
        if(adFinishedPlaying()) {
            giveUserPoint();
        }
    }
}

```

You'll need to write the `adFinishedPlaying` method, which will depend on how you're showing the ad to the user. If it's a video ad you could check the position against the duration or for picture ads you could use a timer.

```
// Example
private boolean adFinishedPlaying() {
    boolean finished;
    // If the ad is a video ad, check if it is finished playing.
    if ( ad.isVideo() ) {
        finished = ad.position >= ad.duration;
    }
    // Else, check if the user has looked at it for long enough.
    else {
        finished = (time.now() - ad.startTime) >= ad.duration;
    }
    return finished;
}

```

The above is only a rough example; The implementation will depend heavily on what tools your using to display your ads.

# Answer
> -1 votes
Set a timer of 3 seconds or so? Maybe it has something with time. Count how much time he is not in the app

---
Tags: java, android
---


# Question
Title: Why do Unity layer masks need to use bit shifting?
I've finally figured out why my layer masks for my ground collision code weren't working. I was using `NameToLayer()` to get the layer I needed, but layer masks use bit shifting to actually set the layer mask value. This is extremely unusual and I don't see any reason why this isn't handled in the code behind. Why do we have to use code like this:

```
mask = 1 << LayerMask.NameToLayer("Default");

```

when something like this:

```
mask = LayerMask.NameToLayer("Default");

```

makes more intuitive sense and works similar to the rest of the Unity API?

# Answer
This is extremely performant. That's all there is to it - comparing strings as the obvious example is slower by a factor of 10. And physics calculations have to be very optimized, so it's good that someone who knew what's going on wrote it this way.

So the obvious follow-up question is - why isn't this wrapped in a helper method to handle the conversion and bit-shifting. I think that no one actually got to it - I've rolled up my own nifty helper utility and that is the common practice.
> 4 votes

# Answer
Using bit shifting allows you to take into account multiple layers in one physics operation:

```
 Physics.Raycast(ray, out hitInfo, Mathf.Infinity, layerMask )

```

Without bit shifting, you would be allowed to raycast in one layer and only one. While with bit shifting, you can raycast in multiple specific layers:

```
layerMask = (1 << LayerMask.NameToLayer("MyLayer1")) | (1 << LayerMask.NameToLayer("MyLayer2")) ;

```

You can also raycast in every layers *except* specific ones :

```
layerMask = (1 << LayerMask.NameToLayer("MyLayer1")) | (1 << LayerMask.NameToLayer("MyLayer2")) ;
layerMask = ~layerMask;

```

If you look at the "Layer manager" in Unity, layers can be seen as the indices of a simple one-dimension array.

---

EDIT : I've never seen it before, but the `LayerMask` class has a utility function to get the "computed" layer mask given the layers names :

```
Debug.Log( LayerMask.GetMask("UserLayerA", "UserLayerB") ) ;

```

Suppose `UserLayerA` and `UserLayerB` are the tenth and eleventh layers. These will have a User Layer values of 10 and 11. To obtain their layer mask value their names can be passed into GetMask. The argument can either be a list of their names or an array of strings storing their names. In this case the return value will be 2^10 + 2^11 = 3072.

Link to documentation : https://docs.unity3d.com/ScriptReference/LayerMask.GetMask.html
> 20 votes

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