# Question
Title: How to design a turn-based game which is easy for humans but difficult for AI?
Until recently, Go used to be of the last bastions of turn-based no information-hiding games where world-class human players could not be defeated by computers. But now this bastion has fallen, as the program AlphaGo managed to beat one of the world top players.

However, Go was never designed as a game which is hard for AI. It was developed thousands of years ago. Being hard for computers was an unintentional side-effect of the game design, not a stated design goal.

What game mechanics make a turn-based strategy game without information hiding hard for AI, yet still playable for humans?

---

In case someone wonders "Why is this question also relevant for video game developers"?

1. because it shows us how to design competitive multiplayer games where players can not cheat by using an AI assistant.
2. For single player games it shows us what to avoid when we plan to add an AI opponent later.

# Answer
Go is difficult for computers because there are many, *many* possible moves for the player in each board state, too many for the computer to brute-force and calculate all possible outcomes (unlike, for example, tic-tac-toe).

Traditionally, chess playing computer programs would calculate all possible moves a few turns into the future and pick one of the moves that would lead to the "best" state, maximising the possible advantage of the computer player and minimising the possible advantage of the other player.

However, there's more possible moves in a complete game of chess than there are atoms in the universe, and this applies even moreso for Go, where there are many more possible board states. There are simply *too many* possible moves for a modern computer to calculate in any reasonable time. Instead, different approaches to AI need to be used to play "better" at games like Go, such as deepmind being able to "learn" how to get better at a task in a similar way to how real intelligence works (learning from trial and error).

So if you want to make an "open information" game hard for a computer? Have a very large amount of possible moves to make, nearly all of which *could* be a good move for the player.
> 6 votes

# Answer
When designing arbitrary turn-based game you have few options to make harder for AI, focusing on different aspects of AI:

1. Abstraction (e.g. task "draw something beautiful")
2. Feature extraction (e.g. from non gaming: captcha)
3. Decision making: unfeasible bruteforce solutions (huge state space, e.g.the go)

Your best bet is on abstraction - you should aim to create too complicated *abstraction* to be approximated by a mathematical model.
You can also further annoy "cracking" the game with AI by giving it inputs that are harder to extract features from: an image or speech. Even if fed with input extracted with 99% accuracy, there is a chance for AI to receive wrong inputs, if it receives wrong inputs it is probably(depending on AI type) much more likely do make a wrong decision.
Or by using combinatorial explosion (go used this) in rule set. For example, if a turn was to play `1` card from `10` cards hand, there are `10 possibilities` how to play the turn. If you were to choose `5` cards for that hand there are "n choose k" options, giving total `252 possibilities` on that turn alone(!). Note: there are many other ways how to introduce something similar in a rule set.
None of above alone will make it *impossible* (the go is good example of that) but with careful design you could make it at least *infeasible* for a few years/decades.

A very, very simple game for illustration purposes using said suggestions:

> Players takes turns, each one saying a single sentence. The goal is to tell a short story.

