# Question
Title: How do i instantiate a particle system on gameObject destroy?
I have this damage script and I want it to instantiate a particle system...a death effect on enemy destroy. How do i add that to this script, please?

```
using UnityEngine;
using System.Collections;
using UltraReal.Utilities;
using UltraReal.WeaponSystem;

public class BasicDamage : UltraRealDamageBase
{

    /// <summary>
    /// Reference to a damage sound effect
    /// </summary>
    [SerializeField]
    protected AudioClip _damagedSound = null;

    /// <summary>
    /// Reference to a death sound effect
    /// </summary>
    [SerializeField]
    protected AudioClip _deathSound = null;

    /// <summary>
    /// Reference to Audio Source. If none is provide, it will try to get the one on the game object.
    /// </summary>
    [SerializeField]
    protected AudioSource _audioSource = null;

    /// <summary>
    /// Overriden OnStart method from UltraRealDamageBase.
    /// </summary>
    protected override void OnStart()
    {
        base.OnStart();

        _audioSource = GetComponent<AudioSource>();
    }

    /// <summary>
    /// Overriden OnDeath method from UltraRealDamageBase.
    /// </summary>
    protected override void OnDeath()
    {
        base.OnDeath();

        if (_audioSource != null && _damagedSound != null)
            _audioSource.PlayOneShot(_deathSound);

        Destroy(gameObject);
    }

    /// <summary>
    /// Overriden OnDamaged method from UltraRealDamageBase.
    /// </summary>
    protected override void OnDamaged(float damage)
    {
        base.OnDamaged(damage);

        if (_audioSource != null && _damagedSound != null)
            _audioSource.PlayOneShot(_damagedSound);
    }
}

```

# Answer
> 1 votes
Add the `ParticleSystem` that you want to play to your script, just like you did for the `AudioClip`s. Then you could use something like this in the `OnDeath` method to instantiate it and play it once:

```
protected void PlayEffectOnce(ParticleSystem prefab, Vector3 position) {
    if (prefab == null) { return null; }
    ParticleSystem ps = Instantiate(prefab, position, Quaternion.identity) as ParticleSystem;
    Destroy(ps.gameObject, ps.startLifeTime);
}

```

---
Tags: unity, c#, 3d
---


# Question
Title: Synchronization between server's value and the one showed in a stat bar (health, stamina, mana...)
I am trying to implement a stamina system for my mmo. In few words, I computed everything on the server that then notifies the client. On the client I have a stamina bar that shows the stamina amount. My problem is that the values on the server and the one on the client often go out of synch because of network delay and that causes odd behaviours on the bar.

EDIT 2:

There are things that can affect the regeneration/depletion of a stat. My architecture is server authoritative and the server is in charge of handling the flat changes and the changes in the delta amount per second, that's a constraint.

END EDIT 2.

The communication scheme is between Client (C) and server (S) is the following:

C: me want use stamina

S: ok your stamina is X descreasing at Y/s

C: set stamina to X and animate the bar accordingly to Y/s

every 1 sec after this initial handshake

S: this is your stamina X\_i and it is decreasing at Y\_i/s

C: use information to animate the stamina bar coherently yet in a way that resembles linearity

as soon as S knows stamina is 0

S: your stamina is 0

C: set stamina bar to 0

Due to loss of synch, the value 0 may appear when the real value is not really 0. The client holds a float amount that is decreased/increased and ceiled to int at every frame to be displayed.

Options I have already tried:

-Whenever the server updates you, force its value: causes jumpy behaviours and doesn't achieve fake linearity

-Whenever the server updates you, calculate the client regen/loss factor as (server amount + delta amount per second) - client amount. Causes the most overshots (client value going to zero when it should not be 0).

-Whenever the server updates you and you find a delta between the server value and the client value, run a coroutine that adds/subtracts over two or three frames that delta to the client value. Still too jumpy and sometimes the error is so big it makes the bar make huge leaps.

Language c#, network library photon, engine unity.

EDIT 1:

My partial solution has been:

The server sends you an update including a duration and a target value predicted for when that duration has elapsed. The client at each update starts a tweener (DOTween library) from it's current value to the target value over that duration. I had the issue that sometimes the client would display 0 when it wasn't the case on the server due to network delay that didn't stop the client in time, and **if you reach 0 in my case I have to perform a cooldown wait** that wasn't happening being the command to start the cooldown issued by the server. So what I've done has been to make the server accept the 0 from client when it was the case. It seems to work but on changes on the delta value per second, sometimes it might slow down or get quicker in a way that it is noticeable, sometimes.

END EDIT 1.

EDIT 3:

Additional tweak that makes it look a little better.

When the event that starts/stops consuming the stat occurs in the client, I stop the stat bar and wait for server update.

END EDIT 3.

# Answer
What I suggest you do is to simulate the change client-side, using the same calculation on server-side, and send request to the server at the same time, using a timestamp to know what value it is. Then, when the server answers, with its own, checked value, compare it to the value you had computed **at that timestamp**, and if it is incorrect, change it.

You can perform the check only when the stamina has stopped being used, to avoid having multiple check requests, and to avoid to have to store their values.

== EDIT ==

You're effectively right about the stamina being in constant use. There is indeed no point in making the checks when it stops going down/up, so you can simply make checks something like every 30-40-50 ms, depending on the rate you send packets to server.

== END EDIT ==

As it is very improbable that the results are different (if you use the same calculation...), there would be therefore no jumpy behaviours, except if someone modifies its own client (but then it's his fault if he makes everything bug out :D)
> 1 votes

---
Tags: unity, c#, mmo, client-server, photon
---


# Question
Title: Calculating angle to aim at target results in over/under aim depending on whether target is below/above
I'm calculating the angle (in radians, ranges -3.141 to 3.141 for yaw and -1.343 to 1.396 for pitch) to aim at in order to aim at a target position. The data I have is my local world camera position, and the world target position. The result should be the angle that needs to be set in order to aim precisely at the target.

This is a fairly simple calculation (even though I'm terrible at math) and it works without issue.. but it has a quirk when I'm in third person.

When I'm in first person, the "local world camera position" is effectively my player's eye position. When I'm in third person the "local world camera position" is effectively offset backwards and above from my player's eye position.

The quirk (actually a pretty big flaw right now) is that when the target position is elevated higher than my local world camera position, the result of my calculation results in an angle that over-shoots/over-aims the target. Inversely, when the target position is elevated lower than my local world camera position, the result of my calculation results in an angle that under-shoots/under-aims the target.

I've drawn this very bad sketch to try and explain my issue, for clarity my drawing is 2D and drawn from the side, but my application is 3D: https://i.stack.imgur.com/lgjLk.png

And to clear something up, the further my angle is pitched downwards, the closer my camera position will be to the top of my local player and the further my angle is pitched upwards, the closer my camera will be to the bottom of my local player. If you imagine playing a third person game you should understand what I mean.

Here's the calculation I'm doing:

`Vector3 vForwardVector = vTargetPosition - vCameraPosition;
Vector2 vCalculatedAngle = Vector2(atan2(vForwardVector.x, vForwardVector.z), atan2(vForwardVector.y, sqrt(vForwardVector.x * vForwardVector.x + vForwardVector.z * vForwardVector.z)));`

I'm not sure what other detail I can provide.. hoping someone can point out an obvious mistake? Happy to provide any extra information!

Thank you everyone.

# Answer
> 1 votes
Sounds like you just always need to use the players eye position instead of the camera position for the calculation.

---
Tags: c++, mathematics, angles, third-person-view
---


# Question
Title: Unity 5.3 Webgl Build not working on Google Chrome
I am testing a game I build it on webgl and opened it on Google Chrome but nothing showed up just a screen with unity logo and no loading screen, then I tried on Firefox and it ran smoothly without any issues I am using unity 5.3.3f1 and Chrome 48 what can be the issue? I am really looking forward for your replies, I searched on internet but in vain and not too many people answered this question on internet.

# Answer
> 2 votes
Web Gl does not work in Chrome running from file system.

I suggest one of two solutions:

1. Run with Firefox for quick testing of a build.
2. Upload to a server if you have it or to your Public-folder on dropbox. Right click on the index file, copy the URL and then test in different browsers.

# Answer
> 2 votes
I'm not sure but I think that Chrome won't let you execute webgl content from file for security reasons. If you chose build and run unity should start a local server with that it should work. Also there had been a problem with Chrome and webgl but I think they've fixed that by now.

# Answer
> 1 votes
Make sure you're not using the default "Arial" font anywhere. WebGL does not support it. You need to import a font and then set all text resources to use it.

When I failed to do so, I got a grey screen that never finished loading, it would just hang.

---
Tags: unity
---


# Question
Title: My mesh has holes in it. How do I make those invisible faces show?
I have a mesh. A perfectly normal mesh, without any artefacts at all.

However, when I import it into Unity, there are holes in it.

After going through my UV mapping and normals, they are all mapped, have no faces with the normals going the wrong way (facing inwards) and have non-transparent textures over each mapped UV face.

Oddly enough, this mesh hasn't been split, despite its poly count and is one whole object, but yet - It has missing polygons. Is there any way to get Unity to recognise these faces?

Also, it is worth noting that these holes happen to be **all** the tris faces on this model, and are all (mostly) along the UV seames.

# Question

How do I make the invisible faces show? What's going on?

# Answer
> -1 votes
Could you post the import settings of the .fbx in unity?

You could try changing the Normals option or the Optimize Mesh and see if it helps.

# Answer
> -3 votes
In edit mode in Blender, select all faces and press `Shift + N` or `Ctrl + N`. I don't remember. Maybe this will be helpful.

---
Tags: unity, rendering, mesh
---


title: 2D Array Map Java Lost In Map

text:
# Question
Title: 2D Array Map Java Lost In Map
I can move within my 2d array. But I'm not sure if my right or left and up and down is messed up, or what but for some reason the movements don't correspond to anything I'm familiar with on the map(like if I move into a wall, and type the opposite direction, there is a wall on both sides of me, you may have to just try this little game out yourself and see).Also sometimes, when it should output that you are on an empty tile, or something, it just goes straight to my `if else` instead of saying one of my `if` statements(Which I'm sure is my blunder). Is it just my directions within the 2D array that are messed up or something more? Thank you again for your time I am just self learning java and having a great time. TLDR: I just want my movements (up, down,left,and right) to correspond to my 2d array map.

```
    package login;

import java.util.Scanner;

public class Form {
static String dir = "";
static int player;
static int chest;
static int monster;
static int key;
static int tile;
static int wall;
static Scanner scan = new Scanner(System.in);

static int[][] map = new int[][]{
    {1,1,1,1,1,1,1,1,1,1},
    {1,2,2,2,3,4,2,2,4,1},
    {1,3,2,2,2,2,2,2,2,1},
    {1,2,5,4,2,2,2,5,2,1},
    {1,2,3,3,0,5,5,3,2,1},
    {1,2,2,2,2,2,2,2,2,1},
    {1,3,3,5,2,2,3,2,2,1},
    {1,4,4,2,2,2,2,2,2,1},
    {1,3,5,2,2,2,3,4,5,1},
    {1,1,1,1,1,1,1,1,1,1}};

    static int x= map[5][0];
    static int y = map[0][5];
    static int playerPos = map[x][y];
    static int life = 3;

static boolean isInGame;

public static void main(String[] args){
int isPlaying;
    System.out.println("Press 1 to play..anything else to exit!");
    isPlaying = scan.nextInt();
    if(isPlaying == 1){
    isInGame = true;
    enterGame();

    }
    else{
        System.out.println("You missed out on a good game...");
        System.exit(1);
    }
}

public static void enterGame(){
    System.out.println("Type, up, down, left, or right, to move.");
    while(isInGame == true){
        move();

    }

}

public static void move(){
    dir = scan.nextLine();
    switch (dir){
    case "up":
        x = x+1;
        playerPos = map[x][y];
        map();
        break;
    case "down":
        x = x-1;

        playerPos = map[x][y];
        map();
        break;
    case "left":
        y = y-1;

        playerPos = map[x][y];
        map();
        break;
    case "right":
        y = y+1;

        map();
        break;

    }
}

public static void map(){
    wall = 1;
    tile = 2;
    monster = 3;
    chest = 4;
    key = 5;
    player = 0;

    if(playerPos == wall){
        System.out.println("Thats a wall. Can't move there.");
    }
    if(playerPos == tile){
        System.out.println("You move to a free tile");
    }
    if(playerPos == monster){
        monsterEncounter();
    }
    if(playerPos == chest){
        System.out.println("Woah a chest!");
    }
    if(playerPos == key){
        System.out.println("Woah a key!");
    }
    else if(playerPos != wall){
        System.out.println("Keep going.");
    }
}
public static void monsterEncounter(){
    if(life > 0){
    if( x == 3 || y == 3){
        System.out.println("WOAH! A MONSTER! HE BEATS YOUR ASS.. -1 LIFES");
        life =- 1;
        System.out.println("You have: "+ life +" life left! Don't die..");
    }}else{
        System.out.println("You have: "+ life +"You encountered too many monsters. GAME OVER.");
        System.exit(1);
    }

}
}

```

# Answer
> 1 votes
Here it is working, I just messed with it until I got it. Hope this code helps someone. I also figured out how to change chests that had been opened, and keys that had been collected, into generic tile pieces. Cheers.

```
   package login;

import java.util.Scanner;

public class Form {
static String dir = "";
static int player;
static int chest;
static int monster;
static int key;
static int tile;
static int wall;
static int keysFound = 0;
static int chestsOpened = 0;
static int chestsLeft = 3;
static Scanner scan = new Scanner(System.in);

static int[][] map = new int[][]{
    {1,1,1,1,1,1,1,1,1,1},
    {1,2,2,2,2,4,2,2,5,1},
    {1,3,2,2,2,2,2,2,2,1},
    {1,2,5,4,2,2,2,5,2,1},
    {1,2,3,3,0,5,5,3,2,1},
    {1,2,2,2,2,2,2,2,2,1},
    {1,3,2,5,2,2,3,2,2,1},
    {1,4,4,2,2,2,2,2,2,1},
    {1,2,5,2,2,2,3,4,5,1},
    {1,1,1,1,1,1,1,1,1,1}};

    static int x= map[5][0];
    static int y = map[0][5];
    static int playerPos = map[x][y];
    static int life = 3;

static boolean isInGame;

public static void main(String[] args){
int isPlaying;
    System.out.println("Welcome to Michael's Mystical Maze.. You will need:\nOne peice of paper\nA pen\nYour wits\n");
    System.out.println("You must map the maze on paper, finding keys, avoiding monsters\nand open three chests to win!");
    System.out.println("Press 1 to play..anything else to exit!");
    isPlaying = scan.nextInt();
    if(isPlaying == 1){
    isInGame = true;
    enterGame();

    }
    else{
        System.out.println("You missed out on a good game...");
        System.exit(1);
    }
}

public static void enterGame(){
    System.out.println("Type, up, down, left, or right, to move.");
    while(isInGame == true){
        move();

    }

}

public static void move(){
    dir = scan.nextLine();
    switch (dir){
    case "up":
        x = x+1;
        playerPos = map[x][y];
        map();
        break;
    case "down":
        x = x-1;
        playerPos = map[x][y];
        map();
        break;
    case "left":
        y = y-1;
        playerPos = map[x][y];
        map();
        break;
    case "right":
        y = y+1;
        playerPos = map[x][y];
        map();
        break;

    }
}

public static void map(){
    wall = 1;
    tile = 2;
    monster = 3;
    chest = 4;
    key = 5;
    player = 0;

    System.out.println(playerPos);
    if(playerPos == wall){
        System.out.println("Thats a wall. Can't move there.");
    }
    if(playerPos == tile){
        System.out.println("You move to a free tile");
    }
    if(playerPos == monster){
        monsterEncounter();
    }
    if(playerPos == chest){
        openChest();
    }
    if(playerPos == key){
        findKey();
    }

}
public static void monsterEncounter(){
    if(life > 0){

        System.out.println("WOAH! A MONSTER! HE BEATS YOUR ASS.. -1 LIFES");
        life = life - 1;
        System.out.println("You have: "+ life +" life left! Don't die..");
    }else{
        System.out.println("You have:NO LIFE , You encountered too many monsters. GAME OVER.");
        System.exit(1);
    }

}
public static void findKey(){
    System.out.println("Woah a key!");
    keysFound += 1;
    map[x][y] = 2;
}
public static void openChest(){
    System.out.println("Woah a chest!");
    if(keysFound >= 1){
        chestsOpened += 1;
        int totalChestsFound = chestsLeft - chestsOpened;
        chestsLeft -= 1;
        System.out.println("You have opened a chest! You have "+ totalChestsFound + " chests to go!");
        map[x][y] = 2;
        keysFound -= 1;
    }
    if(chestsLeft == 0){
        System.out.println("YOU WON! GOOD GAME SIR, GOOD GAME.");
        System.exit(1);
    }
    else{
        System.out.println("No keys, no chests. Keep searching soldier.");
    }

}
}

```

---
Tags: java, maps
---


# Question
Title: Efficiently transforming a series of points into curves to be serialized
I’m working on a video game where I need to display a map (in 2D) of an actual big European city (Paris, London, Madrid… that kind of big) and the player, displayed as a simple dot on the map, can take different routes while following the street lines.

To do so I extract real data from OpenStreetMap.org. Thanks to it I have access to a ton of data and geographic information, and among them I have street visual settings given as series of coordinates (long/lat converted to X/Y points using the right projection). In OpenStreetMap a street is composed of a set of points so drawing a line between these points is enough to display streets.

However it represents a huge number of points to load which means a lot of time spent processing the data which means: not ideal. For example, a big city like Paris is composed of 65.000 street points. That is huge. In order to reduce this number and still being able to draw / follow street curves I’m thinking about using a graph only composed of points implied in street intersections alongside curve equations to describe the street display. This way a street composed of 2000 points would be not much bigger than one composed of 10 points in theory.

# Example

In this example my initial set is composed of 13 points (red crosses) to display a street. What I’m aiming to in this case is keeping only 4 points (intersections with other streets) and an actual “equation” (or something similar) between each couple of points in order to reduce the size on disk of the final map.

This is where I’m stuck. I suck at Math (and regret it every day). So I can’t figure what would be the best way to transform a series of points into a simple equation that would allow me to follow the actual street curve at runtime.

I don’t know how to do it… I’ve read things about Bezier curves, about Clothoids, Circular Arcs… but I don’t know where to start, what is the best solution here, how to convert my series of points using one of these techniques, or if it’s really the clever thing to do in order to reduce the size (in bytes) of the map…

# Answer
> 3 votes
Streets can be pretty funky, with plenty of twists and turns. This can make it hard - or impossible - to describe one by a function of the form \\$y = f(x)\\$, where \\$x\\$ and \\$y\\$ are Cartesian coordinates. Polar coordinates, too, will often fail, no matter where you choose the origin. Therefore, I think your best bet is to create a parametric curve \- that is, a relationship so that any point \\$(x,y)\\$ can be represented by functions of some parameter \\$t\\$:

$$(x,y) = (f(t), g(t))$$

When you're doing some sort of curve fitting like this, it's best to make \\$t\\$ proportional to the arc length \\$s\\$, which tells you where on the curve you are. You can then treat \\$t\\$ as the time it takes to move along the curve with some constant velocity (usually set to 1).

### Step 1: A good approximation

Let's say you have a series of ten points \\$\\{p\_1,p\_2,p\_3,p\_4,p\_5,p\_6,p\_7,p\_8,p\_9,p\_{10}\\}\\$ on your grid, each one with coordinates \\$p\_j=(x\_j,y\_j)\\$. You want to create a curve \\$P(t)\\$ that contains them all. The curve starts at \\$p\_1\\$, and goes from \\$p\_j\\$ to \\$p\_{(j+1)}\\$ until it reaches \\$p\_{10}\\$, where it stops.

We need to figure out the time at which a person traveling on the curve reaches the next point, i.e. how far apart two points are. If they're close enough together, then a linear approximation is enough. In pseudocode:

$$p\_1 = (x\_1,y\_1)$$ $$p\_2 = (x\_2,y\_2)$$ $$d\_x = x\_2 - x\_1$$ $$d\_y = y\_2 - y\_1$$ $$dist = \sqrt{d\_x^2+d\_y^2}$$

We do this for each two points. If \\$P(t\_1) = p\_1\\$, then \\$P(t\_2 - t\_1) = p\_2\\$, where \\$t\_2\\$ is the linear distance between \\$p\_1\\$ and \\$p\_2\\$. We can set \\$t\_1 = 0\\$, if we want, for the sake of simplicity - assuming \\$p\_1\\$ is one of the endpoints.

After we've done this for all the points, we have three sets of numbers:

$$\begin{align}T =& \\{t\_1,t\_2,t\_3,t\_4,t\_5,t\_6,t\_7,t\_8,t\_9,t\_{10}\\}\\ X =& \\{x\_1,x\_2,x\_3,x\_4,x\_5,x\_6,x\_7,x\_8,x\_9,x\_{10}\\} \\ Y =& \\{y\_1,y\_2,y\_3,y\_4,y\_5,y\_6,y\_7,y\_8,y\_9,y\_{10}\\}\end{align}$$

and so at \\$t=t\_j\\$, the curve is at point \\$p\_j(x\_j,y\_j)\\$. Now we can interpolate. You can construct two Lagrange polynomials1, one each for the \\$x\\$ and \\$y\\$ coordinates, each in terms of \\$t\\$. The formula is simple enough, although it's obviously harder to do by hand.

We now have a parametric curve that describes all the points.

But wait! That still requires a lot of coefficients, and we're trying to reduce that. So why did we even do this?

### Step 2: Remove some points.

Let's say we only want to use four points. That's reasonable. I'll pick the endpoints and two others: \\$\\{p\_1,p\_4,p\_7,p\_{10}\\}\\$. Now, we can do the same thing as before. In fact, we could do the same interpolation we did in Step 1, by just finding the linear distance. And that's fine if you have a curve that only deviates a little from a straight line during each segment. However, that's often not the case. By simply finding the shortest distance between \\$p\_4\\$ and \\$p\_7\\$, we'd think that the two are a lot closer together, making the curve a lot different.

Therefore, we take what we did from step one. We find the length between these two points based on our interpolated curve \\$P\\$ that uses all ten. This can be done by just finding the arc length. I'd recommend using numerical methods for this. We then have three sets:

$$\begin{align}T =& \\{t\_1',t\_4',t\_7',t\_{10}'\\}\\ X =& \\{x\_1,x\_4,x\_7,x\_{10}\\} \\ Y =& \\{y\_1,y\_4,y\_7,y\_{10}\\}\end{align}$$

I use the primes to show that the times we've found are different from what we did in step one. They may be more accurate. Now we do the same sort of interpolation, just with four points.

We now have a parametric equation for the curve, using only four points. It's much less accurate than the first equation, but it uses much less data, and it guarantees that the curve will still pass through these four points (that's an issue with polynomial regression \- only rarely will a best-fit curve go through any of the points).