I think we can agree the quality of the story playing this game with average human players will be much better than any AI just as well as the fun for human players playing the game(this is ultimately the goal of games isn't it?). This game is probably even older game than go.
*just a note: noticed how this game above incorporates all of the suggestions?* The feature extraction from speech alone is not trivial task, paired with abstract goal of the game with insanely huge state space (natural language is *infinite*) makes it nearly impossible for AI to crack(=play better).

---

**Edit:** (for downvoters) please, look up definition of game(moreover the game above is just for illustration purposes): a physical or mental activity or contest that has rules and that people do for pleasure or

> an activity that one engages in for amusement

Lets not limit games to something like Call of Duty.

---

**Edit 2:** In fact, it is *really* good question:

> "But how would you rate the story generated by a storytelling game?"

This illustrates the arguments why games with at least some abstract rules are hard - this is exactly what AI would try to ask: how do I measure it, how do I describe it with an equation? AI is not capable to think out of the box or make complex abstractions (such as having fun). The correct answer is:

> You dont. And that is exactly what makes it hard for AI.
> 4 votes

# Answer
Short answer: Increase the number of variables.

Why? Chess was "easy" for a computer to beat because there are only a certain number of pieces and possible moves. Go was "harder" because there were more possible moves. A game that is even harder for a computer will have even more possible moves.

Example: Strategy games. I have yet to play an RTS\* where the computer can win against an experienced human without cheating. Why? The number of variables. Resources, the effects of resources over time (do you use them to get more resources, do research, or produce units?), how scouting and intelligence is handled, and how the plethora of available units are managed. You could probably tell a computer how to "kite" long range units, but telling it when to kite, for how long, when to make those units, etc. etc. with the combination of every other unit and its possible uses would be nearly impossible.

Asking a computer to simulate every possible move in chess and the response that is guaranteed to win against that move is trivial with today's computers. Asking a computer to simulate every possible click in an RTS with resources, research trees, and complex unit types is likely impossible. Yet even inexperienced humans can master the basic elements of these games with relative ease compared to the computer programming necessary.

\*I know I am using RTSs as an example but any RTS can theoretically be made into a very similar turn-based strategy game.

---

Another thought: you could also pick a task that humans already find easy but that is actually very complex, like folding laundry, and make that into a turn-based game. Players could take turns folding a piece of clothing -- every turn is one piece of clothing -- and the player who has taken the least amount of time to complete 5 turns wins.

We find this simple because we have a conception of what words like "up" and "inside-out" mean -- take a shirt, make sure it's "right side in," lay it "flat on the table" so the "collar" is "away from you," take the "sleeve..." etc. etc. As a human, you know what all the phrases/words in quotes mean; essentially, you have simplified a basically infinite number of variables into instructions that take only a few words. Explaining that to a computer is more or less impossible. And even if you explain it for one shirt, will the computer know every shirt? Long sleeve? Short sleeve? Button up? What if the collar is popped? etc.
> 2 votes

# Answer
The reason that Go was so hard for computers was because it took a lot of intuition to play it well. Computers do not possess intuition but they possess an immense amount of processing power and memory which can be used to find patterns, really what a computer does when analysing data.

Your question is hard to answer because if a computer can find patterns it can develop strategies based on that data. Computers can only make perfect choices given the data at the time (which we will some times look at as mistakes but really it's because the data was missing, incomplete or misleading).

So I think the answer you are looking for is: Make games that require a lot of intuition, like Go.
> -1 votes

---
Tags: ai, game-mechanics, turn-based
---


title: Procedural generation of jagged peaks

text:
# Question
Title: Procedural generation of jagged peaks
I would like to generate random cave type backgrounds similar to the one shown below.

I doubt anything I generate will look as good as the image, but something with that feel of sharp, jagged peak should be possible.

I don't have any experience in procedural generation and as such have no idea where to start....

Note: I am using libGdx on Android

# Answer
One easy way to do it would be to use the midpoint displacement algorithm:

1. Start with a line representing the ceiling.
2. At the midpoint, displace it some random amount leaving the end points where they are.
3. Now take the resulting 2 line segments and do it to each of those (divide them in half and displace their centers by a random amount).
4. Continue doing this until you have a shape you like. Do the same for the floor.
5. Repeat the process for the floor, but displace upwards instead of downwards.

Also, see this answer.
> 2 votes

# Answer
Midpoint displacement will work provided that you feed in the right sort of values.

To get sharper peaks & valleys, you need to favor high & low numbers while suppressing mid-range numbers. For instance, assume some function `rnd()` returns a uniform random number in the range \[0-1\]. Then `(sin(rnd()*PI)+1)/2.0` would skew that result to favor values closer to 0 or 1. Other mathematical transformations that would work, this one happens to be easy to prototype in a spreadsheet. If you need to do this in real-time, you might want something faster than `sin()`.

Also, I would only apply the above to the first set of values used by the midpoint displacement. On the "interior" of the algorithm, I'd use uniform noise. That being said, it's easy enough to try it both ways & see which suits you better.

One thing this solution won't do is pair up stalactites with stalagmites other than random chance. If that's a requirement, you should update the question accordingly.
> 2 votes

---
Tags: procedural-generation
---


# Question
Title: How do I structure code with multiple VBOs?
As per my previous question, it seems it would be desirable to use more than a single VBO in my OpenGL program. But I've hit a wall when trying to do this. Currently my main function looks something like this in pseudocode

```
setup "main" VBO and VAO
load shaders
setup shader attributes

while true
  update geometry into "main" VBO
  glBufferData(... "main" VBO)
  glClear(GL_COLOR_BUFFER_BIT)
  glDrawArrays(...)

```

Now what I thought I could do is effectively move the *setup "main" VBO* inside the game loop itself

```
setup VAO
load shaders
setup shader attributes

while true
  setup "main" VBO
  update geometry into "main" VBO
  glBufferData(... "main" VBO)
  glClear(GL_COLOR_BUFFER_BIT)
  glDrawArrays(...)

```

which would then allow me to split the loop into multiple chunks, each creating its own VBO and drawing. But this doens't seem to work, and I get a blank white screen. I can only guess this is because the shaders are not only bound to the VAO, but also to the currently active VBO? I've tried `glUseProgram()` after the "main" VBO setup, but it doesn't seem to help.

I've found it quite difficult to find information regarding which phase exactly depends on which, and in what order things need to be executed.

# Answer
> 1 votes
glBufferData reallocates the VBO in VRAM, use glBufferSubData when updating data.

Generally each mesh has its own VBO(s); and own VAO if not batched. There are optimizations where you use a single VBO for all meshes with the same attribs, etc, but don't worry about that.

The relation of these things is

1. VBO created and loaded with data
2. VAO is bound
3. Vertex attribs are set, vertexAttribPointer points into the current ARRAY\_BUFFER, attribs are part of the state of the VAO
4. Program gets vertex attribs from the current VAO (which may be the default VAO 0 if you never bound one)

---
Tags: opengl
---


# Question
Title: Should I use the pathfinding client side or server side?
I'm developping a game where the user can walk in a room (with the others players). There are some obstacles that blocks the user. I'm using a Javascript pathfinding library to find where the user can walk. But the question is:
Should I use the pathfinding library Client side or server side? Why?

# Answer
Client-side greatly reduces your costs. The server is doing less calculation, so you need less server power per player. Assuming you want to display the path to the client, doing the calculation server side requires you to send the whole path down in one big chunk, while doing it on the client only requires sending up the actual movements (which is about what you'd require in bandwidth anyway).

There are several downsides to doing it on the client. Their severity depends on your game. If the player is controlling squads of AI agents in PvP games (e.g., an RTS) then client-side pathing would allow clients to gain unfair advantages by modding their client. There may also be lag issues resulting in less-satisfying paths/movement in environments rich with dynamic obstacles.

You've told us nothing about your game that helps to inform the decision, but as an educated guess, I'd suggest doing pathing on the client. Just remember to always make movements validated on the server so the player can't send up illegal moves and warp though walls or such.
> 4 votes

---
Tags: javascript, path-finding, server, client
---


# Question
Title: Collisions being detected before objects are intersecting
I'm making space invaders (in OpenGL/SDL) and I'm currently having issues with getting the collisions (box collisions) between the bullets and the enemies to be properly detected. In my `update()` function, I have a nested for loop which iterates through all of entities (for each bullet) detecting if each bullet has collided with it. To do this, I have a function `checkCollision()` in which I'm calculating the dimensions of each enemy and bullet that gets passed in and then checking if the "boxes" for each entity are intersecting:

**Function for checking collisions**

```
bool checkCollision(Enemy* anEnemy, Bullet* aBullet) {
    float enemyTop = anEnemy->y + (anEnemy->height / 2.0f);
    float enemyBottom = anEnemy->y - (anEnemy->height / 2.0f);
    float enemyRight = anEnemy->x + (anEnemy->width / 2.0f);
    float enemyLeft = anEnemy->x - (anEnemy->width / 2.0f);

    float bulletTop = aBullet->y + (aBullet->height / 2.0f);
    float bulletBottom = aBullet->y - (aBullet->height / 2.0f);
    float bulletLeft = aBullet->x - (aBullet->width / 2.0f);
    float bulletRight = aBullet->x + (aBullet->width / 2.0f);

    //This is supposed to check that if the objects are not intersecting, return false
    if (
        (bulletBottom > enemyTop) ||
        (bulletTop < enemyBottom) ||
        (bulletLeft > enemyRight) ||
        (bulletRight < enemyLeft)
        ) {
        return false;
    }
    else {
        return true;
    }
}

```

**Code to check collisions for each enemy in update function**

```
//Check if each of the bullets has hit any of the enemies
    for (int i = 0; i < bullets.size(); i++) {
        for (int j = 0; j < entities.size(); j++) {
            if (entities[j] != nullptr && bullets[i] != nullptr) {
                if (checkCollision(entities[j], bullets[i])) {
                    std::cout << "bullets y position: " << bullets[i]->y << std::endl;
                    std::cout << " hit enemy y position: " << entities[j]->y << std::endl;
                    std::cout << "bullets x position: " << bullets[i]->x << std::endl;
                    std::cout << " hit enemy x position: " << entities[j]->x << std::endl;
                    delete entities[j];
                    entities[j] = nullptr;
                    delete bullets[i];
                    bullets[i] = nullptr;
                }
            }
        }
    }

```

For some reason, when the bullet it shot from the spaceship (player), the collisions are detected before the bullet even reaches the enemy on the screen and I get the following console output:

```
bullet y position: 0.610021
enemy y position: 1.85
bullet x position: 0
enemy x position: -1.0335

```

**How should I be structuring the collision detection differently so that the objects are actually intersecting before the collision is detected?**

# Edit:

I was able to modify the code to make the collisions happen closer to the enemies but they still aren't very precise. I had been scaling the entities by the widths and heights so I decided to reduce the scaling factor. The problem now is that the bullets are taking out two enemies before they are destroyed.

Full Code for reference

**The image below shows the instance in which the collision is being detected between the bullet and the enemy**

# Answer
> 1 votes
When colliding two boxes, you must do more than check if one has edges inside the other.

```
_________
|A ___  |
|  |B|  |
|  |_|  |
|_______|

```

If checking B has edge inside A, it will be correct, but if checking A inside B, it will be wrong.

I approach this by checking if A has any corners inside B, AND if B has any corners inside A. Corners instead of edges as that may then be applied to rotated boxes as well.

---

You'd really benefit from making an AxisAlignedBoundingBox class. This would allow general flexibility with the use of an object's bounds, allowing it to be used for more than collision.

---

```
if (
    (bulletBottom > enemyTop) ||
    (bulletTop < enemyBottom) ||
    (bulletLeft > enemyRight) ||
    (bulletRight < enemyLeft)
    ) {
    return false;
}
else {
    return true;
}

```

Bad code!
instead

```
 return !(
    (bulletBottom > enemyTop) ||
    (bulletTop < enemyBottom) ||
    (bulletLeft > enemyRight) ||
    (bulletRight < enemyLeft) );

```

---
Tags: opengl, c++, collision-detection, physics
---


title: Reset Opengl multisampling

text:
# Question
Title: Reset Opengl multisampling
I start using multisampling by doing

```
        ContextAttribs attribs = new ContextAttribs(3, 3).withForwardCompatible(true).withProfileCore(true);
        Display.create(new PixelFormat().withSamples(8), attribs);
        GL11.glEnable(GL13.GL_MULTISAMPLE);

```

How would I reset how many samples it uses?

# Answer
> 1 votes
Either recreate the display
or
Keep your default framebuffer with no multisamples, make a framebuffer with multisample that is blitted to the default fbo, which may be recreated.

---
Tags: opengl, antialiasing
---


# Question
Title: How to replicate Unity's Rigidbody.AddForceAtPosition in C++?
I am trying to replicate the function Rigidbody.AddForceAtPosition of Unity in C++, it means, to apply force to a body offset from its center.

How could I achieve that in C++?

# Answer
This code is from my own physics engine (C#). It's 2D, but it's just the same in 3D. The forces are simply accumulated, and the rotation (torque) produced is the cross product of the vector from the center of the object to the point and the force applied.

```
public void ApplyForceAtPoint(Vec2 f, Vec2 point)
{
    force += f;
    torque += Vec2.Cross(point - position, f);
}

```
> 1 votes

---
Tags: unity, c++, physics, rigidbody
---


# Question
Title: How to get obstacles to spawn randomly in x position in an infinite runner? 2D
I'm trying to make two obstacles that are different sized to come in a random order in one straight line where the player is going. Doesn't have to be with object pooling.

It seems that the EnemyGenerator class is useless and all can be done in platformGenerator.

> using UnityEngine; using System.Collections;

```
public class EnemyGenerator : MonoBehaviour {

public ObjectPooler enemyPool;

public float distanceBetweenEnemies;

public void SpawnEnemies (Vector3 startPosition)
{
    GameObject karhu = enemyPool = enemyPool.GetPooledObject ();
    karhu.transform.position = startPosition;
    karhu.SetActive (true);

    //GameObject punakuono = enemyPool = enemyPool.GetPooledObject ();
    //punakuono.transform.position = new Vector3(startPosition.x - distanceBetweenEnemies, startPosition.y, startPosition.z);
    //punakuono.SetActive (true);
}

}

```

This also returns the error: "Assets/Scripts/EnemyGenerator.cs(12,36): error CS0029: Cannot implicitly convert type `UnityEngine.GameObject' to`ObjectPooler'".

Edit: I had an extra enemyPool and the class is useless.

My game does spawning with a generation point that is stuck in the camera and when the player runs the generation point goes forward and spawns flatground ahead of him.

Ask me for more example code if you need.

Edit 1: Here is the PlatformGenerator that also spawns other objects.

> using UnityEngine; using System.Collections;

```
public class PlatformGenerator : MonoBehaviour {

public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;

private float platformWidth;

public ObjectPooler theObjectPool;

private EnemyGenerator theEnemySpawner;
public float randomEnemyThreshold;
public ObjectPooler enemyPool;

// Käytä alkuarvon alustamiseen
void Start () {
    platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;

    theEnemySpawner = FindObjectOfType<EnemySpawner> ();
}

// Päivitys tulee joka ruutu
void Update () {

    if (transform.position.x < generationPoint.position.x)
    {
        transform.position = new Vector3 (transform.position.x + platformWidth + distanceBetween, transform.position.y, transform.position.z);

        //Instantiate (thePlatform, transform.position, transform.rotation);
        GameObject newPlatform = theObjectPool.GetPooledObject();

        newPlatform.transform.position = transform.position;
        newPlatform.transform.rotation = transform.rotation;
        newPlatform.SetActive (true);

        if (Random.Range (0f, 100f) < randomEnemyThreshold)
        {
            GameObject newEnemy = enemyPool.GetPooledObject();

            Vector3 enemyPosition = new Vector3 (0f, 0.5f, 0f);

            newEnemy.transform.position = transform.position + enemyPosition;
            newEnemy.transform.rotation = transform.rotation;
            newEnemy.SetActive(true);
        }
    }

}

}

```

Edit 3: I found the problem.

# Answer
> `GameObject karhu = enemyPool = enemyPool.GetPooledObject ();`

Why are you assigning `enemyPool` to `karhu`? `enemyPool` is of type `ObjectPooler` and `karhu` is of type `GameObject`, which is causing the problem.
> 1 votes

# Answer
Delete every reference to EnemyGenerator class. It should look like this.

> using UnityEngine; using System.Collections;

```
public class PlatformGenerator : MonoBehaviour {

public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;

private float platformWidth;

public ObjectPooler theObjectPool;

public float randomEnemyThreshold;
public ObjectPooler enemyPool;

// Käytä alkuarvon alustamiseen
void Start () {
    platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;

}

// Päivitys tulee joka ruutu
void Update () {

    if (transform.position.x < generationPoint.position.x)
    {
        transform.position = new Vector3 (transform.position.x + platformWidth + distanceBetween, transform.position.y, transform.position.z);

        //Instantiate (thePlatform, transform.position, transform.rotation);
        GameObject newPlatform = theObjectPool.GetPooledObject();

        newPlatform.transform.position = transform.position;
        newPlatform.transform.rotation = transform.rotation;
        newPlatform.SetActive (true);

        if (Random.Range (0f, 100f) < randomEnemyThreshold)
        {
            GameObject newEnemy = enemyPool.GetPooledObject();

            Vector3 enemyPosition = new Vector3 (0f, 0.5f, 0f);

            newEnemy.transform.position = transform.position + enemyPosition;
            newEnemy.transform.rotation = transform.rotation;
            newEnemy.SetActive(true);
        }
    }

}

}

```
> 0 votes

---
Tags: c#, unity, gameobject, object-pools
---


# Question
Title: Why do my obstacles float above the ground? Unity2D
I'm making an infinite runner game and I'm trying to spawn obstacles, but all of them float far above the ground instead of being at the ground level.

This is the code on summoning the bears.

> PlatformGenerator Class

```
    if (Random.Range (0f, 100f) < randomEnemyThreshold)
        {
            GameObject newEnemy = enemyPool.GetPooledObject();

            Vector3 enemyPosition = new Vector3 (0f, 0f, 0f);

            newEnemy.transform.position = transform.position + enemyPosition;
            newEnemy.transform.rotation = transform.rotation;
            newEnemy.SetActive(true);
        }

```

Ask me more about the game if you need more information.

Edit:

Here is the whole class.

> The PlatformGenerator Class

```
using UnityEngine;
using System.Collections;

public class PlatformGenerator : MonoBehaviour {

public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;

private float platformWidth;

public ObjectPooler theObjectPool;

public float randomEnemyThreshold;
public ObjectPooler enemyPool;

// Käytä alkuarvon alustamiseen
void Start () {
    platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;

}

// Päivitys tulee joka ruutu
void Update () {

    if (transform.position.x < generationPoint.position.x)
    {
        transform.position = new Vector3 (transform.position.x + platformWidth + distanceBetween, transform.position.y, transform.position.z);

        //Instantiate (thePlatform, transform.position, transform.rotation);
        GameObject newPlatform = theObjectPool.GetPooledObject();

        newPlatform.transform.position = transform.position;
        newPlatform.transform.rotation = transform.rotation;
        newPlatform.SetActive (true);

        if (Random.Range (0f, 100f) < randomEnemyThreshold)
        {
            GameObject newEnemy = enemyPool.GetPooledObject();

            Vector3 enemyPosition = new Vector3 (0f, 0.5f, 0f);

            newEnemy.transform.position = transform.position + enemyPosition;
            newEnemy.transform.rotation = transform.rotation;
            newEnemy.SetActive(true);
        }
    }

}

}

```

# Answer
Try checking the collider component on the game objects you are spawning. Add a rigid body component on them too as they are using gravity !!
> 1 votes

---
Tags: c#, 2d, unity, object-pools
---


# Question
Title: How to change game background image when press button in unity?
In my game provide two background user can wish to change game background when user press button so how I can do this.

I use a sprite for background.

# Answer
There are two ways you could do this.

1. Have two SpriteRenderers on screen, each displaying a different sprite. One enabled, one disabled. Swap their active states when you want to display the other image.
2. Have one SpriteRenderer on the screen, and swap the active Sprite that it is displaying. With this option, you would have to set up your Sprites as Resources.
> 1 votes

---
Tags: unity
---


# Question
Title: What is the purpose of the second parameter to Array.removeValue in libgdx?
I have been wondering what the second parameter of the method in Array removeValue does.

```
removeValue(T value, boolean identity)

```

What does indentify mean and should I pass true or false?

# Answer
From the documentation, which you should generally try to consult first:

> ```
> identity - If true, == comparison will be used. If false, .equals() comparison will be used.
>
> ```

If you pass `true`, `removeValue` will compare every array element to `value` with `==`. Otherwise it will call `element.equals(value)` to do the comparison.
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Deferred Rendering and skeletal animation
I am working on a deferred rendering engine and just finished skeletal animation in the vertex shader, but soon realized that this was only updating the rendered geometry and not the shadows, as the animation was only done in the VS of the deferred rendering step, and not in the VS of each light.

I assume this means I should just calculate the animation on the cpu, as otherwise it will be done #oflights + 1 times in the gpu, which seems like a huge waste of cycles.

Is this how it is typically done?

Edit: As a note, I am currently implementing this in OpenGL

# Answer
If you are working with DirectX 10 or higher, you can do stream-output. The Idea is, that you keep a vertex buffer of the unskinned mesh, run it through a stream-output shader which is a vertex shader + geometry shader combo. In that shader you can do your skinning, and stream it out to an other Buffer, which you can bind like a regular vertex buffer later. See MSDN

You can also stream out in OpenGL, though I am not familiar with that yet. From the documentation it seems that you can use that feature since the 4.0 version. OpenGL Output streams
> 2 votes

# Answer
Just write a single render function per specific type of object, this way you can call the object's render function regardless of where you are rendering to, such as the screen or a shadowmap.

As others have said, you should pass all your matrices to the shader and do the math there. Since you have 2 different rendering operations (standard model rendering, and shadow map rendering), you will need to make sure you use the right bone transformations in both shaders.

This tutorial may be of help: http://ogldev.atspace.co.uk/www/tutorial38/tutorial38.html
> 0 votes

---
Tags: skeletal-animation, deferred-rendering
---


# Question
Title: Unity5 - Create navmesh for a random generated environment
I am following this tutorial to create a game with random generated mazes:

```
http://catlikecoding.com/unity/tutorials/maze/

```

I want to add some monsters to roam around the newly created maze. How can I create navmesh for this kind of random generated environment?

# Answer
You could achieve something similar to what you are describing using NavMesh Obstacles. The idea here is that you would create a flat surface that has a baked Navmesh on it, then place walls that have the NavMesh Obstacle Component attached.

This will cut out the NavMesh around each wall, given you the desired effect. Although I've used obstacles before, it's only ever been on small NavMeshes so I can't comment on how efficient this solution would be for you.

A tutorial on NavMesh Obstacles can be found here
> 1 votes

---
Tags: unityscript, unity, navmesh
---


# Question
Title: Unity Engine: How to change mointor/desktop resolution in 4.5.3 and higher
As of unity 4.5.3, Screen.SetResolution and the Unity Resolution Display Dialog, by default, no longer change the monitor/desktop resolution. Instead, it only changes the render target resolution for the game. This means that if you run a 1024x768 resolution on a widescreen monitor, your cursor can travel into the letterboxed area, outside of the window bounds, even when running in full screen mode. This is not the desired behaviour for our game.

This was described in the Unity 4.5.3 release notes:

**"Windows Player: The default full-screen mode no longer changes the desktop resolution, so things like IME text input work."**

I would like to *actually* change the desktop resolution. The change log suggests there is some non-default full-screen mode that will actually change the desktop resolution... How do I do this?

# Answer
> 1 votes
It's under

PlayerSettings\> Settings for Pc, Mac and Linux standalone\> StandAlone Player Options\> D3D9 Fullscreenmode and D3D11 Fullscreenmode

But I find it kinda buggy;

---
Tags: unity, resolution
---


# Question
Title: Why do I get link errors when extending UBatchLineComponent in UE?
I got some link errors when extending `UBatchLineComponent` this way:

```
UCLASS(MinimalAPI)
class UPBLineBatchComponent : public ULineBatchComponent
{
    GENERATED_UCLASS_BODY()
public:
    virtual void UpdateBounds();
    virtual FBoxSphereBounds CalcBounds(const FTransform& LocalToWorld) const override;
    void SetTransform(const FTransform &Transform);
    FBoxSphereBounds LocalBounds;
};

```

It gave me those errors:

```
Error   5   error LNK2001: unresolved external symbol "public: virtual class FPrimitiveSceneProxy * __cdecl ULineBatchComponent::CreateSceneProxy(void)" (?CreateSceneProxy@ULineBatchComponent@@UEAAPEAVFPrimitiveSceneProxy@@XZ)  C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\Module.ProBuilderPlugin.2_of_2.cpp.obj    ProBuilder
Error   6   error LNK2001: unresolved external symbol "public: virtual class FPrimitiveSceneProxy * __cdecl ULineBatchComponent::CreateSceneProxy(void)" (?CreateSceneProxy@ULineBatchComponent@@UEAAPEAVFPrimitiveSceneProxy@@XZ)  C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\ProBuilderPlugin.generated.cpp.obj    ProBuilder
Error   9   error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::ApplyWorldOffset(struct FVector const &,bool)" (?ApplyWorldOffset@ULineBatchComponent@@UEAAXAEBUFVector@@_N@Z) C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\Module.ProBuilderPlugin.2_of_2.cpp.obj    ProBuilder
Error   10  error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::ApplyWorldOffset(struct FVector const &,bool)" (?ApplyWorldOffset@ULineBatchComponent@@UEAAXAEBUFVector@@_N@Z) C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\ProBuilderPlugin.generated.cpp.obj    ProBuilder
Error   1   error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::DrawLine(struct FVector const &,struct FVector const &,struct FLinearColor const &,unsigned char,float,float)" (?DrawLine@ULineBatchComponent@@UEAAXAEBUFVector@@0AEBUFLinearColor@@EMM@Z) C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\Module.ProBuilderPlugin.2_of_2.cpp.obj    ProBuilder
Error   2   error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::DrawLine(struct FVector const &,struct FVector const &,struct FLinearColor const &,unsigned char,float,float)" (?DrawLine@ULineBatchComponent@@UEAAXAEBUFVector@@0AEBUFLinearColor@@EMM@Z) C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\ProBuilderPlugin.generated.cpp.obj    ProBuilder
Error   3   error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::DrawPoint(struct FVector const &,struct FLinearColor const &,float,unsigned char,float)" (?DrawPoint@ULineBatchComponent@@UEAAXAEBUFVector@@AEBUFLinearColor@@MEM@Z)   C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\Module.ProBuilderPlugin.2_of_2.cpp.obj    ProBuilder
Error   4   error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::DrawPoint(struct FVector const &,struct FLinearColor const &,float,unsigned char,float)" (?DrawPoint@ULineBatchComponent@@UEAAXAEBUFVector@@AEBUFLinearColor@@MEM@Z)   C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\ProBuilderPlugin.generated.cpp.obj    ProBuilder
Error   7   error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::TickComponent(float,enum ELevelTick,struct FActorComponentTickFunction *)" (?TickComponent@ULineBatchComponent@@UEAAXMW4ELevelTick@@PEAUFActorComponentTickFunction@@@Z)   C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\Module.ProBuilderPlugin.2_of_2.cpp.obj    ProBuilder
Error   8   error LNK2001: unresolved external symbol "public: virtual void __cdecl ULineBatchComponent::TickComponent(float,enum ELevelTick,struct FActorComponentTickFunction *)" (?TickComponent@ULineBatchComponent@@UEAAXMW4ELevelTick@@PEAUFActorComponentTickFunction@@@Z)   C:\Users\Yvain\Documents\ProBuilder\Intermediate\ProjectFiles\ProBuilderPlugin.generated.cpp.obj    ProBuilder

```

# Answer
> 2 votes
`ULineBatchComponent` is not fully-exported out of the engine module, so you can't subclass it like that (the symbols you are getting link errors for are not tagged with `ENGINE_API`, so they don't get exported, so they cannot be found at link time).

A better solution to this problem is to create your own component that *delegates* to a `ULineBatchComponent` member for all functionality except that which you're trying to alter (based on your other question, this is the bounding box computation).

You *could* also modify the engine source code to expose the type (remove `ENGINE_API` from all members of `ULineBatchComponent` and added it to the class itself, remove `MinimalAPI` from the `UCLASS` macro). This is probably a recipe for long-term pain, though.

---
Tags: unreal
---


# Question
Title: What if I extend a uclass without UClass() in Unreal Engine?
What happens if I extend a uclass (or UObject) without the UClass() macro?

Will it still be a UClass() and managed by the garbage collector?

I'm just curious.

**Update**

I managed to extend ULineBatchComponent without `UCLASS` nor `GENERATED_UCLASS_BODY()`, it compiled, did not complain, and I could instantiate it.

# Answer
> 2 votes
`UCLASS` evaluates to a marker used by the Unreal Header tool to inject various bits of code, typedefs, attributes, and other bookkeeping information related to Unreal's reflection (and thus garbage collection) systems.

Anything that has `UCLASS` should also have `GENERATED_UCLASS_BODY` in the body of the class. Without both of those, your code *shouldn't* compile or link.

Failure to include `UCLASS` causes UHT to skip generation of the `YourFile.generated.h` header, which you should be including, and if you're not including that header you'll get compilation errors within the evaluation of `GENERATED_UCLASS_BODY`.

It may be possible to hack up the source file to get it through the compiler somehow (I stopped trying after a few basic attempts) but at that point you won't be able to instantiate or completely use the class because you won't have the related type info metadata Unreal's object system requires for things like `NewObject` to function.

**tl;dr**: bad things, don't do it.

# Answer
> 2 votes
You won't be able to instantiate the class without it because the UCLASS() macro above the class declaration creates the global UClass instance (a ptr to which is returned when you do GetClass() on an instance of the UObject) describing that class' metadata, which is required for spawning it (either via the editor/dynamically or via NewObject\<\>)

That is, if UHT doesn't catch you using UPROPERTY/UFUNCTION inside the body of something that isnt declared as a UCLASS or USTRUCT beforehand, which will make it error on the preprocessing stage.

---
Tags: unreal, inheritance
---


# Question
Title: How do I make my enemies to follow a path and allow them to collide with the player in Game Maker?
I am making a game in which enemies follow a path. These enemies should be colliding with the player, but it's not working.

The enemy is walking the path. And, I want to make it so if the player collides with the enemy, the game restarts the level. Game Maker doesn't let me collide my player with the enemy at all!

How could I make my enemy that follows a path collide with the player?

I'm using Game Maker: Studio.

# Answer
In order to collide objects, make sure the player **object** and the baddy **object** both have the **property** of

> solid

.

Then add the **event**

> collision: player

and give that **event** the **action** that restarts the level.
> 0 votes

---
Tags: collision-detection, game-maker
---


title: Flowing GPU compute water

text:
# Question
Title: Flowing GPU compute water
I have a civil engineering background and perform hydraulic and hydrologic analysis' regularly. They sell degrees for that sort of thing, but it's really not rocket science. I recently got it in my mind to implement the entire hydrologic and hydraulic process for a terrain on the GPU. I learned compute shaders only recently so I'm currently stuck being better at engineering than designing parallel GPU workflows.

You can calculate the amount of water generated during a rainfall event using the formula:
`Q (CF/S) = c * I (in/hr) * A (acres)`

I'm having difficulty moving beyond calculating the "acreage" of even the first area.

Current implementation overview:

1. The terrain is a regular grid of vertices at 1-unit intervals
2. A heightmap contains one R32 height value for each vertex
3. Currently, I'm only allowing flow in the 4 cardinal directions (no diagonals)
4. I'm using a Texture2D\[int\] as a stencil for vertices I have already analyzed

Current algorithm:

1. When the terrain tool has been active and is, now, not....
2. Clear the "stencil".
3. Scan the entire terrain for the lowest elevation.
4. That single point is the initial input to CS\_Flood.
5. CS\_Flood makes an X-axis pass.
6. Each input vertex is projected in both the X- and X+ directions up to 2048 times.
7. Finding an adjacent vertex with an OOB coordinate indicates the edge of the terrain in this direction. CurrentPoint is appended to the BoundaryPoints buffer and the projection loop for that direction is terminated. This was easy and works great every time.
8. Adjacent vertices with heights \>= the current vertex's height are marked in the stencil and added to the NextPass buffer.
9. Adjacent vertices with heights \< the current vertex's height indicates the peak of a ridge and terminates the projection loop. A future iteration of the flood fill *might* flow around the base of the ridge, up the "back" side of it and detect the same ridge a second time.
10. Any peak/ridge points that are detected more than once will **not** be a BoundaryPoint, for this purpose.
11. Any peak/ridge points detected exactly once are appended to BoundaryPoints and the projection loop in that direction is terminated.
12. CS\_Flood makes a Z-axis pass with the same code, using the points generated by the X-axis pass as input.
13. Right now, CS\_Flood continues alternating between the two directions indefinitely. Eventually, I'll terminate the overall loop whenever CS\_Flood completes and the NextPass buffer is empty.

Ideally, at that point, BoundaryPoints would contain each vertex that occurs on the natural drainage divide. Water drops landing within the boundary eventually flow to the same low spot. Water drops landing ouside the boundary go "somewhere else".

Then:

1. Without clearing the stencil, re-scan the terrain for the lowest, non-stenciled, vertex.
2. Iterate CS\_Flood.
3. Repeat until the stencil is full (or something similar).

3D is hard to perceive with these colors; this shows contour lines at integral elevations:
(a hole surrounded by a berm near the edge)

There are about 10 unique ways to drain across a vertex; giving each one a unique color looks like:
(visible circular tool marks, "ridges" show up nicely)

This shows every point generated by CS\_Flood, boundary or otherwise, as a POINTLIST:

The algorithm **always** *almost works*. Sometimes, it even works correctly. Other times, the algorithm is clearly contained to the correct shape but will continue to output points indefinitely. As seen in the 3rd screenshot, sometimes it gets confused. There must be another situation/factor that I've overlooked. I would appreciate any help finding my oversight or suggestions of simpler and/or more elegant ways to attack the problem.

MissingPoint! can be included by band-aiding the algorithm to add every new BoundaryPoint detected to the NextPass buffer. During the next pass, 99% of the points generated by that band-aid will waste a small amount of GPU time determining that they can't go anywhere and doing nothing. During the first pass, sending LowestPoint along with the other NextPass points would also handle this specific scenario.

I know it's plausible and, given enough time, I'll be able to band-aid it enough to do what I want. I'd like to do it in a better, smarter, faster way, if possible, and I don't have enough experience yet to know better.

# Answer
> 1 votes
When a drop "tried" to visit a vertex, the stencil was marked with `InterlockedExchange` using the "original value" to determine if it was *already* stenciled (even though I just overwrote it).

The best algorithm I came up with gave the flood a "scratch pad" and a single rule: "don't flow down-hill" (heights equal to or greater). That eliminated almost all of the complicated tests. While it is generally good at not flowing *over* peaks/ridges, it does flow *along* them because the adjacent vertices are "flat". This occasionally allows drops to sneak past ridge-lines.

Each of the "too far" points is, then, "flowed" and will flow "into" the drainage area (stops at a 1) or not (stops at a 0). The "nots" are discarded and the corrected scratch-pad is copied into the "final". If the final is already stenciled, the scratch pad is discarded. (Future: those collisions should collectively represent the outer boundary of the current drainage area.)

At 10FPS:

The "nots" are shown in red, once the large area is copied into the final and becomes green, then the algorithm repeats for the remaining unstenciled areas.

---
Tags: directx, algorithm, terrain, compute-shader
---


# Question
Title: Implementing getters for a singleton script in unity
Ok the title might be a bit confusing but what I want to do is make a getter that returns the class, exactly like unity does with the camera.current.

You should just be able to go class.current and get the running instance of the class but I have no idea how to do this as it would most likely be a static method but how would you return the class form a non static class without some sort of out of class variable? or do you have to make the class static?

# Answer
You just need a static variable of the same type as the containing class. Then you set that static variable to your instance of interest. For `Camera.current`, that would be whatever camera is currently in use. Or `Camera.main` is whatever camera is tagged with 'MainCamera'. You decide what conditions result in the static variable being set. For example below, if you just had one instance in your game, you can set it in the `Start` method.

```
public class MyScript : Monobehaviour {
    public static MyScript myInstance;

    public void Start() {
        myInstance = this;
    }
}

```

You'd access this instance with `MyScript.myInstance`

Or if you didn't want it to be a script attached to an object, you can easily do something similar with a static code block:

```
public class GameManager
{

    public static GameManager instance;
    static GameManager()
    {
         instance = new GameManager();
    }

    public GameManager() {
         //initialize stuff here
    }
}

```

Or even stuff if all into a getter:

```
public class GameManager
{
    static GameManager _instance;
    public static GameManager instance {
        if(_instance == null)
        {
            _instance = new GameManager();
        }
        return _instance;
    };

    public GameManager() {
         //initialize stuff here
    }
}

```
> 2 votes

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


# Question
Title: How could I draw text in an 'info bubble' with libgdx?
I am making an android game using libgdx where there are textures on the screen which represent people. When you touch a person sprite I want a little info bubble to pop above their head displaying some information about them in text form (something a bit like how speech is shown in a comic book). The sprites move and the info should follow above them until it is tapped closed.

I have got something working at the moment, which is really basic. I have rectangle that is part of the ShapeRenderer that is drawn, I then draw the text over the top using the batch draw.

I want the rectangle to have curved edges and resize depending on the size of the text but before I start writing something.

Does anyone have any suggestions on how I should go about it? Should I try and use dialog from scene2d and render my whole game using scene2d? From what I have seen it seems good for menus but I'm not sure about rendering a whole game using it.

Or is there something else?

# Answer
> 1 votes
Ok so two parts to this;

> rectangle to have curved edges and resize depending on the size of the text

This sounds great for 9patch! 9patch can scale up textures using only certain portions of the image, so you get to keep undistorted smooth corners when scaling both vertically and horizontally.

> depending on the size of the text

LibGDX has a useful tool for this, BitmapFonts. We can call : `font.draw(Batch batch, java.lang.CharSequence str, float x, float y, float targetWidth, int halign, boolean wrap)`. Then to find out how tall we need to draw the box after specifying the width with `targetWidth`by capturing information from the GlyphLayout object returned.

... However we have already drawn it so this is no good! Instead we can use a GlyphLayout object directly and then call `font.draw(Batch batch, GlyphLayout layout, float x, float y)`. Once we have added all the text and more importantly drawn the background.

```
//It might look something like this
BitmapFont font = new BitmapFont();
...
int textBoxBuffer = 5; // Allow for box to surround the text
int textBoxWidth = 80; // the default width of the textbox
void drawSpeech(String str, int x, int y){
    GlyphLayout layout = new GlyphLayout(str, x, y, textBoxWidth , Align.left, true);
    draw9PatchTextBox(x - textBoxBuffer, y - textBoxBuffer,
                      layout.width + textBoxBuffer, layout.height + textBoxBuffer);
    font.draw(batch, layout, x, y);
}

```

---
Tags: android, libgdx
---


title: Tilemap Object Placement

text:
# Question
Title: Tilemap Object Placement
I am looking for a way to select tiles within a bounding box for object placement within a scene/world, similar to Roller Coaster Tycoon and other simulation games.

<sub>(source: tumblr.com)</sub>

In the above screenshot of Theme Parkitect you can see that a 4x4 grid is used as the footprint for the object being placed. Given the bounding box and location of the mouse, how can I suitably determine the neighbouring tiles which fall into the bounding box?

I have implemented a graph like structure of tiles, corners and edges by following Amit's fantastic articles on Red Blob Games. As of such, I have a graph of all tiles and their neighbours as well as associated tile edges and corners. These tiles are laid out diagonally against the world axis so simply selecting all tiles within a rectangular region isn't as simple (or maybe it is?) as i'd expected. This layout can be changed if necessary however.

The main source of information used to steer my implementation has been from Amit's Thoughts on Grids and the graph structure implemented in his article about Procedural Map Generation

As a bonus, I would like to implement a way to rotate the object being placed such that a footprint of 1x5 could be rotated to instead be 5x1. I would imagine that once the basics of multiple tile picking has been implemented this should be reasonably simple.

Unfortunately, Amit's articles don't seem to cover this topic and the approaches I have found and tried so far haven't quite yielded the correct results. Any help that fits in with the graph like structure for connected tiles, edges and corners would be greatly appreciated.

I have tried to implement the approach outlined in Raytracing on a Grid with a mixture of both Broad-Phase collision and A\* Path Finding but neither of these two approaches cover selection of multiple surrounding tiles.

I am not concerned with the viability of tiles for placing objects at this point (i.e.: sloped edges of tiles or obstructions from other objects). The ideal solution for now would simply be to find the tiles included within the bounds.

My initial forays into this have resulted in incorrect results whereby the bounding rect doesn't include *all* neighbouring tiles (sometimes missing entire rows/columns) or returning neighbours outside of the bounds. I was pretty sure that I was close to a winning implementation but my vector math isn't strong enough to validate my findings.

# Answer
if your data is in a one dimensional array you can convert from index to coords and back easily. making it easy to determine what is beside a coord

```
public int TileIndex(int x, int y)
{
    return y * Width + x;
}
public Vector2 TilePosition(int index)
{
    float y = index / Width;
    float x = index - Width * y;
    return new Vector2(x, y);
}

```

so to check the tile to the east of 2,2 you can get the tile at index 3,2

```
if (Empty(TileAt(TileIndex(x + 1, y)))
    MoveEast();

```
> 1 votes

# Answer
When you have your mouse-picking working all you need to do is overlap your map with the object you wish to place. This problem would be the same for an isometric grid as for a rectangular grid.

Take this exmaple map:

And this building:

On this map the green squares are meant to as grass, the brown squares as mountain and the blue squares as water. Although this is irrelevant to the actual solution

On the building the color of the squares determines the placemant restrictions, white can be placed anywhere, yellow can only be placed on green squares and orange can be placed on either green or brown squares.

After you've picked the square the mouse is over on the map you simply pick a square from your building-template, (this can be any square you want, top-left, best-effort middle or whatever provides the best experience to your players), let's use top-left for this example. and then check if all squares are compatible with the map.

This can be done by simply looping over the squares:

```
for each square in building_template do:
    determine offset from cursor on template
    pick tile from map with same offset
    check if placement is allowed

    if placement is not allowed, depending on your design either:
        return false immediately and draw the entire template in red.
        color that square from your template red and continue, keep track if any blocking squares were encountered

```

If we place the building on C4 for example We'd get the following result:

Where B2 of the building is blocked because that square could only be placed on green tiles.

Note that you can have the matching algorithm take into account any conditions you want.

I hope this is the problem you were trying to solve.
> 2 votes

---
Tags: tilemap, picking
---


# Question
Title: Need help with a field of view-like collision detector!
I ran into a trouble while making a field of view for my character. I figured how to make it work with a Linecast, but what I really need is a cone-shaped field, so that the character can detect objects or enemies if they get in that field of vision. It also needs to be intersectable by other objects, so OnCollisionEnter won't work. I suspect that Raycasting might solve the problem, but I couldn't quite understand it's workings, because I'm still new. I would really appreciate any ideas that might help to solve it. Here is what I need:

Here is what I have so far, but this detector is unsuitable, because it can only detect objects in a straight line:

```
public Transform sightStart, sightEnd;
    // Update is called once per frame
    public bool objectSpotted = false;
    void Update () {
        Raycasting1 ();
}
void Raycasting1()
{
    Debug.DrawLine(sightStart.position, sightEnd.position, Color.green);
    objectSpotted = Physics2D.Linecast (sightStart.position, sightEnd.position);
}

```

# Answer
Physics.OverlapSphere() and Physics2D.OverlapCircleAll() will return all colliders within a radius of a point. Those colliders are in range, but possibly not in view. If you are going to do this often, create an array once, and pass it to Physics2D.OverlapCircleNonAlloc(), instead.

To see if they are in view, check the dot-product of the normalized collider-to-center direction and the normalized character-forward direction. The dot is 1.0 if the object is directly in front of the character (0 degrees), 0.0 if the object is directly left/right of the object (+-90 degrees), and -1.0 if the object is directly behind (+-180 degrees); it is the cosine of the angle between the object and forward.

**Edit:**

```
void Raycasting1()
{
    Collider2D[] cols = Physics2D.OverlapCircleAll(transform.position, 1);
    Vector3 characterToCollider;
    float dot;
    foreach (Collider2D collider in cols)
    {
        characterToCollider = (collider.transform.position-transform.position).normalized;
        dot = Vector3.Dot(characterToCollider, transform.forward);
        if (dot >= Mathf.Cos(55))
        {
           //objectSpotted = true;
        }
        else
        {
           //objectSpotted = false;
        }
    }
}

```

For many, many objects:

```
Collider2D[] inRangeColliders = new Collider2D[1000]; //No more than 1000
void Raycasting1()
{
  int inRangeColliderCount =
     Physics2D.OverlapCircleNonAlloc(transform.position, 1, inRangeColliders);
  for (int i = 0; i < inRangeColliderCount; i++) //replace the foreach
  {
     //collider. is now inRangeColliders[i].
     ...
  }
}

```
> 5 votes

# Answer
First of all... don't over complicate the objective... I would suggest creating your own collider, and not using one from unity...

First of all, get all of the enemies and put them in their own separate list.

```
public void EnemyList(){
    GameObject[] GameObjectArray = FindObjectsOfType (typeof(GameObject)) as GameObject[];  // we check every gameobject and only select the Enemies
    unitList = new List<GameObject> ();                                                     // and put them in their own separate list for quicker checking
    for (int i = 0; i < GameObjectArray.Length; i++) {
        if (GameObjectArray [i].layer == unitLayer)
            unitList.Add (GameObjectArray [i]);
    }
}

```

Then we can check if they are within sight... the condition to check if we should check if they are in our fov...

```
// check to see if a enemy is within viewing range
public bool IsEnemyNear(int i){
    float dist = Vector3.Distance (unitList [i].transform.position, transform.position);
    if (dist < unitDistanceFromNpc) // if true, an Enemy is within range
        return true;
    else return false;
}

```

If the enemy is near and within the player's viewing range.. then we only need to shoot ONE `Raycast`... Cause we know where he is... and if he is hiding or behind crates or barrels.. then we cannot see him...

```
// check to see if Enemy is in npc's current fov
public bool IsEnemyInNpcFOV(int i){
    Vector3 targetDir = unitList[i].transform.position - transform.position;
    Vector3 forward = transform.forward;
    float angle = Vector3.Angle(targetDir, forward);
    if (angle < npcFov)
        return true;
    else return false;
}

```

and if the NPC can see the player...

```
// can the Npc see the Player
PlayerSeen = false;
public void IsPlayerSeen(int i){
    Vector3 direction = ( unitList[i].transform.position - transform.position ).normalized;
    if ((Physics.Raycast (ourPosition, direction, out hit, unitDistanceFromNpc) && hit.collider.tag == "Player")) {
        hit.collider.gameObject.GetComponent<Unit> ().isSeen = true;
        PlayerSeen = true;
    }
}

```

Basically, you create your own collider.. if the enemy is range of that collider then you check if it's in your fov.. and if it is, then you check if you can see him... i.e... he is not behind a pile of crates.... a simple loop.. and only one raycast.... hope this helps....
> 3 votes

---
Tags: unity, collision-detection, raycasting
---


# Question
Title: How to map changing stances (southpaw/orthodox) to gamepad controls?
I am developing a third person hack n slash style game which features a variety of melee and projectile weapons as well as unarmed combat. The player will be able to dual wield any combination of the above weapons eg. a sword and a pistol, or a knife and a bare fist. I'm trying to work out the gamepad controls based on the game mechanics, but I've come to a dilemma regarding the movesets.

Originally I had the left and right triggers mapped as the left and right hand attacks. However, some of the attack moves that I have planned involve the player taking a step forward. Meaning they may have started in orthodox stance (left foot forward) but will end up in southpaw (right foot forward). For some weapons like firearms the stance makes no difference, since the attacks will be the same from either. But for some melee weapons and especially for unarmed combat this is a significant difference. For example, from orthodox stance the left trigger should logically do a jab attack from the front hand, while the right trigger should do a straight punch attack from the back hand. If the player now does a lunging attack in which they take a step forward, they end up with their other foot infront, meaning that now the left trigger cannot do a jab but must perform a straight punch since the left hand is no longer in front.

So the question is how to resolve this without having a controls system that confuses the player. There are a few options I have considered after studying other games, but I am looking to see if a better alternatives exists.

**1)** Seen in Elder Scrolls, Dark Souls, Tekken:

Use 2 attack buttons but have the player always stay in a single stance. This way they the left and right limbs will always perform the same move. The downside of this is that attacks which would normally leave the player in another stance have to either be avoided or the animation has to include the player returning to their original stance. While this solves the problem it can look unrealistic.

**2)** Seen in DOA, VF:

Use only 1 attack button, instead of one for each limb. This will mean that the stance of the player is irrelevant since a single button will play the correct attack animation of either the left limb or right limb depending on the stance. While this is more realistic it makes it difficult to have dual wielding weapons with only one button controlling both. For example, consider if a pistol and sword are being dual wielded, the left trigger may swing the sword while the right trigger may fire the pistol; but if both weapons are mapped to only the right trigger what attack should happen? The sword, the pistol, both? Here lies the problem.

**3)** Seen in MK:

Use 2 attack buttons which refer to the front or back limb, not the left or right limb. This method allows for the player to switch stances, since for example the left trigger may refer to the front hand irrespective of which stance the player is in. In a side scrolling game this may not be a problem, but in a third person game where the camera is behind the player, I am concerned that this type of controls will be confusing. Especially since the convention (correct me if I'm wrong) for dual wielding seems to be that the left and right triggers control the left and right weapons/limbs.

So are these the only options, or is there a better way of mapping the controls for this use case?

# Answer
Honestly, of the control schemes you outlined, the current one (ie, the problem you are trying to solve) sounds the most natural and intuitive to me.

As long as you give the player a simple method for changing stance (preferably a single button, easy to access way), then getting off the attack you want shouldn't be a problem.

This could be coupled with a "switch and fire" move, where hitting the switch stance and a fire button simultaneously will perform both actions, allowing the player to smoothly transition between moves.
> 1 votes

---
Tags: game-design, control, shooter, third-person-view, combat
---


title: Mesh disapears before out of fov

text:
# Question
Title: Mesh disapears before out of fov
I use a C# script to move the vertecies of my quad around the world space. It works perfectly fine, but when I move/ rotate the camera away, so it does not look at the position of the quad, the quad disappears.

I cannot change the size of the quad, since that would not work with my other scritps.

How can I force the camera to allway render the mesh of the quad?

# Answer
> 4 votes
I'm assuming you have reasons for moving the vertices rather than just transforming the quad so I won't point out how slow this way is =p.

What Unity is doing is called frustum culling, it basically checks the precalculated bounds of an object to see if it's possibly on the screen and if not, just skips it entirely. This works fine except when the bounds don't match the vertices. That's what is happening here.

You can tell Unity to update the bounds via Mesh.RecalculateBounds, or if you have the information to do it without letting Unity brute force it's way through all the vertices you can manually update localBounds and related variables in the mesh.

---
Tags: unity
---


# Question
Title: Does Specular Power affect the Brightness?
I read the book *Real-Time Rendering, 2nd Edition*. Somewhere in there it say:

But I did the experiment and concluded that the mshi doesn't seem to affect to the brightness (it causes the area just to be narrower):

The experiment is base on http://www.rastertek.com/dx11tut10.html. Am I missing something? I didn't find an errata for the book on its corrections Website, and my first-languages isn't English, so maybe my vocabulary understanding is wrong?

Does the Shininess means the Brightness? Or what else?

# Answer
> 1 votes
Okay, I eventually understand the Shininess is different from Brightness.

Because I misunderstood the shiny will increase the area of highlight before.

Actually, the more shiny will let the area of highlight become smaller.

So the below picture is more shiny than the above picture.

Sorry for asked a seemingly has nothing to do with programming problems.

---
Tags: shaders, rendering, specular
---


# Question
Title: How to rotate camera counterclockwise around player?
Holder contains camera and rotates around player

Camera looks like in diablo, titan quest, grim dawn, etc

I cant rotate camera to negative angle values

My code:

```
public void ChangeRotation(float val){
    if(isTurning)
        return;
    isTurning = true;
    needAngleY += val;
}

void Turning(){
    Quaternion quatertion = transform.rotation;
    Vector3 eulerAngle = new Vector3(0, quatertion.eulerAngles.y, 0);

    if(needAngleY - eulerAngle.y < 0.2f){
        if(needAngleY == 360 || needAngleY == -360){
            needAngleY = 0;
        }
        eulerAngle.y = needAngleY;
        isTurning = false;
    } else {
        eulerAngle.y = Mathf.Lerp(eulerAngle.y, needAngleY, timeRotation * Time.deltaTime);
    }
    m_Compas.rotation = eulerAngle.y;
    quatertion.eulerAngles = eulerAngle;
    parentTran.rotation = quatertion;
}

```

# Answer
You can use transform.RotateAround() to specify a rotation axis for your camera. If you pass in the player transform.position as the first param and the axis you want to rotate around as the second, this should get you what you want.
> 1 votes

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


# Question
Title: How to load a png file without alpha premultiplying in ios?
I am making a game in which I use the alpha value, in some cases for transparency, in others for occlusion, and for HDR in others.

I'm loading the images like this (this is MonoTouch, but objective-c can be easily converted to c#):

```
CGImage bitmap = new UIImage(resourcePath).CGImage;
width = bitmap.Width;
height = bitmap.Height;
IntPtr pixels = Marshal.AllocHGlobal(bitmap.Width * bitmap.Height * 4);
using (var context = new CGBitmapContext(pixels, bitmap.Width, bitmap.Height, 8, bitmap.Width * 4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast))
{
    var dest = new RectangleF(0, 0, bitmap.Width, bitmap.Height);
    context.ClearRect(dest);
    context.DrawImage(dest, bitmap);
    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, pixels);
}
Marshal.FreeHGlobal(pixels);
bitmap.Dispose();

```

However, this butchers all my pixels by premultiplying them by the alpha value.

The reason behind this is that I'm creating `CGBitmapContext` with `CGImageAlphaInfo.PremultipliedLast`. I tried with `CGImageAlphaInfo.Last`, but creating the context fails. Core Graphics only works with premultiplied alpha, as explained here.

I tried using `CGDataProviderCopyData`, as well as pngcs. However, they both simply decode the bitmap, and don't convert the pixels to RGBA, which is relevant when you're storing 8-bit, 24-bit PNGs, or indexed PNGs (I have lots of these, which are the result of optimizing my PNG files for size).

So I'm lost. I need a way to decode PNG files in a way that they are converted to RGBA *without* premultiplying my colors by the alpha value. Is that too much to ask? GDI, GDI+, System.Drawing, DirectX, Mono for Android as well as PSM do it just fine...

Also, why does iOS development has to be so picky?

# Answer
> I tried using CGDataProviderCopyData, as well as pngcs. However, they both simply decode the bitmap, and don't convert the pixels to RGBA, which is relevant when you're storing 8-bit, 24-bit PNGs, or indexed PNGs.

Did you look at ImageLineHelper.Palette2rgb()? What functionality are you missing?

(disclaimer: I'm the PngCs developer)
> 4 votes

# Answer
C code:

```
CFURLRef url = CFURLCreateWith...("path/to/file.png");
CGDataProviderRef dp = CGDataProviderCreateWithURL(url);
CGImageRef img = CGImageCreateWithPNGDataProvider(dp, nil, NO, kCGRenderingIntentDefault);
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(img));
UInt8* pixelData = CFDataGetBytePtr(data);  // not premultiplied RGBA8 data
// use pixelData

CFRelease(data);
CGImageRelease(img);
CGDataProviderRelease(dp);
CFRelease(url);

```
> 0 votes

---
Tags: textures, ios, opengl-es, monotouch, png
---


title: Unity make dotted line renderer

text:
# Question
Title: Unity make dotted line renderer
I know, that this question was asked before, but I could not find a proper answer to this. So how can I make my line dotted? I added a texture with a dot, but it just gets stretched for the length of the line, which is obviously not what I want. I'm using C# btw, if some code is needed here.

Edit: Inspector:

Edit: New Code :

```
public class dashedLine : MonoBehaviour
{
    public Vector2 newPosition;
    private LineRenderer line;

    void Awake()
    {
        line = GetComponent<LineRenderer>();
    }

    void Update()
        {
        line.material.SetTextureOffset("_MainTex", new Vector2(Time.timeSinceLevelLoad * 4f, 0f));
        line.material.SetTextureScale("_MainTex", new Vector2(newPosition.magnitude, 1f));
        line.SetPosition(0, newPosition);
       }
}

```

This is what I get:

Edit: This works now, when I use a Texture which has multiple dots in a row and put it to a material with Shader: Unlit/Transparent. I still don't know, why it's not working with a single dot.

Edit2: I had to recreate the dot texture with a single dot and it worked, so there was some issue on my side. Everything works now fine.

# Answer
> 1 votes
Apply a texture with a circle to a material, assign that material to a line renderer, and attach a script to it that will scale the texture relative to the magnitude of the line. Here's some code:

```
public class LineScript : MonoBehaviour
{
    private LineRenderer line;

    void Awake()
    {
        line = GetComponent<LineRenderer>();
    }

    void Update()
    {
        Vector2 newPosition = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
        line.material.SetTextureOffset("_MainTex", new Vector2(Time.timeSinceLevelLoad * 4f, 0f));
        line.material.SetTextureScale("_MainTex", new Vector2(newPosition.magnitude, 1f));
        line.SetPosition(0, newPosition);
    }
}

```

---
Tags: unity
---


# Question
Title: What is a fragment in 3D graphics programming?
What is a fragment in a fragment shader? Wikipedia says that:

> In general, a fragment can be thought of as the data needed to shade the pixel, plus the data needed to test whether the fragment survives to become a pixel (depth, alpha, stencil, scissor, window ID, etc.)

So is it textures, vertices or something else?

# Answer
In computer graphics, a fragment is the data necessary to generate a single pixel's worth of a drawing primitive in the frame buffer.

This data may include, but is not limited to:

* raster position
* depth
* interpolated attributes (color, texture coordinates, etc.)
* stencil
* alpha
* window ID

As a scene is drawn, drawing primitives are rasterized into fragments which are textured and combined with the existing frame buffer. How a fragment is combined with the data already in the frame buffer depends on various settings. In a typical case, a fragment may be discarded if it is farther away than the pixel that is already at that location (according to the depth buffer). If it is nearer than the existing pixel, it may replace what is already there, or, if alpha blending is in use, the pixel's color may be replaced with a mixture of the fragment's color and the pixel's existing color, as in the case of drawing a translucent object.

In general, a fragment can be thought of as the data needed to shade the pixel, plus the data needed to test whether the fragment survives to become a pixel (depth, alpha, stencil, scissor, window ID, etc.)

From wikipedia
> 32 votes

# Answer
A fragment is simply the data that is given from the contribution of the 3 vertices around the pixel you're shading.

In the Vertex Shader, you output some data per vertex (color, texture coords, ...). Then in the Fragment Shader, for each pixel you get a weighted average of those values, that you then use to build the final color(s) of the pixel.
> 7 votes

# Answer
> What is a fragment in a fragment shader

The only precise thing that can be said is defining the inputs and outputs of the fragment shader.

Since that has been done / is too broad, I will focus on the intuitive visual side of it.

**A fragment is the raster output**

The OpenGL wiki says:

> A Fragment is a collection of values produced by the Rasterizer.

Which makes sense since the fragment shader comes after the rasterizer which produces its input.

And this is the visual representation of the rasterizer output:

Image source.

The input of the rasterizer is a 3D triangle and a point of view, and the output, is a set of pixels which might appear on the screen (if they don't get blocked by others).

Each of those those little squares (which are encoded as a single plixel), is a piece of the triangle, and *fragment* is just another name for piece.

More information at: https://stackoverflow.com/questions/17789575/what-are-shaders-in-opengl-and-what-do-we-need-them-for/36211337#36211337
> 5 votes

# Answer
In the same way a vertex shader acts on vertices, a fragment (or pixel) shader will just act on pixels.
> 3 votes

---
Tags: shaders, terminology
---


# Question
Title: Wwise with Unity Rigidbody 2d or Collider 2d
I'm half way in making a 2D game in Unity and found that Wwise needed the game objects to have a normal 3D RigidBody, since that's quite some work to replace everything, is there any way around?

# Answer
> 0 votes
You could script the replacement. If you have a common script for all the objects that need to use Wwise:

```
if(this.GetComponent<RigidBody2D>() != null)
{
    this.Destroy(this.GetComponent<RigidBody2D>());
    RigidBody newBody = this.AddComponent<RigidBody>();
    //Make whatever config changes you need to newBody
}

```

However, this is kind of a clunky way to do it, since it only replaces the items at runtime, and will have to replace every time.

An editor script is a better way to approach. This supposedly will add a menu item to run this script in the editor. I say supposedly because it's completely untested. The premise is the same though, find objects that have your component of interest, then remove that component and add a new component of the type you want.

```
class Replace2DComponents extends Editor
 {
     @MenuItem ("CustomCommands/Replace2D")
     static function Replace2D()
     {
         List<GameObject> rigid2ds = new List<GameObject>();
         rigid2ds.AddRange(FindObjectsOfType(typeof(RigidBody2D) as GameObject);
         for(GameObject obj in rigid2ds)
         {
             DestroyImmediate(obj.GetComponent<RigidBody2D>());
             RigidBody newBody = obj.AddComponent<RigidBody>();
             //other config changes for newBody
         }
     }
 }

```

Finally, you shouldn't be in this situation in the first place. You should be using prefabs to create your game objects, and should thus only need to make your changes in a few places to get the desired effect.

---
Tags: unity, rigidbody, wwise
---


# Question
Title: Unity3D - Resources load to materials, how to?
I think is a simple question, but I don't know nothing about it:

I have an created material in my materials folder, I just want to apply it to the GameObject by script.

I am trying

```
this.GetComponent<Renderer>().materials[0]=Resources.Load("Test", typeof(Material)) as Material;

```

The material name is Test and it is in materials folder, but the return is always the default material applied to the GameObject, so I think Unity didn't found it.

# Answer
> 3 votes
`Renderer.materials` is a getter that returns *a copy of* the materials array.

The code you've written modifies that copy, but does not change the material used by the object, which is why it always shows up as the default.

What you want to do instead is something like the following:

```
var renderer = GetComponent<Renderer>();
var materials = renderer.sharedMaterials;
materials[0] = Resources.Load<Material>("Test");
renderer.sharedMaterials = materials;

```

or, if you only have one material on the object, you can take a shortcut:

```
renderer.sharedMaterial = Resources.Load<Material>("Test");

```

---

**One detail of note:**

In these examples I chose to use `sharedMaterials`/`sharedMaterial`, which are slightly different getter/setter properties. `materials`/`material` do a deep copy, in that they create a unique instance of the materials they return.

This means if I have 10 cubes using the "red" material, then I say `cube5.renderer.material.color = Color.Blue`, only the one cube will change colour - it has a unique copy of the material now, which is separate from the red material used by all the others.

If I instead say `cube5.renderer.sharedMaterial.color = Color.Blue` then *all* my red cubes will turn blue, because I've modified the single material instance they're all sharing.

This fact about hidden material copying is useful to keep in mind, since materials aren't garbage collected as readily as certain other objects. You want to make sure you know when you're creating a new instance of a material versus when you're modifying an existing (and possibly shared) instance.

---
Tags: unity, materials
---


# Question
Title: Unity3D - Determining if a spherical object is grounded using raycast
I'm making a game revolving around moving a ball around a space. My game has a jump mechanic, so I need to know when I'm grounded in order to determine when I'm able to jump. Best way to check this is to setup raycast from ball's origin and make it constantly face downwards. However, I'm running into an embarrassing issue: the ball keeps rotating, so I'm not able to find a constant downward ray to use for finding the ground.

I started making code that looks similar to this, which the object's local transform:

```
bool grounded = false;
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hit;

if(Physics.Raycast(ray, out hit)){
//determine if object is on ground
grounded = true;
}

```

This caused the issue I stated earlier, where the ray would point downward but only relative to the object's current rotation. In other words, if the ball was upside-down, the ray would be pointing upwards.

My current code for this look similar to this, which now uses world space to determine what is 'down':

```
bool grounded = false;
Ray ray = new Ray(transform.position, -Vector3.up);
RaycastHit hit;

if(Physics.Raycast(ray, out hit)){
//determine if object is on ground
grounded = true;
}

```

However, in this instance, the ball raycast actually points directly to position Vector3(0,-1,0), which is even weirder than my initial problem and shouldn't be an issue based on other posts about this issue.

The only other way I can think of to properly determine whether the object is grounded is to see if it collides with anything. However, the other reasons I want to determine whether the player is grounded using raycast are:

1. for determining whether the player is over an endless pit (e.g. if they fell off the world) in order to start a kill/respawn timer
2. to ensure the player can perform a move equivalent to a butt stomp while in the air

If anyone knows how to perform a raycast on a spherical object in Unity, it's be much appreciated.

# Answer
> 1 votes
So, about that second piece of code with the -Vector3.up reference. I was using a Debug method call to check for the ray's direction. If you're experienced in Unity, you know where this is going.

Yes, I used Debug.DrawLine() instead of Debug.DrawRay(), which caused the editor to draw a line from my player to the position (0,-1,0). I suspected this when I was about to go to sleep for the day but only tested it this morning. So, there's one issue out of the way.

I also checked to see if my ray was not unintentionally detecting my player's collider, and it seems to be properly ignoring it.

Long story short, I had already fixed my problem but had used the incorrect methods for determining it was correct. So, for those who are having issues with seeing your raycast in the editor, use Debug.DrawRay().

# Answer
> 0 votes
You may need to add a distance for how far the ray should extend from the Transform.position. Try this

```
if(Physics.Raycast(ray, out hit, <yourDistance>))

```

---
Tags: unity, raycasting, sphere
---


# Question
Title: Why current scene in cocos2dx has no children when accessed from outside scene class?
I want to access a sprite in a scene, but I cannot get the running scene from outside the scene class.

The scene is created using:

```
Scene* MyScene::createScene() {
    auto scene = Scene::create();
    auto layer = MyScene::create();
    scene->addChild(layer);
    return scene;
}

bool MyScene::init() {
    this->addChild(sprite,100, 1234);
}

```

But if I then access the running scene from outside the class, it has no children.

```
Director::getInstance()->getRunningScene()
//should be the MyScene instance with sprite children, but has no children.

```

I also tried giving the scene layer a tagname, but with the same result.

```
scene->addChild(layer,100,TAGNAME);
...
Director::getInstance()->getRunningScene()->getChildByTag(TAGNAME)
//returns NULL because getRunningScene has no children.

```

The only way I can access the scene is making a static reference in my AppDelegate, but this doesn't seem a proper way. **How can I get the current scene correctly from outside the class?**

# Answer
> 2 votes
Your `layer` is a child of `scene`.

Try a `Director::getInstance()->getRunningScene()->getChildrenCount()` and you will find only 1 child: `layer`

You will have to search the children of `layer` to find the one you need :)

I would use:

```
auto scene = Scene::create();
auto layer = HelloWorld::create();
scene->addChild(layer,0,999); // add layer as a child to scene

```

In the `init()`:

```
this->addChild(yourNode,100,TAGNAME); //this points to layer!

```

To find yourNode with tag

```
auto scene = cocos2d::Director::getInstance()->getRunningScene();
auto layer = scene->getChildByTag( 999 );
auto node = layer->getChildByTag( TAGNAME );

```

I think this will answer your question.

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


# Question
Title: Why do we use 4x4 matrices to transform things in 3D?
To translate a vector by 10 unit in the X direction, why do we have to use a matrix?

We can just add 10 to the mat\[0\]\[0\], and we got the same result too.

# Answer
Yes, you can add a vector in the case of translation. The reason to use a matrix boils down to having a uniform way to handle different combined transformations.

For example, rotation is usually done using a matrix (check @MickLH comment for other ways to deal with rotations), so in order to deal with multiple transformations (rotation/translation/scaling/projection...etc) in a uniform way, you need to encode them in a matrix.

Well, more technically speaking; a transformation is mapping a point/vector to another point/vector.

```
p` = T(p);

```

where p\` is the transformed point and T(p) is the transformation function.

Given that we don't use a matrix we need to do this to combine multiple transformations:

> p1= T(p);
>
> pfinal = M(p1);

Not only can a matrix combine multiple types of transformations into a single matrix (e.g. affine, linear, projective).

Using a matrix gives us the opportunity to combine chains of transformations and then batch multiply them. This saves us a ton of cycles usually by the GPU (thanks to @ChristianRau for pointing it out).

> Tfinal = T * R * P; // translate*rotate*project
>
> pfinal = Tfinal\*p;

It's also good to point out that GPUs and even some CPUs are optimized for vector operations; CPUs using SIMD and GPUs being data driven parallel processors by design, so using matrices fits perfectly with hardware acceleration (actually, GPUs were designed to fit matrix/vector operations).
> 35 votes

# Answer
**3x3 matrices cannot represent 3D translations, but 4x4 matrices can**

A simple argument why 3D translations are not possible with 3x3 matrices is that translation can take the origin vector:

```
0
0
0

```

away from the origin, say to `x = 1`:

```
1
0
0

```

But that would require a matrix such that:

```
| a b c |   |0|   |1|
| d e f | * |0| = |0|
| g h i |   |0|   |0|

```

But that is impossible.

A "more overkill"/"more elegant" argument is the singular Value Decomposition theorem, which says that every matrix can be made up with two rotations and one scaling operation:

* rotate to align with eignevectors
* scale with the eigenvectors
* rotate to the final desired position

No translations there.

**Why is it possible to use matrices to represent rotations?**

Many modeled objects (e.g. a car chassis) or part of modeled objects (e.g. a car tire, a driving wheel) are solids: the distances between vertexes never change.

The only transformations we want to do to on them are rotations and translations.

Matrix multiplication can encode both rotations (NxN matrix) and translations (we need one extra dimension).

Rotation matrices have explicit formulas, e.g.: a 2D rotation matrix for angle `a` is of form:

```
cos(a) -sin(a)
sin(a)  cos(a)

```

There are analogous formulas for 3D, but note that 3D rotations take 3 parameters instead of just 1.

Translations are less trivial and will be discussed later. They are the reason we need 4D matrices.

As a cultural fact, the set of all rotation matrices in a dimension is called the special orthogonal group (SO(n)), which is also a Lie group, and has fundamental applications in particle physics.

**Why is it nice to use matrices at all?**

Because the composition of multiple matrices can be pre-calculated by matrix multiplication.

E.g., if we are going to translate one thousand vectors `v` of our car chassis with matrix `T` and then rotate with matrix `R`, instead of doing:

```
v2 = T * v

```

and then:

```
v3 = R * v2

```

for each vector, we can pre-calculate:

```
RT = R * T

```

and then do just one multiplication for every vertex:

```
v3 = RT * v

```

Even better: if we then want place the vertexes of tire and driving wheel relative to the car, we just multiply the previous matrix `RT` by the matrix relative to the car itself.

This naturally leads to maintaining a *stack* of matrices:

* calculate chassis matrix
* multiply by tire matrix (push)
* remove tire matrix (pop)
* multiply by driving wheel matrix (push)
* ...

This stack was explicitly present in the older deprecated immediate mode OpenGL APIs such as glPushMatrix, but with the advent of shaders this responsibility was passed more directly to the shader authors.

**How adding one dimension solves the problem**

Let's consider the case from 1D to 2D which is easier to visualize.

A matrix in 1D is just one number, and as we've seen in 3D it can't do a translation, only a scaling.

But if we add the extra dimension as we get:

```
| 1 dx | * |x|  = | x + dx * y |
| 0  1 |   |y|    | y          |

```

Now, since we added this extra dimension ourselves, we are free to choose a fixed value for `y` that suites our needs, so we choose `y == 1` to get:

```
| x + dx |
| 1      |

```

And finally, if we forget about this new extra dimension, we get:

```
x + dx

```

as we wanted.

This 2D transformation is so important that it has a name: shear transformation.

It is cool to visualize this transformation:

Image source.

Note how every horizontal line (fixed `y`) is just translated (larger `y` being translated more).

We just happened to take the line `y = 1` as our new 1D line, and translate it with a 2D matrix.

Things are analogous in 3D, with 4D shear matrices of the form:

```
| 1 0 0 dx |   | x |   | x + dx |
| 0 1 0 dy | * | y | = | y + dy |
| 0 0 1 dz |   | z |   | z + dz |
| 0 0 0  1 |   | 1 |   |      1 |

```

And our old 3D rotations / scaling are now of form:

```
| a b c 0 |
| d e f 0 |
| g h i 0 |
| 0 0 0 1 |

```

This Jamie King video tutorial is also worth watching.

**Affine space**

Affine space is the space generated by all our 3D linear transformations (matrix multiplications) together with the 4D shear (3D translations).

If we multiply a shear matrix and a 3D linear transformation, we always get something of the form:

```
| a b c dx |
| d e f dy |
| g h i dz |
| 0 0 0  1 |

```

This is the most general possible affine transformation, which does 3D rotation / scaling and translation.

One important property is that if we multiply 2 affine matrices:

```
| a b c dx |   | a2 b2 c2 dx2 |
| d e f dy | * | d2 e2 f2 dy2 |
| g h i dz |   | g2 h2 i2 dz2 |
| 0 0 0  1 |   |  0  0  0   1 |

```

we *always* get another affine matrix of form:

```
| a3 b3 c3 (dx + dx2) |
| d3 e3 f3 (dy + dy2) |
| g3 h3 i3 (dz + dz2) |
|  0  0  0          1 |

```

Mathematicians call this property *closure*, and is required to define a space.

For us, it means that we can keep doing matrix multiplications to pre-calculate final transformations happily, which is why use used matrices in the first place, without ever getting more general 4D linear transformations which are not affine.

**Frustum projection**

But wait, there is one more important transformation that we do all the time: `glFrustum`, which makes an object 2x further, appear 2x smaller.

First get some intuition about `glOrtho` vs `glFrustum` at: https://stackoverflow.com/questions/2571402/explain-the-usage-of-glortho/36046924#36046924

As a quick reminder, a projection is the act of taking 3D points and plotting them on the 2D camera plane, possibly taking into account perspective if we want to be realistic. This is the key step to translate between the 3D world of vertex shaders and the 2D world of fragment shaders: https://stackoverflow.com/questions/17789575/what-are-shaders-in-opengl-and-what-do-we-need-them-for/36211337#36211337

`glOrtho` can be done just with translations + scaling , but how can we implement `glFrustum` with matrices?

Suppose that:

* our eye is at the origin, looking at -z
* the screen (near plane) is at `z = -1` that is a square of length 2
* the far plane of the frustum is at `z = -2`

If only we allowed more general 4-vectors of type:

```
(x, y, z, w)

```

with `w != 0`, and in addition we identify every `(x, y, z, w)` with `(x/w, y/w, z/w, 1)`, then a frustum transformation with the matrix would be:

```
| 1 0  0 0 |   | x |   |  x |               | x / -z |
| 0 1  0 0 | * | y | = |  y | identified to | y / -z |
| 0 0  1 0 |   | z |   |  z |               |     -1 |
| 0 0 -1 0 |   | w |   | -z |               |      1 |

```

If we throw away:

* `z` because projection means to take a 3D point and place it in a 2D plane
* `w` because it is just a mathematical calculation artifact we invented

we get:

* `x_proj = x / -z`
* `y_proj = y / -z`

which is exactly what we wanted! We can verify that for some values, e.g.:

* if `z == -1`, exactly on the plane we're projecting to, `x_proj == x` and `y_proj == y`.
* if `z == -2`, then `x_proj = x/2`: objects are half size.

Note how the `glFrustum` transform is not of affine form: it cannot be implemented just with rotations and translations.

The mathematical "trickery" of adding the `w` and dividing by it is called homogeneous coordinates

Image source.

Related:
> 21 votes

# Answer
To succinctly answer the "why" question, it's because a 4x4 matrix can describe rotation, translation, and scaling operations all at once. Being able to describe any of these in a consistent manner simplifies a lot of things.

Different kinds of transformations can be more simply represented with a different mathematical operations. As you note, translation can be done just by adding. Uniform scaling by multiplying by a scalar. But an appropriately crafted 4x4 matrix can do anything. So using 4x4's consistently makes code and interfaces much simpler. You pay some complexity in understanding these 4x4's, but then lots of things get easier and faster because of it.
> 8 votes

# Answer
If all you are ever going to do is move along a single axis and never apply any other transformation then what you are suggesting is fine.

The real power of using a matrix is that you can easily concatenate a series of complex operations together, and apply the same series of operations to multiple objects.

Most cases aren't that simple and if you rotate you object first, and want to transform along its local axes instead of the world axes you'll find you can't simply add 10 to one of the numbers and have it work out correctly.
> 7 votes

# Answer
the reason to use a 4x4 matrix is so that the operation is a linear transformation. this is an example of homogeneous coordinates. The same thing is done in the 2d case (using a 3x3 matrix). The reason for using homogeneous coordinates is so that all 3 geometric tansformations can be done using one operation; otherwise one would need to do a 3x3 matrix multiply and a 3x3 matrix addition (for the translation). this link from cegprakash is useful.
> 4 votes

# Answer
See this video to understand the concepts of model, view and projection.

4x4 matrices are not just used for translating a 3D object. But also for various other purposes.

See this to understand how the vertices in the world are represented as 4D Matrices and how they are transformed.
> 1 votes

---
Tags: opengl, 3d, matrix
---


# Question
Title: How can I create an "afterimage" effect like this one?
How can I make an effect like this? With a particle system?

# Answer
> 5 votes
* Create a new particle system
* In the general settings:
    + "Start Lifetime" reduce a lot. The lower, the lower the length of the particle trail. In my example I am using 0.2.
    + "Start Speed" to 0, so the particles don't move from where they were created.
    + "Simulation Space" to "World" so the particles don't move when the parent moves
* "Emission":
    + Controls the number of after-images in the trail. In my example I increased it to 100. Should be at least `5 / StartLifetime` to avoid flickering.
* "Shape"
    + Uncheck this module, so all particles are spawned at exactly the position of the particle system
* In "Color over Lifetime":
    + set the gradient to fade from 255 alpha to 0 alpha so the trail-sprites fade out over time
* In Renderer
    + Create a new material with the shader "Particles/Alpha Blended"
    + Set the desired sprite as the sprite of that material
    + Assign that material to the Renderer
* Optional: Adjust start lifetime and emission amount to taste to control length and density of the trail.

Result when you move the object:

# Answer
> 2 votes
You can achieve this sort of effect pretty easily. You don't have to use a particle system to do so, but it can work pretty well. The structure is:

* You want a system that emits a single stationary particle (zero velocity) at a fixed interval.
* Configure the particle so that it decays over whatever period of time you want (this will be the time it takes each afterimage to "fade out"), and is spawned with whatever the current animation frame is.
* Tie the decay of the particle to it's opacity, so it gets more transparent as it approaches the end of its lifetime.

---
Tags: unity, c#, particles, graphic-effects
---