Now, we *could* have skipped Step 1. I know, maybe you're disappointed. As I said before, we could just have used the linear distances between the four points. But that misses most of the finer details of the curve, and if you're shortening a curve from, say, 20 points to 6 points, skipping the first interpolation could really be costly.

---

1 A Lagrange polynomial (not parameterized) is of the form

$$L(x)=\sum\_{i=1}^ny\_ik\_i(x)$$

where

$$k\_i(x)=\prod\_{m=0,m\neq i}^n\frac{x-x\_m}{x\_i-x\_m}$$

Here's the reasoning behind Lagrange polynomials (in this case, there is no parameterization - \\$y\\$ is directly a function of \\$x\\$). You have \\$n\\$ points with coordinates \\$\\{(x\_1,y\_1),(x\_2,y\_2), ... ,(x\_n,y\_n)\\}\\$. You want to come up with a non-parameterized function \\$y = f(x)\\$. The simplest way to do that is to come up with a function with \\$n\\$ terms. At each point \\$p\_j\\$, i.e. when \\$x = x\_j\\$, all but one term - let's call it the *j*th term - will come to zero, and the remaining term will be equal to \\$y\_j\\$. From there, it's simple to construct the second expression for any point \\$p\_l\\$, and you simply add up \\$n\\$ terms, each corresponding to a different \\$p\_l\\$, \\$x\_l\\$ and \\$y\_l\\$. This gives you the Lagrange polynomial for your set of points.

In your application of Lagrange polynomials to streets, we've done the same thing - just parametrically.

---
Tags: mathematics, maps, curves
---


# Question
Title: How do I rotate, inverting flipping one local axis direction of a game object transform using C#?
How do I invert my arrow that is pointing Z forward to point backwards? The arrow has it own rotation and position. The arrow is also linked to it´s parent rotation and moving position in space. I wish to rotate flip direction of my arrow conserving the direction of it, so that it points in the opposite direction of one local axis (Z for example). Without losing the parent or it´s own direction in space.

```
transform.localRotation = Quaternion.... Z * -1

```

Is there more than one way to do this?

Probably by rotating in Y 180°? I wish not to scale Y to -1.

```
transform.rotation = new Quaternion.AngleAxis(Vector3.up, 180f);

```

# Answer
> 0 votes
```
// rotate following parent. localEulerAngles CAN CAUSE CRAZY ROTATION PROBLEMS
transform.localEulerAngles = new Vector3(0f, 180f, 0f);

```

Making a rotation in Y will make the arrow to pointing back. If is necessary make the arrow a child object of the Game Object transform that you are rotating. In this way, this line of code will not affect the direction and the final rotation will be opposite to the Game Object parent.

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


title: When to use LOD and when not to?

text:
# Question
Title: When to use LOD and when not to?
I have a simple question: are there any cases where game LOD models don't need to be created? Obviously you need LODs for landscapes, large props, characters, vehicles etc. But what about small indoor props which are unlikely to be seen from large distances? I understand that it depends on genre and other factors like the distance to the camera, but still, is there any common standard regarding when LODs need to be made?

# Answer
Make (and use) them when you'll see a benefit from them. Don't when you won't.

As you said, this can vary widely between games, but it's about as general a statement as you can make. In some cases, as you said, you won't need LODs for clutter geometry because you can simply remove it from the scene. But maybe in other cases you have an engine where it's quicker (at runtime) to drop to a lower LOD than remove the mesh entirely from the world, so you might want to do that instead. Or perhaps it's alternatively faster to swap LODs than put the mesh *back* in the world, and you have a game with sniper rifle scopes where the player might need to see far-off distances very suddenly.

It just depends on the needs of your project.
> 2 votes

---
Tags: 3d, graphics, 3d-meshes, level-of-detail
---


# Question
Title: Turn a single player game into multiplayer game
hobbyist / indie dev here and I was wondering about network programming and making a game capable of multiplayer.

So basically I just haven't touched on network programming yet and really don't know much and have very little experience with coding multiplayer games. So with that in mind I have a project I want to make and I have all the key points pretty much on paper and a clear vision of what I want to make, I am also going to end up recruiting help (for such things as multiplayer capability more than likely as well as other aspects) since this is outside the scope of my ability to do alone.

I do not plan on having this game hosted by a central server I control and am leaning heavily on the side off a type of p2p connection like minecraft / starbound / terraria (I think those are p2p anyway) with that in mind is it extremely important that I code / build the game with multiplayer from the ground up or might I be able to work on other systems first such as game mechanics and the procedural world creation first and might it be easy to basically create a multiplayer system ontop of the game?

I guess the question is kind of broad but what it boils down to is might it be critical to focus on the networking / multiplayer first or is it a safe and(or) common practice to implement it later in development?

# Answer
> 2 votes
First, you should read through Gaffer on Games's article *What every programmer needs to know about game networking*. It covers all the important parts on typical networking architectures and their pros and cons. There's also some decent answers here: Limitations of p2p multiplayer games vs client-server. But basically you have two architectural choices: **P2P or client/server**1. It's an important decision since it has huge consequences, like how well you can handle cheating, or compensate for latency, all of which depend on your game; there is no "right" choice.

The reason why you need to be aware of all this is that it also affects your choice on whether to build your game with networking in mind from the start, or build it in later:

* **P2P is much easier to build later** than client/server, especially if the game's architecture was not designed with clear separation of concerns from the start, like mixing game logic with rendering. As someone who's added client/server networking into such a game, I can attest to it being a huge amount of work.
* **Client/server is harder to work with**, especially if you are a small team. Any game feature might involve multiple decoupled systems, and additional decisions on how it will be handled: by the client, by the server, by both, and how. For programmers not familiar with this, it can slow down progress.
* However, **for the most demanding networked games, client/server is pretty much mandatory**, given the severe limitations of P2P.

This is all covered in the Gaffer on Games article I linked at the start. Here's the relevant real-life experience from id's Doom/Quake games:

* Doom came with P2P networking, which worked well on LANs but was unplayable for the typical online connections at the time (14.4Kbps modems).
* Quake was written as a pure client/server architecture from the start, and networking was trivial. Online multiplayer was playable but typical clients experienced so much latency that they had to suffer a degraded experience
* QuakeWorld, which included client-side prediction, meant that players with high latency can still play with a decent experience, and this model became the industry standard since

So what this all boils down to is four choices, ranked from easy to hard:

* Write game with P2P networking from the start
* Write game first, add P2P networking later
* Write game with client/server networking from the start
* Write game first, add client/server networking later

And with the following considerations:

* P2P is easier most of the time2
* Client/server is mandatory for online networking for certain genres (action, MMO)
* Writing with networking from the start is easier, and much easier if you choose to do client/server
* But keep in mind the caveat that game development is risky, so there's an advantage to making a game as fast as possible to test its viability

1Note that when I say "client/server" I'm assuming you also do client-side prediction. Pure client/server, i.e. dumb clients, isn't too hard. Most of the difficulty comes from client-side prediction and how you reconcile client and server discrepancies.

2P2P can be harder if you want to handle things that it's not well-suited for, like drop-in/drop-out. But the "classical" P2P lockstep model as used by Doom is dead-easy, it simply requires sharing state across all the players.

---
Tags: multiplayer, software-engineering
---


# Question
Title: Does interfacing not work as well when it comes to games development?
I'm currently at the start of a project, and I'm following the wisdoms of my day-to-day career as a C# developer for large web applications.

Currently I have set up a bunch of interfaces. Notable of these are `IActor`, `IHuman`, `ISelectable`, `IUIAction` & `IHealth`.

I also have a `Person` class. `Person` implements `IHuman` (which implements `IActor`), `ISelectable` and `IHealth` and also inherits from `MonoBehaviour`.

`ISelectable` has a property of `IEnumerable<IUIAction> Actions`. Actions have a property of `Action click`. Im sure you can see where I am going with this...

The intended goal is that if a class inheriting from `MonoBehaviour` (`person` in this case) implements `ISelectable` and is attached to a `GameObject` that is clicked, a list of buttons representing `ISelectable.Actions` is displayed on the screen. If a class implements `IHealth`, a healthbar will be displayed on the screen etc etc...

Now, the problem I see is I'm going to end up with **huge** classes. The classes are going to need properties for their health, theyre going to need properties for their actions, theyre going to need properties for what the UI panels title should be when selected, and anything else that comes up as development progresses... My other thought is to remove the interfaces like `IHealth` from the class itself and have them be their own class, such that `IHealth` will only mean a class has a property that is of the class `Health` and `Health` has all the properties relating to an objects health levels... but this removes authority from the class as to what control it has over its health.

Whats the industry standard for this sort of thing, and how can I implement it effectively in my game?

# Answer
> 9 votes
Unity emphasizes a philosophy called Composition Over Inheritance.

The idea is that rather than thinking of what a particular entity "is":

> A soldier is a unit which is selectable and which is damageable.

You think of the set of behaviours/features it "has":

> A soldier has a selection behaviour and a taking-damage behaviour

So then, as you suggest in the question, you can break these responsibilities off into their own `MonoBehaviour` components:

* **Selectable** (watch out for naming conflicts with `UnityEngine.UI.Selectable`) can respond to click events and hold information needed to draw a selection highlight.
* **Damageable** can track the current health, resistances, and handle firing off low-health state change events or destruction animations.

etc.

Your "soldier" might not exist as a class anywhere in code - it's just a particular combination of components and parameter values that gives the set of behaviours you want, ie. an entity with both Selectable and Damageable components attached (among others).

This move from defining each entity in code to doing it in data gives us a number of outcomes that are useful in game development:

* Non-programmers on the team can take a more active role in developing game behaviour. If your coders provide a good set of building-block components, the level designers can go to town experimenting & combining them in new ways, without waiting on a coder to write a class that glues-together all the bits they need in a new standalone class.
* Occasionally you'll get new behaviour "for free" out of this combinatoric play. For example, take an enemy and remove the Damageable component - boom, now you have invulnerable enemies, without a coder creating a special mode or flag. ;)
* We can create and modify these compound entities on the fly while the game is running, without recompiling code or relying on edit-and-continue functionality.
* This style helps encourage small modular components, each easy to understand and modify on their own, rather than massive sprawling classes with many responsibilities as you describe - a common pitfall in game development, with player classes especially!
* A more modular, data-driven architecture tends to have fewer bottlenecks for exclusive checkouts & merging when multiple developers are collaborating on a cluster of features.
* This pattern can also make it easier to develop tools like level editors or support user generated content, since all the game entities are just data files that can be modified without code changes.

That's not to say you can't or shouldn't use interfaces - they're still a great tool to have in your toolbox, especially when you have some kind of well-defined need in your game and multiple ways you might want to serve that need.

For example, maybe your base AI movement logic knows it wants to move into firing range for whatever weapon it's using - but that weapon might vary from one unit archetype to another. You could introduce an `IAttackBehaviour` interface exposing methods to select a target, locate a good attack position for the movement behaviour to reach, and to execute an attack. Then you could implement this in concrete types like`MeleeAttackBehaviour`, `SniperAttackBehaviour`, `GrenadierAttackBehaviour`, etc. Your movement behaviour just needs to know it "has" an IAttackBehaviour attached, but doesn't need to implement these details itself for every archetype flavour. This allows AI designers to mix & match components as they need, while maintaining a clear contract for how the movement & attack behaviours communicate.

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


title: How to enable & disable this option?

text:
# Question
Title: How to enable & disable this option?
How to enable and disable this option only, not the whole object with C# ?

# Answer
> 4 votes
If I understand correctly you're trying to achieve is to disable just a component and not the whole gameobject.

You can get any component (on the current object) using

```
var component = GetComponent<Type>();

```

Where `Type` is the component you want to get. Examples in your case:

```
var camera = GetComponent<Camera>();
var canvas = GetComponent<Canvas>();

```

Here `GetComponent` is called on the current gameObject where your script is, but you can call it on another gameObject, it's a public function.

Then all components can be enabled/disabled:

```
component.enabled = false; // Disable
component.enabled = true; // Enable

// Examples
camera.enabled = true;
canvas.enabled = false;

```

Finally, notice that the checkbox only appears in the inspector next to a component if some methods are found by Unity (usually: `Start` and `Update`).

---
Tags: unity
---


title: GLES2 GL_BGR undeclared?

text:
# Question
Title: GLES2 GL_BGR undeclared?
I tried to bind a bitmap texture. This bitmap is BGR format, and I'm trying to use `glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data)`, but during compile, error: 'GL\_BGR' undeclared appears.

I checked `<GLES2/gl2.h>` and `<GLES2/gl2ext.h>`, but there isn't any `GL_BGR` . Is there any way to upload BGR format?

# Answer
Unfortunately OpenGL ES2.0 does not support BGR texture formats in glTexImage2D.

> *format* determines the composition of each element in data. It can assume one of these symbolic values:
>
> * GL\_ALPHA
> * GL\_RGB
> * GL\_RGBA
> * GL\_LUMINANCE
> * GL\_LUMINANCE\_ALPHA

Source: https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glTexImage2D.xml
> 1 votes

---
Tags: opengl-es2
---


# Question
Title: How to make sure spinning objects hit a target with the right end?
I'm working on a throwing knife type weapon where a player free aims and then throws a knife. The knife spins through the air and on collision stops spinning and parents itself to the object it collided with. The spinning is handled via animation while the path of the knife is handled by physics.

One problem I'm facing is how to make sure that when the knife collides with an enemy that the knife will be facing towards them. At the moment what is happening sometimes is that the knife embeds into an enemy handle first. Which is obviously unrealistic. At the same time, I think it would be quite unreasonable for the knife to only "hit" the enemy if it collided blade first, since the rate at which the knife spins is beyond the player's control.

I've been watching a lot of slow killcam footage of similar weapons and each time the weapon is thrown it spins through the air and magically always ends up with the blade pointing at its target. For a game where the throwing distance will be consistent, this is quite straight forward to do. But I'm not quite sure how to predict this since there are many unpredictable factors involved eg. direction of the knife, rotation of the knife, position of the enemy, distance from enemy etc. If possible, I would prefer not to have to use complex prediction logic since the game will be for fairly low end devices. Is there a "smoke and mirrors" way to solve this?

Example: https://youtu.be/0fav8lFpBko?t=42s

# Answer
## Fake it

Look at the video you linked, watch it in slow motion... eh, what is that? The camera jumps at the end, and the knife is already in the helmet of the target.

Just fake it. Once the distance from the knife to the target is small, jump cut to the knife magically in the target.

Edit: you can check if it will hit a target using the convoluted prediction, and then pretend it did hit blade first, then show an animation where the target does not move and the knife kills it.

---

## The convoluted prediction

> since the rate at which the knife spins is beyond the player's control.

That is right. It is beyond player's control. However, not beyond your control...

If you can compute the distance the knife has to travel, you can make the rotating rate such that the knife will hit blade first.

Now, it does not make sense to make this prediction in mid-flight, because the knife would have to adjust if an obstacle gets in the way. Therefore, you would do it when you throw.

The fact that you have to follow a parabolic path to hit test makes it more complicated than a simple ray cast. I would suggest getting the equation for the parabolic motion that correspond to the knife throw, and evaluated it at given intervals.

It is also possible to find the distance of obstacles to the parabola, by finding the closest point in the parabola to the position of the obstacle, and then do a collision check with that point.

Once you know how much has the knife has to travel, you can divide it into an integer number of rotations, so that it will hit blade first. Edit: or an integer 0.5 depending on how you throw.

Of course, the obstacles would have moved by the moment when the knife gets there…

---

## Be realistic

You will not make the knife hit blade first 100% of the times, in particular with moving targets. Just embrace that, a throwing knife is not a reliable weapon. So have the alternative of having it bounce when it hits handle first. You can check if it hit handle first by checking its orientation and comparing it with the direction to the collision point.
> 35 votes

# Answer
If you know ahead of time where the knife will land - like in those kill cam footage, which is most definitely produced after-the-fact - just calculate the right rotation speed based on flight distance and number of rotations desired. Throwing knives leave the thrower hilt-first, so it needs to rotate N+0.5 full rotations1, where N is usually at least 1 but could be more based on the thrower's skill level or how cool you want it to look: more spins = more cool.

If you don't, it's ok to cheat by fixing the rotation on hit, and perhaps hide it with a blood splatter. Like a magician, if you do it quick enough the player is not going to notice.

Of course, none of this is realistic. In real life, knife throwing is really hard and requires a lot of practice if you want the knife to land blade-first. The thrower needs to be fully aware of the distance and alter their throw accordingly, otherwise the knife will hit hilt-first.

1: There are some styles where the knife goes blade-first too.
> 14 votes

# Answer
1. Calculate the straight line distance to target.
2. Each Frame set the angle of the knife to be 2PI\*(remainingStraightLineDistance)/(originalStraightLineDistance)\*DesiredNumRotations.

The spin ratio will vary slightly if you don't move the knife in a straight line but no-one will ever notice.

If you don't pre-determine the target (i.e. you're just throwing and using physics to see what it hits) then you will need to fudge this but you can use the same principle of looking at what target it's likely to hit and adjusting the spin to be correct for that target.
> 14 votes

# Answer
Real throwing-knifes are designed to have a very high chance of hitting blade-first. Design your knives accordingly.

**Collection of throwing knives from Wikipedia:**

You want the center of mass, and thus the center of rotation, **as far away from the tip of the blade** as possible. This will increase the odds that the blade will spin around into hitting position before the end of the handle gets there.

The blade is typically long and thin, to protrude as far as possible from the center of mass while adding as little mass of its own as possible. Additionally, there is a often disk-shaped or spherical counterweight at the end of the handle, which interestingly I don't see in any of the knives from the Wikipedia image.

The knife is thrown by holding the tip of the blade and arcing the handle into the direction of throw.
> 4 votes

# Answer
For a "smoke and mirrors" way, you can have the center of rotation of the knife (i.e. the center of mass) near to the handle (i.e. non-pointy part). This way, if the rotation speed is high enough compared to the knife's velocity, it can be guaranteed that the tip of blade will collide with the target and not any other part.

There's some calculation to get which is the minimum rotation speed given the center of mass and dimensions, but should be straightforward. Note also this doesn't imply anything about the angle of the hit.
> 2 votes

# Answer
Perfect knife thrower?

At the moment, you say you are spinning the knife through animation. What parameter are you using to control the angle? Frame number? Game time? Scaled by an arbitrary spin rate?

If instead you used the parameter (distance moved)/(total distance to target), with the appropriate scaling by pi and (number of turns+0.5), then the knife would indeed always magically arrive point first.
> 1 votes

---
Tags: physics, rotation, movement-prediction, collision-prediction
---


# Question
Title: How can I have realistically bending/flexing paper?
I am a new hobbyist to Unity and I working on a game where the player goes around picking up clues in the form of paper notes to solve a mystery.

So far, thanks to the help I got here, I was able to animate a note made from a UI canvas and an image in game world to fly and rotate to align itself in front of the first person camera.

Although, it looks nice, it still looks like a rigid plank of wood rather than a piece of paper. Is there a way I could bend/flew/distort the canvas to give the illusion of a piece of paper rather than piece of wood?

Is it possible to bend a canvas or should I go towards another solution, like using an actual plane or quad during the animation effect?

# Answer
> 2 votes
You might be able to use Cloth to simulate this, similar to a flag blowing in the wind.

Flag blowing in the wind: http://answers.unity3d.com/questions/935743/how-do-you-make-a-flag-blow-in-wind-unity5.html

Youtube tutorial on working with Cloth: https://www.youtube.com/watch?v=hZ8DgasVT\_M

Unity Cloth Manual: https://docs.unity3d.com/Manual/class-Cloth.html

---
Tags: unity, animation, gameobject
---


# Question
Title: Are there performance benefits to full-screen haze filters?
Some games apply a full-screen filter effect that desaturates picture, causing the colors to be "washed out".

For example, in Zelda: Breath of the Wild:

Someone used Photoshop to remove the filter, giving this result:

Is there a performance or other technical benefit to applying this kind of filter, or is it a purely aesthetic choice?

# Answer
> 1 votes
Fog is usually there to hide something or to make a game look more realistic.

Let's go way back, to the days of the first Silent Hill game. This is a very known tale alreadx so I keep it short. The developers had FPS issues when they tried rendering the game, so they had to take the view distance shorter. This made the game have a noticable cutoff, so to hide this, they added fog, which made the game have that eerie feeling it's known of. This is not the first use of fog, but it's a pretty know one.

Fast forward 10 or so years, and the fog's purpose is still the same, but rather than hiding a cutoff point, it hides things such as changing from models to billboards (which can't be hid any other way), straight up using 2d images instead of models for distant object you can't get to, and LOD changes. If you look at the Breadth of the Wild images, you can notice this. The terrain in the background is far less detailed and has a bad texture on it.

Fog can also add realism to the game, it can obviously symbolise weather and make the player a bit more freaked out.

---
Tags: performance, graphic-effects, fog
---


# Question
Title: Air AS3 Desktop - Detecting wrong screen resolution and coordinate offset
I have an issue with developing an Air desktop app using FlashDevelop in ActionScript 3.0

I'm pretty much new to all this, but I think I made all I should and am wondering if this could be some bug outside my code.

My screen and desktop composition is as follows:

1x Surface pro 3 with Multitouch 2160x1440 screen on the left (Identified as Screen 1) 1x Dell P2314T Multitouch with 1920x1080 screen in the middle (Identified as Screen 2) 1x Dell P2314T Multitouch with 1920x1080 screen on the right (Identified as Screen 3)

When I run Air app with fullscreen mode with

```
stage.displayState = StageDisplayState.FULL_SCREEN;
stage.scaleMode = StageScaleMode.NO_SCALE;

```

I get it on the Surface's screen on fullscreen, it being the windows Main display. If I trace the `stage.nativeWindow.width and stage.nativeWindow.height` I get the correct resolution.

Now since I wanted the app to run on the 23" screen, I set Screen 2 to be the Main display in windows. Now AIR app is ran on the screen 2 by default, thus reporting the stage width and height being 1920 and 1080. However, the child sprites I have on stage with coordinate x = 0 are outside my screen area! They are not visible on the screen on the left, but simply hidden like they're outside of the stage. If I put first child x offset to 120 (half of the difference between 1920 and 2160 screen widths), it's positioned approx on the left edge.

To see better what's going on, I went to screen resolution manager and disabled the internal Surface's screen completely ("Don't show desktop on this screen", thus leaving me with 2x 1920x1080 screens only.

If I run the code now, the stage.nativeWindow.width and height are reporting resolution of 2160x1440 - that's screen 1, which is disabled and has no image on it at all. The Sprite x offset issue remains the same, being 120 in minus.

The code is completely clear, having stage with single sprite and quad drawn.

```
public class Main extends Sprite
    {

        static public var instance:Main;

        public function Main()
        {
            instance = this;
            Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
            stage.displayState = StageDisplayState.FULL_SCREEN;
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.nativeWindow.alwaysInFront = true;

            trace( String(stage.nativeWindow.x) + ' y: ' +
            String(stage.nativeWindow.y) + ' size h: ' +
            String(stage.nativeWindow.height) + ' w: ' +
            String(stage.nativeWindow.width) );
            init()
        }

        private function init():void
        {
            frame = new Sprite
            frame.x = 120;
            frame.y = 450;
            addChild(frame);
            trace('frame x: ' + frame.x);

        }

    }

```

What could possibly cause such error? Could someone confirm whether this error is reproducible?

Thanks!

**Edit 1:**

Ok, seems like the failed offset was fixed adding the stage align property in main:

```
stage.align = StageAlign.TOP_LEFT

```

I'm still interested to know why the runtime default align happens using scree 1 instead of main's resolution, and therefore fails to be correct though!

The magic about wrong resolution still stays the same, and can't be reproduced using two different screens (AOC 1920x1080 and Dell 1920x1200) in same composition, using same settings. Weird...

# Answer
> 1 votes
In order to listen to stage resize, orintation change, and to position items correctly on your screen, the only option is: Stage.align = StageAlign.TOP\_LEFT; Stage.scaleMode = StageScaleMode.NO\_SCALE; Then, you resize and layout items yourself.

If you use other alignments (TOP, TOP\_RIGHT, BOTTOM, BOTTOM\_RIGHT, BOTTOM\_LEFT) stage will not report that it has been moved, and even if you see it centered, it doesnt tell you. 0.0 in that case will be relativo to top left corner of ALIGNED stage, but nothing will warn you.

So, NO\_SCALE, TOP\_LEFT are the winning combination for AIR apps.

---
Tags: actionscript-3, flashdevelop
---


# Question
Title: Screen Space reflections not tracing correctly - GLSL
I've been trying to implement screen space reflections for the past couple of days, however it's been difficult finding specific implementation instructions or guides.

Most of the hits on the subject that I can find relate to UE4 or Unity, or a sample implementation in HLSL derived from GLSL work both using different coordinate systems for the y and z axes.

Following what little I could find, I've been using the following shader:

```
#version 430

layout (std430, binding = 2) buffer Camera_Frag
{
    mat4 pMatrix;
    mat4 InvPMatrix;
    vec2 ScreenSize;
};

uniform sampler2D ViewNormalMap;
uniform sampler2D DepthMap;
uniform sampler2D LightMap;

in vec2 TexCoord;
layout (location = 0) out vec4 FragColor;

vec2 RayCast(vec3 dir, inout vec3 hitCoord, out float dDepth)
{
    dir *= 0.25f;

    for(int i = 0; i < 20; ++i) {
        hitCoord               += dir;

        vec4 projectedCoord     = pMatrix * vec4(hitCoord, 1.0);
        projectedCoord.xy      /= projectedCoord.w;
        projectedCoord.xy       = projectedCoord.xy * 0.5 + 0.5;

        float depth             = texture(DepthMap, projectedCoord.xy).r;
        dDepth                  = hitCoord.z - depth;

        if(dDepth < 0.0)
            return projectedCoord.xy;
    }

    return vec2(0.0f);
}

void main(void)
{
    vec3 View_Normal            = texture(ViewNormalMap, TexCoord).xyz;
    float View_Depth            = texture(DepthMap, TexCoord).r;
    vec3 ScreenPos              = 2.0f * vec3(TexCoord, View_Depth) - 1.0f;
    vec4 View_Pos               = InvPMatrix * vec4(ScreenPos, 1.0f);
         View_Pos              /= View_Pos.w;

    // Reflection vector
    vec3 reflected              = normalize(reflect(normalize(View_Pos.xyz), normalize(View_Normal)));

    // Ray cast
    vec3 hitPos                 = View_Pos.xyz;
    float dDepth;
    float minRayStep            = 0.1f;
    vec2 coords                 = RayCast(reflected * max(minRayStep, -View_Pos.z), hitPos, dDepth);

    FragColor                   = textureLod(LightMap, coords, 0);
}

```

I get the scene projected further down, but it isn't upside down. Notice the vases and the plants on top of them. Its like the scene gets resampled and pushed downwards.

Can anyone help me understand why I'm not getting the expected results? I've never done any raytracing before, so perhaps I'm misunderstanding how this is supposed to work.

# Answer
The problem was that I was not using the right DEPTH value.

I noticed that if I increased the ***minRayStep*** value from 0.1f to 30.0f, I was getting what resembled somewhat *okay* reflections. I figured that didn't make a lot of sense as I was sure to be stepping way too far into the depth buffer.

Within my ***RayCast*** function, I somehow overlooked that I needed *View Space depth*, but I was just grabbing the *raw NDC depth* by mistake.

To fix this I created the following handy function:

```
vec3 CalcViewPositionFromDepth(in vec2 TexCoord)
{
    // Combine UV & depth into XY & Z (NDC)
    vec3 rawPosition                = vec3(TexCoord, texture(DepthMap, TexCoord).r);

    // Convert from (0, 1) range to (-1, 1)
    vec4 ScreenSpacePosition        = vec4( rawPosition * 2 - 1, 1);

    // Undo Perspective transformation to bring into view space
    vec4 ViewPosition               = InvPMatrix * ScreenSpacePosition;

    // Perform perspective divide and return
    return                          ViewPosition.xyz / ViewPosition.w;
}

```

And both in *main* and *RayCast*:

```
vec2 RayCast(vec3 dir, inout vec3 hitCoord, out float dDepth)
{
        ...
        float depth             = CalcViewPosition(projectedCoord.xy).z;
        ...
}

void main(void)
{
    vec3 View_Normal            = texture(ViewNormalMap, TexCoord).xyz;
    vec3 View_Pos               = CalcViewPosition(TexCoord);
    ...
}

```
> 4 votes

---
Tags: shaders, glsl, reflection-rendering, ssr
---


# Question
Title: Should we avoid a padding of transparent pixels around an image when creating Assets to be used in 3D Space?
Assuming we are creating Assets to be used on iOS in order to create textures that are then mapped to the surface of Quads in 3D Space, is below recommendation and its reasoning appropriate?

> Try to avoid unnecessary\* transparent pixels whilst ensuring a Power of 2 texture size.
>
> Since the texture will occupy the same amount of RAM whether it has its content spread across its entire surface or not, try to use as much of the available surface for the content as possible. This will improve visual quality when downsizing the texture (e.g. to generate Mipmaps).
>
> Example (for illustrative purposes, transparency is represented by a Gray color):
>
> \*e.g.: a padding of transparent pixels around an image could be considered unnecessary if the texture will be resized anyway.

# Answer
The reasoning is correct, as long as you take into account usage of the texture.

1. When texture is used on a 3D model (or a 2D with transformation), then having extra resolution/details for the same performance "price" is almost always better (but see n.3).
2. When texture is used in 2D and does not intended to be resized, then you might want to have it in the exact scale you are going to display it. Otherwise you end up with "larger-than-needed" texture being scaled down, which provides poorer quality (slightly blurry or jaggy, depending on resize method) than when texture is drawn to be rendered pixel-to-pixel perfectly.
3. Much alike n.2, sometimes your artistic style will call for specific texture sizes (think pixel-art games). E.g. ship's texture has to be exactly 176x221 pixels to match the scale of 1px thin and 3px thick lines. In that case you will have to sacrifice performance/memory for aesthetics.
> 2 votes

---
Tags: textures, assets
---


# Question
Title: fish tank water distortion Shader for unity
I am working on **unity** and trying to make a fish tank water distortion Shader effect with the following requirement:

1.its a 2D top down prospective.

2.every object under/in the fish tank has to be distorted, game objects might pass trough/under the fish tank (distortion) and game object might pass over the fish tank (no distortion) as well.

3.the fish tank does not follow the main camera.

I try to search online and most of the solution I get is to apply the shader to an object or to the main camera which will not meet requirement 3 or 2, can someone give me an ideal on what is the best way to deal with this ? I am working on a mobile game so the solution has to be light weighted on processing power. Many thanks !

# Answer
> 5 votes
I think I did something similar to what you are looking for few month ago.

I open-sourced the whole thing on GitHub and tried to keep it simple (script / prefab / shader).

# How it works

## 1/ A shader for the water surface

It's a rather simple transparent bumped colored shader

* with a GrabPass, so it can display everything that has been drawn before
* with a bump mapping texture

* a Color to apply to the grabbed texture
* an additional sinusoïdal deformation with the magnitude parameter

So it’s basically just a simple transparent shader that applies a color and a bump texture.

Note: I'm not really skilled in writing shaders so this I cannot guaranteed it will be working on every platforms.

## 2/ A simple trick

The reflection is just a simple trick. For every object we want to reflect in the water, we create a new mirroded sprite!

Note: I'm not using the right sprite in this picture for the boat reflact but it's just a SpriteRenderer, it could be easily changed.

Note 2: the reflect creation can be automated with a script. That's what I did in my package.

# Answer
> 0 votes
Why don't you use two cameras?

One render the the fishtank and whatever will pass under and the other render everything else that shouldn't have distortion.

---
Tags: unity, shaders, water
---


# Question
Title: Stuck on walls or sliding on top dilemma
I'm making a 2.5D platformer game. I earlier had problem with my character getting stuck on walls when holding the forward button. I solved this problem by adding a physics material with zero friction to my colliders on the wall. So now when hitting a wall the character slides down, which is correct.

My walls consits of 1 unit cubes tiled together, and box colliders are generated and merged at runtime.

Now I've created a ladder and by pressing a button the player will rotate 180 degrees, and I also add some force along the y- and z-axis:

```
var force = -transform.forward + Vector3.up;
force.y *= JumpOffForceY;
force.z *= JumpOffForceZ;
_rigidBody.AddForce(force, ForceMode.Impulse);

```

Now when the player lands on the top of the wall, which has the same box collider, and physics material, the player slides very jerky for a long time before coming to a halt.

I understand why this happens, I've been trying to find a solution. One solution I'm thinking of is to change my algorithm that creates the box colliders and divide them so there is one box collider on the top with higher friction, and one for the walls with zero friction. Before I delve into that, is that a good solution? Or is there any other way?

Have a nice day!

# Answer
I faced a similar problem a long time ago, and found that for me the easiest solution was to add a second collider, which was thin, but acted as a surface for walls/rooftops. I then made a prefab which I could scale around my visual object. Maybe that helps?
> 1 votes

# Answer
Unity had a Character Controller for this exact reason. It works very well for 3D, and should translate just fine to 2.5D.
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Limiting GIF animation rate to its frame delay in JME3
I've figured out how to render a GIF image using this library as follows:

```
@Override
public void simpleUpdate(float tpf) {
    if (bgFrameIndex > 0) {
        guiNode.detachAllChildren();
    }

    guiNode.attachChild(bgNodes.get(bgFrameIndex));

    if (bgFrameIndex < bgDecoder.getFrameCount() - 1) {
        ++bgFrameIndex;
    } else {
        bgFrameIndex = 0;
    }
}

```

where `bgDecoder` is a `GifDecoder`, `bgNodes` is an `ArrayList` of nodes that contain the GIF's frames, and `bgFrameIndex` is the current frame index to render. By default, the `tpf` (ticks per frame) variable is at around 0.01 seconds, when I want to limit it to the frame delay of the current frame without changing the FPS of the entire game. What's the best way to do this?

**EDIT**

My new code from the answer of @1000ml (I also fixed frame removal):

```
private float bgFrameDelay = bgDecoder.getFrameCount() > 0 ? bgDecoder.getDelay(bgFrameIndex) : 0;

@Override
public void simpleUpdate(float tpf) { // ticks per frame
     bgFrameDelay -= tpf;

     if (bgFrameDelay < 0F) {
         bgFrameDelay = bgDecoder.getDelay(bgFrameIndex) / 1000F;

         if (bgFrameIndex > 0) {
             bgNodes.get(bgFrameIndex - 1).removeFromParent();
         }

         guiNode.attachChild(bgNodes.get(bgFrameIndex));

         if (bgFrameIndex < bgDecoder.getFrameCount() - 1) {
             ++bgFrameIndex;
         } else {
             bgFrameIndex = 0;
         }
     }
 }

```

# Answer
> 0 votes
Adding a `Thread.sleep()` call to the `simpleUpdate()` method will throttle the whole jme thread. This will be very noticable when you add more elements to your application.

Here's a way to skip calls to `simpleUpdate()` until the desired delay is reached:

```
private float t = bgDecoder.getDelay(0);

public simpleUpdate(float tpf) {
    t -= tpf;
    if(t > 0f) {
        return;
    }
    t = bgDecoder.getDelay(bgFrameIndex) / 1000f;

    // Your stuff goes here
}

```

You might have to adjust the frame index, but I hope you get the idea.

# Answer
> 0 votes
Ended up just using `Thread.sleep(bgDecoder.getDelay(bgFrameIndex));` and everything works perfectly! I'd love to hear any better alternatives.

---
Tags: java, animation, jmonkeyengine
---


title: Numeric problem with ray transformation

text:
# Question
Title: Numeric problem with ray transformation
I am performing ray triangle intersection by transforming the ray into the object space for efficiency. I am using the same technique from this question (The correct way to transform a ray with a matrix?).

My question has to do with the numeric stability of the transformed ray. This is my code

```
Matrix4f matModel= this->getWorldTransform();
Matrix4f matModelInverted = matModel.Inverted();
Matrix4f matInverseNormal = matModel.Transposed();

rayOrigin = matModelInverted.Transform(rayOrigin);
rayDirection = matInverseNormal.Transform(rayDirection).Normalized();

```

`matModel` is the Object-to-World transform and it is a very simple translation matrix with this value

```
| 1 0 0 -4 |
| 0 1 0 -15|
| 0 0 1 -13|
| 0 0 0  1 |

```

`matInverseNormal` is the transposed inverse of the matrix used to transform the ray origin and has the value

```
| 1  0   0  0|
| 0  1   0  0|
| 0  0   1  0|
|-4 -15 -13 1|

```

My code works as it should most of the time, the problem appears around certain value where the transformed ray direction behaves erratically and the ray flip flops by as much as 180 degrees for very small changes in the input.

For input ray direction `{-0.59531, 0.64250, -0.48249}` I get a transformed direction `{-0.59531, 0.64250, -0.48249}` which is visually the correct behavior. Perturbing the values of the input ray direction to `{-0.59520 0.64320 -0.48169}` (a change of about 10e-3 magnitude) gets me `{0.59520, -0.64320, 0.48169}`, which has flipped signs on all axes and is visually the incorrect behavior.

What am I doing wrong?

# Answer
> 0 votes
I managed to solve the problem but I would certainly appreciate a mathematical explanation as to why it works.

I performed the calculations using 4D Vectors instead of 3D. The fourth component for the ray origin was set to 1.0 and the fourth element in the direction component was set to 0.0. Then I did matrix multiplication as usual. And from the output values I used only the 1st three components.

The code now looks like this

```
Vector4f o = Vector4f(rayOrigin.x, rayOrigin.y, rayOrigin.z, 1.0f);
Vector4f d = Vector4f(rayDirection.x, rayDirection.y, rayDirection.z, 0.0f);

o = matModelInverted.Transform(o);
d = matInverseNormal.Transform(d).Normalized();

```

Works like a charm.

---
Tags: raycasting
---


# Question
Title: Could triangles be used for swept-AABB checks between positions?
I'm trying to understand swept-AABB collision detection. When checking for collisions between two positions of an object, I commonly see one of 3 strategies used:

* Rays: trace rays from parts of the AABB at the previous postion to those on the final position, and check for intersection between them and other objects.
* CCD: split the motion into multiple in-between positions, and check each one for collisions.
* No sweep: just check that start and end positions are collision-free, and assume there was no collision in between.

A solution I've not seen discussed is **just to use 2 triangles**.

Here's how they compare:

The math wouldn't change even if you started using OBBs or convex shapes with more vertices: you still just need 2 triangles.

The above image illustrates the shortcomings of each approach. Only the Polygon conversion test is sure to catch all of the swept region.

From the tests I have done, simple triangle collision in not that costly, though slower than AABB–AABB and sphere–sphere. It seems to cost less than CCD also, but avoids misses (e.g. CCD might miss the red cube in the top left). Rays have a tendency to miss small objects if you imagine moving one of the red cubes up or down in the image.

Are there issues with this technique that would cause it to be used so little?

# Answer
> 2 votes
Yes, your technique would work. It looks like a certain implementation of the **convex hull** technique, where you construct a convex hull describing the movement, and detect collisions by checking the overlap of those convex hulls with each other. Depending on implementation details, your technique could be faster or slower - note that your triangles technique has two redundant diagonal edge tests, which could be made faster by converting the two triangles into a single quad.

But there are other techniques, including **spacial partitioning**, **Minkowski**, and all sorts of variations under the **bounding volume** family (which includes everything from bounding spheres, AABB, down to convex hull).

One disadvantage with many of these techniques, including yours, is that it does not give the time and location of the collision. CCD does, so does transforming into a ray-volume test.

# Answer
> 0 votes
Continuous Collision Detection (CCD) and Ray Casting provide a specific time of impact (TOI). However using two AABBs and two triangles to create the 'hexagon' that covers all locations of the AABB's travel, you would only know whether TRUE/FALSE an intersection occurred - this isn't as useful when dealing with 'swept AABB' detection.

Even with the images if you have a box in the middle of your two triangles is true that the triangles will detect the hit as true but they cannot tell you which edge hit first or *when* along the swept aabb it occured.

---
Tags: collision-detection, geometry, aabb
---


title: SFML collisions

text:
# Question
Title: SFML collisions
I'm needing help with the collision response of my player "Mario". I would like my player to be able to stand on the tiles that i add if he jumps as well as collide wit them if he walks into them i'll show the code below. I'm using AABB collision i think that's all the information that you need, but no doubt i'll miss something if you need anything more then please just ask. Thanks for taking the time to read and help out if you can.

in the game.cpp

```
//check collision with world
vector<Tile>* world = level.getLevel();
for (int i = 0; i < (int)world->size(); i++)
{
    if ((*world)[i].isAlive())
    {
        //if "alive" check collision
        //world tile that are not alive don't do checks
        if (checkCollision(&mario, &(*world)[i]))
        {
            mario.collisionResponse(&(*world)[i]);
        }
    }

}
 bool Game::checkCollision(MySprite* sprite, MySprite* sprite2)
 {
if (sprite->getAABB().left + sprite->getAABB().width <sprite2->getAABB().left)
    return false;
if (sprite->getAABB().left > sprite2->getAABB().left + sprite2->getAABB().width)
    return false;
if (sprite->getAABB().top + sprite->getAABB().height < sprite2->getAABB().top)
    return false;
if (sprite->getAABB().top > sprite2->getAABB().top + sprite2->getAABB().height)
    return false;

return true;

 }

```

in the mario.cpp

```
#include "Mario.h"

 Mario::Mario(sf::RenderWindow* hwnd, Input* input, const sf::Vector2f &size) : MySprite(size)
 {
scale = 200.f;
gravity = 3.5f * scale;

falling = true;
animated = true;

window = hwnd;
in = input;

walkRight.init(0, 0, 15, 21, 4, 0.3f);
walkLeft.init(0, 0, -15, 21, 4, 0.3f);
swimRight.init(0, 22, 15, 20, 3, 0.2f);
swimLeft.init(0, 22, -15, 20, 3, 0.2f);
duck.init(0, 41, 15, 20, 2, 0.6f);

currentAnimation = &walkRight;
setTextureRect(currentAnimation->getCurrentFrame());

}
Mario::~Mario()
{

}
void Mario::update(float dt)
{
//collision with wall while jumping
if (getPosition().x < 0)
{
    velocity.x = 0;
    setPosition(0, getPosition().y);
}
else if (getPosition().x > window->getSize().x - getSize().x)
{
    velocity.x = 0;
    setPosition(window->getSize().x - getSize().x, getPosition().y);
}
if (getPosition().y < 0)
{
    velocity.y = 0;
}
else if (getPosition().y > window->getSize().y - getSize().x)
{
    velocity.y = 0;
}

//falling
if (falling)
{
    move(velocity*dt);
    velocity.y += (gravity)*dt;

}
if (getPosition().y >= 500)
{
    falling = false;
    setPosition(getPosition().x, 500);
}

if (animated == true)
{
    // ANIMATION //
    elapsedTime += dt;
    if (elapsedTime >= currentAnimation->getAniTime())
    {
        //next frame
        currentAnimation->nextFrame();
        setTextureRect(currentAnimation->getCurrentFrame());
        elapsedTime = 0;
    }
}

// INPUT //
if (in->isKeyDown(sf::Keyboard::RShift))
{
    // point to current animation
    currentAnimation = &swimRight;
}
if (in->isKeyDown(sf::Keyboard::LShift))
{
    // point to current animation
    currentAnimation = &swimLeft;
}

//jump
if (in->isKeyDown(sf::Keyboard::Space) && !falling)
{
    velocity.y = - 2.0f * scale;
    falling =  true;

}
/*if (in->isKeyDown(sf::Keyboard::Space)==false)
{
    falling = false;
}*/
if (in->isKeyDown(sf::Keyboard::Right))
{

    if (getPosition().x < window->getSize().x - getSize().x)
    {
        currentAnimation = &walkRight;
        velocity.x = 100;
        move(velocity.x * dt, 0);

    }
}

if (in->isKeyDown(sf::Keyboard::Left))
{
    //if (getPosition().x < window->getSize().x - getSize().x)
    //{
        velocity.x = 100;

        currentAnimation = &walkLeft;
        move(-velocity.x * dt, 0);
        //if (in->setKeyUp(sf::Keyboard::Left))
        //{
            //animated = !animated;
        //}

    //}

}
if (in->isKeyDown(sf::Keyboard::P))
{
    //in->setKeyUp(sf::Keyboard::BackSpace);
    animated = !animated;
}
updateAABB();
}

void Mario::collisionResponse(MySprite* sp)
{

//problems here
}

```

# Answer
Usually if you have a tiled level, you can calculate from World coordinates of your character the index of your tile by dividing your coordinates by tile size.

Example:

your character is at position `(123, 78)` and your tilesize is `32 px`. Then the tile your character is occupying is `(3,3)` (123/32=3.xx; 78/32=3.xx)

so on moving to right you want to position your character at 130, 78 now he is walking into tile `(4,3)` (130/32=4.xx) So before you make the move you need to check if tile `(4,3)` is occupied.
> 2 votes

---
Tags: c++, collision-detection, sfml
---


title: Game loop on windows

text:
# Question
Title: Game loop on windows
I have seen different "basic" game loops both from books like "Introduction to 3D game programming with DX11" or online tutorial ( Rastertek ) and if we take off all the fancy stuff to control framerate and more they all look roughly like this :

```
while (msg != WM_QUIT) //
{
    if (PeekMessage(&msg,0,0,0,PM_REMOVE)
    {
        // Translate and dispatch message
    }
    else
    {
        // Do update, rendering and all the real game loop stuff
    }
}

```

If you run it this way it works perfectly, but the thing that i do not understand is the **else**. If i look naively at the loop i might think that if the system keeps sending events ( key presses, mouse clicks and more ) the **else** part will never be executed, am i wrong ? ( yes!! i am but this is exactly the point, i don't understand why! ).

I'd like to understand why the loop works this way. If the messages were strictly related to the window ( resizing,moving,closing ) i'd understand it, but they are not. Let's say that i keep pressing any key a WM\_KEYDOWN message is repeatedly sent and a message is peeked, thus never allowing the else part to execute

I have not a lot of experience with the Win32 library and i'm probably missing something^^.

Thank you for your time and happy coding!

# Answer
I have not seen an else being used in this instance (the Rastertek tutorial you mentioned does not use an else).

My guess would be if that you tried to resize your window the game rendering would freeze proving that the else part is never executed, as the resize message would be constantly sent.

A common loop would have this structure.

```
while (true)
{
    while (PeekMessage(&msg,0,0,0,PM_REMOVE)
    {
        // Translate and dispatch message
    }

    if (msg.message == WM_QUIT)
    {
        break;
    }

   // Do update, rendering and all the real game loop stuff

}

```
> 10 votes

# Answer
I think the thing you need to grasp is that the message processing will run much faster than the rate at which messages are sent.

For the example code you've provided, here's an estimate of timings:

```
while (msg.message != WM_QUIT) //
{
    if (PeekMessage(&msg,0,0,0,PM_REMOVE)
    {
        // Translate and dispatch message
        // [A] --> This takes a very small amount of time (epsilon ms)
    }
    else
    {
        // Do update, rendering and all the real game loop stuff
        // [B] --> This takes way more time, ~16 ms at 60 fps for instance
    }
}

```

I've not searched the documentation for this but Windows is probably **not** spamming messages all the time: they have to come at regular intervals or they'd be clobbering the system. Maybe they use the keyboard refresh rate if you keep pressing one key. Maybe they use the screen refresh rate.

Let's say a new message comes every *t* ms, reasonably greater than *epsilon*. The `[A]` part of the loop will process all stacked messages very quickly: it will run for *epsilon* ms and start again, which leaves no chance for new messages to arrive. As soon as all messages are consumed, the `[B]` part will run and new messages will stack again.

Here's an illustration to try to make my point, `[An]` are processings of the `[Mn]` messages sent by Windows, and `[Bn]` are actual frame updates:

```
Game:    --[A1][B1----------][A2][A3][A4][B2----------][A5][A6][A7][B3------->

            ^       ^       ^       ^       ^       ^       ^      ^
Windows: ..[M1]....[M2]....[M3]....[M4]....[M5]....[M6]....[M7]....[M8]....

```

Here you can see that as long the duration of `[A]` stays reasonably small compared to the message rate (it's already very exaggerated here), the game will still have plenty of time to update its frames.

So this explains why such a game loop structure doesn't prevent a game to run normally. But the solution CoderScott proposed in his answer makes this execution flow much more explicit, so in my opinion it should be preferred.
> 4 votes

# Answer
No, you are not wrong. Actually that's true - if there are too many events the else will never be run, or at least will not be run quickly enough. If your UI methods take too much time to process the event this could lock the OpenGL refresh. First of all you should check why processing events is taking that much processing, but in sometimes you can be spammed by events (like quick mouse move with big refresh rates) and then even simple processing takes too much time to be in line with OpenGL frame refresh timings.

This loop actually is really bad and it hit me as I copy pasted it from many resources on the internet too (note this is **wrong approach**):

```
while( true ) {
    if ( PeekMessage( &m_msg, m_hWnd, 0, 0, PM_REMOVE ) ) {
        if ( WM_QUIT == m_msg.message ) {
            break;
        } else {
            TranslateMessage( &m_msg );
            DispatchMessage( &m_msg );
        }
    } else {
        processFrame();
    }
}

```

The correct one is like this:

```
while( !finished ) {
    DWORD currentTick = GetTickCount();
    DWORD endTick = currentTick + 1000/FRAMES_PER_SECOND;

    while (currentTick < endTick) {
        if ( PeekMessage( &m_msg, m_hWnd, 0, 0, PM_REMOVE ) ) {
            if ( WM_QUIT == m_msg.message ) {
                finished = true;
                break;
            } else {
                TranslateMessage( &m_msg );
                DispatchMessage( &m_msg );
            }
            currentTick = GetTickCount();
        } else {
            break;
        }
    }

    processFrame();
}

```

So with additional break, if the processing events procedure consumed too much then a forced OpenGL frame refresh is made.
> 3 votes

# Answer
**if/else** in your loop will process windows messages before anything. It will not block loop too long (of course if your WndProc will be good). Usually there is not so much messages. I dont think there is a better way to prevent window from stop responding and save FPS. If you will keep your message processing code good i think your loop will be great.

Here is my code, i believe it will be interesting for you, and it is quite usable. But one day i will code a new one. At least it is much better than many other. **For playable game you will definitely need a stable state update() rate.** Windows messages will not break it.

```
// Game loop paramters.
const int TICKS_PER_SECOND = 70; // Update() rate per second
const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
const int MAX_FRAMESKIP = 10;

```

Run() function:

```
DWORD next_game_tick = GetTickCount();
int loops;
MSG msg = {0};
m_bIsGameRunning = true;
while( msg.message != WM_QUIT && m_bIsGameRunning )
{
    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        g_pWindow->HandleMessage(msg); // translate and dispatch the message
    else
    {
        // *Update*
        loops = 0;
        while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP)
        {
            Update();

            next_game_tick += SKIP_TICKS;
            loops++;
        }

        // *Draw*
        Render();
    }
}
m_bIsGameRunning = false;

```
> 1 votes

# Answer
I am working on an OpenGL Shader Engine from www.MarekKnows.com and the framework is setup as follows: An Engine Class that is part of a static library with other helpful and important classes. Then there is the main startup project where the Game Class resides along with Game Properties. This structure is to keep all Engine code separate from Game code. The nice thing about this setup is it can be reused to create a variety of games just by inheriting from the Engine lib. It is not complete as of yet as each week another segment or class object is being incorporated.

This hierarchy is based on the folder & VS filter structure:

**Project - Static Lib Engine**

* **Animation**
    + AnimationManager: Inherits from Singelton
* **Engine**
    + AssetStorage: Inherits from Singleton - Stores All Game Assets & handles their memory
    + Batch: Stores vao & vbo information into batches before rendering to the GPU
    + BatchManager: Inherits from Singleton - Manages Batches, Adds To queue when necessary and empties buckets when full sending batches to GPU
    + BlockProcess & BlockThread - Helper Classes for Process & Threads
    + Engine: Inherits from Singleton - Abstract Base Class to Game\**
    + ExceptionHandler - Handles All exceptions works closely with the Logger & console output.
    + FontManager: Inherits from Singleton - handles all fonts to be loaded into memory and prepares them before rendering and stores them in the AssetStorage.
    + Logger: Inherits from Singleton
    + Settings: Inherits from Singleton Various Settings needed for Engine: physics refresh rate, isWindowed, randomNumGen, gamePixelSize, openglVersion etc.
    + Singleton - Base Class
    + Utility - Utility Functions that are useful - converting functions from numbers, vectors etc. to strings and vice versa.
    + CommonStructs - Header Only basic structs & enums common to many objects
* **FileHandlers**
    + FileHandler: Base Class
    + MkoFileReader: Inherits from FileHandler - Reads in MKO object Files & Parses Data
    + TextFileReader: Inherits from FileHandler - Reads in Text Files
    + TextFileWriter: Inherits from FileHandler - Writes to Text Files
    + TextureFileReader: Inherits from FileHandler - Reads in Texture Files (currently supported - tga & png )
* **GUI**

+ Gui.h - helper \*.h file to easily include all GUI elements
    + GuiCompositeElement: Inherits from GuiElement, Abstract Base Class
    + GuiElement: Abstract Base Class
    + GuiImage: Inherits from GuiRenderable
    + GuiImageElement: Stand alone class that is used with Gui Objects
    + GuiLabel: Inherits from GuiText
    + GuiLayout: Inherits from GuiRenderable - Abstract Base Class
    + GuiLayoutAbsolute: Inherits from GuiLayout
    + GuiLayoutGrid: Inherits from GuiLayout
    + GuiLayoutSlices: Inherits from GuiLayout
    + GuiLayoutStack: Inherits from GuiLayout
    + GuiLoader: Loads in a text file and parses data to load & render any gui elements
    + GuiRenderable: Inherits from GuiCompositeElement - Abstract Base Class
    + GuiScreen: Inherits from GuiCompositeElement - Can have children nodes but does not have any parents for it is the top level parent
    + GuiText: Inherits from GuiRenderable
    + GuiTextArea: Inherits from GuiText

**MKO** \- This MKO Object Hierarchy Relies Heavily On Templates

+ Array2d: Inherits from BaseMko
    + BaseMko: Abstract Base Class
    + FontFile: Inherits from BaseMko
    + Image2d: Inherits from VisualMko
    + Surface3d: Inherits from BaseMko
    + VisualMko: Inherits from BaseMko, Abstract Base Class

**Shader** \- This Shader Hierarchy Relies Heavily On Templates

+ ShaderManager: Inherits from Singleton, Manages Shaders
    + ShaderProgramSettings
    + ShaderVariable

**Start Up Project - Game**

* Game: Inherits from Engine
* Properties: - Properties unique to current game

With this frame work I'll demonstrate the message loop for you

```
void Engine::start() {
    while( true ) {
        if ( PeekMessage( &m_msg, m_hWnd, 0, 0, PM_REMOVE ) ) {
            if ( WM_QUIT == m_msg.message ) {
                break;
            } else {
                TranslateMessage( &m_msg );
                DispatchMessage( &m_msg );
            }
        } else {
            processFrame();
        }
    }
}

```

If you would like to see more of this code then you will have to visit www.MarekKnows.com for his wonderfully well structured and clearly explained video tutorials for Game Development using OpenGL. For copy right reasons I will only give small snippets as suggestions to others that may help them with a specific case problem. I can not claim this as my own source code, however with following his course setup everything is personally hand typed and personally debugged. There is no copying and pasting! Almost everything I have learned about Game Programming is accredited to Marek's videos along with a few other sources.

I can try to explain this the best I can from what I have learned and following the code's execution. Somewhere in the program the Engine::start() function is invoked. The first thing that happens is we go into an infinite while loop; within this while loop we check to see if any messages from windows were peeked and if they are we check to see if the WM\_QUIT message was set from some other place. If it was set we break out of the while loop and return from this function and the application will clean up memory, destroy window and close; otherwise we then call TranslateMessage() & DispatchMessage(). If the PeekMessage() returns false then we go into the else statement and call proccessFrame().

On my machine I am rending basic GUI objects at about 100-120 frames per second with this framework. I have an EVGA NVidia GeForce GTX 750Ti 2GB with overclocking and dual fan coolant running on Windows 7 64bit with 8GB Ram on an Intel Core 2 Quad Extreme 3.0Ghz.

We have not yet delved into extensive animations, physics, particles systems, collision detections as of yet. We did however cover all of that in one of his older video series were the older GameEngine was based on OpenGL v1.0 and everything was done on the CPU. With this series we are now working on using Shaders & the GPU. I am sure with this frame work we can have a full 2D or 3D game running on a system similar to mine at a full 40 - 60 FPS with ease.

Another great source for learning is to check out www.GeometricTools.com and check out the book section. A few years ago I purchased their book: 3D Game Engine Design (2nd Edition) by David H. Eberly, The Morgan Kaufmann Series in Interactive 3D Technology, and it is a great read. I have not yet had the chance to purchase their newest book: GPGPU Programming for Games and Science by David H. Eberly, but would soon like to own it since it is more relevant, current and up to date with modern hardware & software development. Good luck to you!
> -1 votes

---
Tags: c++, game-loop, windows, events
---


# Question
Title: Unity 5 - Place objects in game to closest gameobject
I am making a puzzle game in unity3D 5 for school and one of the puzzles is this: The player (third person) can pick up certain objects (4 objects) and has to place them inside holes in a wall in a specific order for a door to open.

I have 4 empty gameobjects named as slot001, slot002, slot003 and slot004 at the right positions at the holes in the wall. When the player has an item held and a certain button is pressed I link the transform of the object to the transform of the empty gameobject.

The problem is that the objects transform has to link to the transform of the closest gameobject. So when you stand in front of the slot002 gameobject the objects transform should link to the transform of slot002. The same goes for slot 001, 003 and 004 ofcourse. I am not sure how to do this.

I put the 4 empty gameobjects (slots) in a list. I know of the Vector3.Distance() function and I tried using that to check for the closest distance with Mathf.Min() but I couldn't quite get it to work.

Any help or a nudge in the right direction would be appreciated!

Thanks.

# Answer
```
GameObject closestObject = null;
var distance = SnapDistance; // guarantees it will only snap once close enough.  Assuming some value that is inspector editable, like 3.
// if you don't want a snap distance, then set the starting distance to float.MaxValue
foreach(var slot in ListOfSlots) // ListOfSlots is GameObject[] or List<GameObject>
{
   // gets the current distance from this object to the slot.
   var currentSlotDistance = Vector3.distance(slot.transform.position, transform.position);

   // check the distance.  if this is closer than the previous distance, then this is our closest object.  By checking each object to see if it is closer than the last, we will eventually find the closest one.
   if (currentSlotDistance < distance)
   {
     // once found, set the distance to our current distance, and set the closestObject to the slot we are looking at.
     distance = currentSlotDistance;
     closestObject = slot;
   }
}

if (closestObject != null) // we have a winner  closest under X distance
{
  // assuming you wanted to move this object into the slot:
  transform.position = closestObject.transform.position;
}

```
> 2 votes

# Answer
So I almost got it to work thanks to the answer of Dan Violet Sagmiller, there is just one small problem left. I need to check if a slot is already occupied. How could I do this? I was thinking of an array of booleans but that didn't quite work.

Here is the current code that I have now: http://pastebin.com/XYQ4hBEX
> 0 votes

---
Tags: unity, gameobject
---


# Question
Title: For Vertex Buffer Steaming, Multiple glBufferSubData VS Orphaning?
I was learning OpenGL recently. In games, we need to update the position of game objects frequently, and they will come in & out of screen constantly. So it means in rendering we need to update the vertex buffer quite often as well.

In OpenGL's context, one intuitive way is to use glBufferSubData to update those that changed.

But I also read online a trick called Orphaning that creates a new buffer data and upload the whole vertices data to it.

Also due to state chagnes cost and uploading cost, multiple glBufferSubData may also cost more.

Here is my question,

1. Which method is better?
2. Is stalls really matters in this case?
3. Is state changes and uploading cost really matters in this case?

Thanks!

# Answer
This is a complex question with a lot of small details that really matter, the performance will vary based on platform and application. So you should profile for possible bottlenecks before investing in optimizations.

That said, firstly, I assume you should reduce uploads and updates as much as you can, for example use instancing.

Secondly, note that GPUs can’t transfer buffers and render at the same time, so all OpenGL commands in the command queue are processed sequentially by the device. There are different ways to copy data and/or make it avaialbe to be used by the GPU.

There are various ways to stream data to GPU

**1-`glBufferData` or `glBufferSubData` method**

Using `glBufferData` or `glBufferSubData` is like memcpy. you pass a pointer and DMA operation *might be* performed, I said might because memory might be pinned in CPU memory and used directly by the GPU without actually a memory transfer to GPU happening, depending on the usage flag (GL\_STREAM). In opinion you should try this at first because it's simpler to implement.

**2- getting a pointer to internal memory using `glMapBuffer`**

If the above isn't good enough you can use `glMapBuffer`, you get a pointer to internal memory, and you can use this pointer to full the buffer directly, this is good with file read and write operations, as you can directly map the file data to GPU memory rather than copying to a temp buffer first. If you don't want to map the whole buffer you can use `glMapBufferRange` which can be used to map a portion of the buffer.

One trick is to create a large buffer, use the first half for rendering and the second half for updating.

**3- Buffer Orphaning**

Regarding buffer orphaning this can be done using glBufferData with null and the same parameters it had. The driver will return the memory block once it's not used. And will be used by the next glBufferData call (no new memory will be allocated).

All the methods mentioned cause alot of expensive sync, again GPUs can’t transfer buffers and render at the same time.

**4- `Unsynchronized Buffers`**

The fastest (and hardest to get right) method is to use buffers without synchronization you can use `GL_MAP_UNSYNCHRONIZED_BIT` flag with `glMapBufferRange`, the problem is that no sync is done, so we might upload data to a buffer begin used, and hence screwing everything up. You can use multiple buffers with unsync bit to make things a little bit easier.
> 10 votes

# Answer
I do it another way. May be something is wrong there. Some hidden dangerous things.

(I use C# + OpenTK.GameWindow)

For instancing of the object I use a separated Array Buffer Object for the set of model matrices for every instance. In the vertex shared:

```
#version 400
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texcoord;
layout (location = 4) in mat4 model_matrix;

uniform mat4 proj_matrix, view_matrix;

```

In my C# code matrices are stored in a float array `float[] mat4_array`

Then I bind the array to Array Buffer Object:

```
public void bind_data_instances()
{
    GL.BindBuffer(BufferTarget.ArrayBuffer, id_InstanceBO);
    GL.BufferData(BufferTarget.ArrayBuffer, mat4_array.Length * sizeof(float), mat4_array, BufferUsageHint.DynamicDraw);
}

```

Every frame the model matrices are updated. To update `mat4_array` I just call:

```
Buffer.BlockCopy(mat4_array_new, 0, mat4_array, 0, sizeof(float) * mat4_models.Length);

```

and render the scene. using `GL.DrawElementsInstanced`.

There is no additional OpenGL calls and it works perfectly.
> 0 votes

---
Tags: opengl, rendering, optimization, vbo
---