# Question
Title: OpenGL deferred rendering, multiple FBO targets
so for a game I am developing I am giving a go at deferred shading. I have only implemented entity rendering and an initial deferred shader and rendering the scene using OpenGLs FBO multiple render targets. I am facing an issue where the entity fragment positions do not stay in the FBO, or load the data correctly and I do not know. The code I have is open source on git but the two shaders I am working with are attached below. https://github.com/EquilibriumGames/4Space-Game Thank you for any help!

```
// entityFragment.glsl
#version 130

layout(location = 0) out vec4 out_colour;
layout(location = 1) out vec4 out_position;
layout(location = 2) out vec4 out_normal;
layout(location = 3) out vec4 out_additonal;

layout(binding = 0) uniform sampler2D colourTexture;
layout(binding = 1) uniform sampler2D normalMapTexture;

varying vec2 textureCoords;
varying vec4 entityPosition;
varying vec3 surfaceNormal;
varying vec4 positionRelativeToCam;
varying vec3 toCameraVector;

uniform bool useNormalMap;
uniform float transparency;

void main(void) {
    vec4 textureColour = texture(colourTexture, textureCoords);
    vec3 unitNormal = normalize(surfaceNormal);

    if (textureColour.a < 0.5){
        discard;
    }

    if (useNormalMap) {
        vec4 normalMapValue = 2.0 * texture(normalMapTexture, textureCoords, -1.0) - 1.0;
        unitNormal = normalize(normalMapValue.xyz);
    }

    out_colour = textureColour;
    out_colour.a = min(out_colour.a, transparency);
    out_position = entityPosition;
    out_normal = vec4(unitNormal, 0.0);
    out_additonal = vec4(0.2, 0.0, 0.0, 0.0);
}

// deferredFragment.glsl
#version 130

layout(location = 0) out vec4 out_colour;

varying vec2 pass_textureCoords;

layout(binding = 0) uniform sampler2D colourTexture;
layout(binding = 1) uniform sampler2D positionTexture;
layout(binding = 2) uniform sampler2D normalsTexture;
layout(binding = 3) uniform sampler2D additonalTexture;
layout(binding = 4) uniform sampler2D shadowMapTexture;

const int NUMBER_LIGHTS = 32;

uniform mat4 viewMatrix;
uniform vec3 cameraPosition;
uniform mat4 shadowSpaceMatrix;
uniform float shadowMapSize;
uniform float shadowDistance;

uniform vec3 lightsColour[NUMBER_LIGHTS];
uniform vec3 lightsPosition[NUMBER_LIGHTS];
uniform vec3 lightsAttenuation[NUMBER_LIGHTS];

uniform vec3 fogColour;
uniform float fogDensity;
uniform float fogGradient;

const float transitionDistance = 85.0;
const float tileAmount = 50.0;
const float shadowDarkness = 0.6;

void main(void) {
    vec4 colour = texture2D(colourTexture, pass_textureCoords);
    vec4 position = texture2D(positionTexture, pass_textureCoords);
    vec4 normal = texture2D(normalsTexture, pass_textureCoords);
    vec4 additonal = texture2D(additonalTexture, pass_textureCoords);
    float specular = additonal.r; // g, b, a

    vec4 positionRelativeToCam = viewMatrix * position;
    vec4 shadowCoords = shadowSpaceMatrix * position;
    float distanceAway = length(positionRelativeToCam.xyz);
    distanceAway = distanceAway - ((shadowDistance * 2.0) - (transitionDistance));
    distanceAway = distanceAway / transitionDistance;
    shadowCoords.w = clamp(1.0 - distanceAway, 0.0, 1.0);

    float shadowTexelSize = 1.0 / shadowMapSize;
    float shadowHalfw = shadowTexelSize * 0.5;
    float shadowTotal = 0.0;
    float shadowValue = 0.0;
    float shadowShadeFactor;
    shadowValue = texture(shadowMapTexture, shadowCoords.xy + vec2(0 + shadowHalfw, 0 + shadowHalfw)).r;

    if (shadowCoords.x > 0.0 && shadowCoords.x < 1.0 && shadowCoords.y > 0.0 && shadowCoords.y < 1.0 && shadowCoords.z > 0.0 && shadowCoords.z < 1.0) {
        if (shadowValue < shadowCoords.z) {
            shadowTotal += shadowDarkness * shadowCoords.w;
        }

        shadowValue = texture(shadowMapTexture, shadowCoords.xy + vec2(shadowTexelSize + shadowHalfw, 0 + shadowHalfw)).r;

        if (shadowValue < shadowCoords.z) {
            shadowTotal += shadowDarkness * shadowCoords.w;
        }

        shadowValue = texture(shadowMapTexture, shadowCoords.xy + vec2(0 + shadowHalfw, shadowTexelSize + shadowHalfw)).r;

        if (shadowValue < shadowCoords.z) {
            shadowTotal += shadowDarkness * shadowCoords.w;
        }

        shadowValue = texture(shadowMapTexture, shadowCoords.xy + vec2(shadowTexelSize + shadowHalfw, shadowTexelSize + shadowHalfw)).r;

        if (shadowValue < shadowCoords.z) {
            shadowTotal += shadowDarkness * shadowCoords.w;
        }

        shadowShadeFactor = 1.0 - (shadowTotal / 4.0);
    } else {
        shadowShadeFactor = 1.0;
    }

    float visibility = clamp(exp(-pow((length(positionRelativeToCam.xyz) * fogDensity), fogGradient)), 0.0, 1.0);

    out_colour = vec4((colour * shadowShadeFactor).xyz, colour.a);
    out_colour = mix(vec4(fogColour, 1.0), out_colour, visibility);
}

```

# Answer
As far as I know, a FBO is basically a texture, not a shader stage. This means, it can only contain pixel data. All the other values you emmit from you fragment shader are just ignored. If you'd really want to keep all the data, you would need to draw a FBO for each attribute you want to save, which means that you have to draw 4 FBOs, one for color, position, normal and additional. Since all of those attributes are vec4, you can use them as "colors".
> -1 votes

---
Tags: opengl, glsl, deferred-rendering, deferred-shading
---


# Question
Title: Ways to track time and character ages across many years of game time?
I'm working on a system to track large numbers of characters across long periods of time. Characters grow old and die, give birth to new characters, etc. It's a grand-strategy game, with warring nations and long scenarios.

Of course, this means I need to track the passage of years. My first idea was to create a `class Calendar`, with methods like `increment_year()` that would go through the list of every person, faction, etc in the game and call their methods (`update_age()` and so forth).

However, this would mean `Calendar` would be a singleton, which is sometimes considered an antipattern.

Alternatively, I could make a `global` variable for the current time, and update that as part of the `main()` game loop--using globals sounds like a dirty thing to do, though.

Is there a good reason to use a Calendar singleton (or even a reason to have multiple separate Calendars?)

# Answer
> 2 votes
Thinking of something like ROTK series, every scenario has a starting date and would benefit from holding the game time as one of its attributes, considering that many of its methods would need to access it.

Also, if you think of saving/loading a game, the time **should** belong to the scenario on the data file - a scenario would then represent the whole game instance/session.

If we make the current scenario available to each creature, their age could become a property:

```
@property
def age(self):
    """Return timedelta // 365, age in years."""
    return (self.scenario.date - self.birth).days // 365

```

Thinking about a turn-based strategy game, for example, at each turn/step the scenario could check for births and deaths of the creatures on it. I've made some test code to illustrate. Even if it doesn't help you, at least it points out what I (mis)understood.

```
"""An illustration of a possible approach to handle time, births and deaths."""

import datetime

class Scenario:  # or level, or map, or scene, or session
    """A class to hold maps, creatures - and time."""

    creatures = []

    def __init__(self, year, month, day):
        """Start a new scenario.

        As every scenario is time related, we hold the time as one of its
        attributes.
        """
        self.date = datetime.date(year, month, day)

    def step(self, **kwargs):
        """The ammount of time we're goin to pass."""
        delta = datetime.timedelta(**kwargs)
        self.date = self.date + delta
        self.check_births()
        self.check_deaths()

    def add_creature(self, creature):
        """Add the new creature to the list of creatures."""
        self.creatures.append(creature)

    def remove_creature(self, creature):
        """Remove a dead creature from the list of creatures."""
        self.creatures.remove(creature)

    def check_births(self):
        """Check the fertility/married attributes - that we don't have.

        If they match the criteria, a new live is created!
        """
        pass

    def check_deaths(self):
        """Check if creatures have reached the maximum age.

        If so, they're dead!
        """
        for creature in self.creatures:
            if creature.age > 40:
                creature.die(cause="time")

class Creature:
    """A living creature that resides in the current scenario."""

    def __init__(self, name, year, month, day, scenario):
        """We pass in a name, a birth date and the current scenario."""
        self.name = name
        self.birth = datetime.date(year, month, day)
        self.scenario = scenario
        self.scenario.add_creature(self)

    @property
    def age(self):
        """Return timedelta // 365, age in years."""
        return (self.scenario.date - self.birth).days // 365

    def die(self, cause):
        """Time to die."""
        death_msgs = {
            "time": "At the age of {}, {} is no more."
        }
        print(death_msgs[cause].format(
            self.age, self.name
        ))
        self.scenario.remove_creature(self)

s = Scenario(year=1200, month=12, day=1)
c = Creature(name="John Doe", year=1160, month=10, day=5, scenario=s)

# the current age, 40
print(c.age)

# some time passes
# at 41 every single person dies in this dumb test
s.step(weeks=80)

```

This would print:

> 40

And then, after one step, when the character dies:

> At the age of 41, John Doe is no more.

If you don't like the idea of passing the scenario to every creature as an attribute, another possible way would be to turn every method of `Scenario` into `@classmethod`s (which sounds reasonable to me, considering that only a single instance of scenario would be used at a time). Maybe even a dynamic transition would sounds more doable in that way (say, after x years, we enter in another scenario time-range: instead of handling a new instance of `Scenario` we could fetch specific stuff from that other scenario and use it on our class Scenario.

Should that be the case, on the creature's methods we could call `Scenario.date`, `Scenario.add_creature`, etc. In that way it would have the same functionalities of a global variable, without being one. Is it considered a bad practice? Probably, as it would work pretty much like a `global`...

# Answer
> 1 votes
If you don't need to process something every single turn/year for every character (though you might do for other reasons) you could just store the birthdate of each character, then when you need to know or display the age, subtract this from the current date. This lets you know the age of every character without having to constantly process and update all of them. You may want a death date too from the sounds of it.

# Answer
> 0 votes
The Singleton pattern is sometimes(!) by some(!) people considered an anti-pattern because it takes measures to *make it impossible* for more than one object of the class to exist and also provides access to that object from everywhere turning it into a global variable in disguise. This does not mean that it is bad when you have an object where you *usually* only having one instance of even though it would be *theoretically* possible to have more than one.

I would not necessary call the class `Calendar`, but otherwise there is absolutely nothing anti-patterny about a class which controls the flow of time, is instanced at game start and is explicitly passed to those objects/methods which require a reference to it.

In general, you should be careful with blindly following "patterns" and dismissing "anti-patterns" when you don't fully understand *why* they are considered good or bad. Otherwise you will just be following a cargo cult. A good resource for learning about the rationales behind patterns and anti-patterns is programmers stackexchange.

# Answer
> 0 votes
I wouldn't use a calendar, I would just make time a property of your game world, then having an "advance time" method that does both, update the state of your large number of characters and advance the time property.

The world could contain the time and a list of characters (you probably need to insert and remove elements from this list quite frequently, so pay attention to the time complexity of insertions and deletions).

One thing to clarify is if the update of a character only depends on the state of the character (and the world in general) itself but not on the state of other characters? If not, you would have to store the old state of the characters before, update then the character states and only afterwards forget about the previous characters' states.

Also the order of aging, dieing, giving birth might influence the outcome (in one time step, do you first give birth and then die or first die and then give birth only if you didn't die before), but not very much, you just have to decide for an order.

In Python like syntax this would look like:

```
class World():

    def __init__(self):

        # time in your time format
        self.time = X

        # characters as list
        self.characters = [...]

    def advance_time(self):

        # new characters
        updated_characters = []

        # loop over all characters
        for character in self.characters:

            # update character (may or may not depend on other characters and time)
            update_character_function(character, self.characters, self.time)

            # if he hasn't died, keep him
            if character.is_alive():
                updated_characters.extend(character)

            # maybe he gives birth (may or may not depend on other characters and time)
            if gives_birth(character, self.characters, self.time):
                updated_characters.extend(newborn_character_function(character))

        # finally replace characters by updated characters
        self.characters = self.updated_characters

        # and update the time
        self.time = update_time_function(self.time)

```

---
Tags: architecture, python, strategy
---


title: How to run Unity in "headless" mode?

text:
# Question
Title: How to run Unity in "headless" mode?
I need to run my game without graphics and user input (headless mode).

I googled it but I actually couldn't find a solution, except something like this:

```
using UnityEngine;
using System.Collections;
using UnityEditor;

public class a : MonoBehaviour {

    public static void BeforeBuild()
    {
        EditorUserBuildSettings.enableHeadlessMode = true;
    }
}

```

Unfortunately, this doesn't work for me as it seems to work only on Linux.

Am I forced to run my instance on Linux?

I would be really thankful if anyone could help me!

# Answer
From the documentation:

> Unity Standalone Player command line arguments
>
> Standalone players built with Unity also understand some command line arguments:
>
> \[...\]
>
> **-batchmode** Run the game in “headless” mode. The game will not display anything or accept user input. This is mostly useful for running servers for networked games.
> 11 votes

---
Tags: unity
---


title: Add Boo or Python to Unity 5

text:
# Question
Title: Add Boo or Python to Unity 5
I'm new to Unity, but I'm more comfortable with Python.

Is there any way to use Python as scripting language in Unity 5?

I heard there is some language called Boo that has a syntax like Python but it seems Unity just supports C# and Javascript.

How can I add Boo or Python scripting to Unity 5?

# Answer
Unity's primary development language is C#. I am not aware of any way to add a new scripting language to Unity which works just like a native one.

But you can call Python from C# using IronPython. So you could implement a stub for each MonoBehaviour in C# which doesn't do more than call a Python script to implement the actual logic.

The end result might be that for many classes, the boilerplate C# code to call the Python implementation will be more code than the Python implementation itself. Also, there will be performance overhead for the switching between C# and Python, so your game won't be as fast as it would be when developed in pure C#.

Or you could just learn C#. The hardest part when learning a new programming language is usually to learn how to use all the libraries and APIs you need to do something productive with them. And you will have to learn the Unity scripting API anyway, no matter which programming language you use to call it.
> 4 votes

# Answer
Unity dropped the support for Boo, however Boo script can be use anyway. Check this post
> 0 votes

---
Tags: unity, python, boo
---


# Question
Title: How does the 3G network assign IP to smartphones?
I am playing a game on the 3G network using Android or Iphone. Suppose I am moving from one cell to another; Will the IP Address change? If yes, then how can I continue the same game while changing the base station, as my IP address is already registered in The game server? Is there something DHCP?

# Answer
Just as @JustSid said, if you move from one cell to another the handover is handled transparently. The 3G network is just the method of transportation of your data packets, therefore it is a few layers below the IP layer, if you think in terms of the ISO/OSI stack. I worked on a push-to-talk application for mobile phones and all i can say is, that we never dealt with 3G cell changes. We just opened a TCP connection and started sending packets. One thing that also depends on your carrier is the 3G \<-\> 2G handover. With some carriers it worked fine, with some others we had disconnects.
> 12 votes

# Answer
A HTTP request from a mobile device is routed through a WAP Gateway. These are maintained by the mobile network operators. The WAP Gateway routes the request to the desired server and returns the response to the client.

As far as I know, IP routing on a mobile phone has nothing to do with cell tower base stations as everyone on the same network would be routed through these gateways.
> 4 votes

# Answer
An effective way around this is to send a client a 'session ID' that they can reconnect to IP.

Allocate 2 IPs to the mobile - one of them stays constant (the identifier) & one which varies, (the location). This is termed 'Tunnel-based'.
> 0 votes

---
Tags: networking, server, mobile
---


# Question
Title: Why does my mesh disappear from certain angles?
I'm trying to construct a hexagonal prism from vertices for my turn-based strategy game. This is my first time working with meshes and I have been following this tutorial.

The problem I am having is that the sides of my shape disappear at certain angles (in this example, I only rendered the top, bottom, east, and west sides).

I have tried removing the main camera and lighting from the scene. I have tried using `RecalculateBounds()` but that had no effect and besides, Unity's documentation says it's not needed when assigning triangles.

The whole thing gets rendered if I position the camera perfectly, so I don't imagine I'm calculating vertices incorrectly or anything like that. Is there something I should know about Unity meshes that would cause this to happen?

# Answer
> 0 votes
Your drawing *at least some* of your sides to face the incorrect direction. We can see this in your video loop; despite looking up and into the mesh, we can clearly see the top plane. This would not happen if it was drawn with the correct facing.

By facing the wrong direction, we can see fragments of your intended mesh in the example video loop, but it will not render correctly from an outside perspective. In turn, this mostly explains why your drawn sides are disappearing when the loop moves around the back of them. One side appears to be drawn with an outward facing direction, while the other appears to have an inward facing direction.

The only time this is not evident occurs when the view is panned; It is worth pointing out that this stuff is easier to debug when you use distinctly different textures on the different sides, as the constant fuchsia can make it hard to see various inconsistencies.

It is hard to confirm the direction you are drawing your vertices at without your direct code, and the link you provide for the tutorial you followed is broken. That said, correcting your vertices to draw in ***counter-clockwise order when looking in to your mesh*** should correct your plane facing.

---
Tags: unity, rendering, camera, 3d-meshes, mesh
---


# Question
Title: Why are extra assets left in the final game?
I was just reading about what was discovered in the files for No Man's Sky, a lot of things that weren't used or relevant to the game. I also read a short while ago about the E3 settings being left in the Watch Dogs files. Why do game developers leave old and unused files in the final game?

Surely this just takes up extra space on a disc and means more data has to be downloaded if you download the game?

Also, aren't the developers afraid of what people could find?

# Answer
Major games use something called a build pipeline. This is like another set of tools that handles building the game content for all the different distributions. Multi-platform games like No Man's sky and Watch\_Dogs most definitely use different assets for the different platforms. So the way I see it there two possible answers to your question.

1. The devs forgot to remove certain assets from the pipeline and they got bundled with the actual game.
2. The devs intentionally left some "unused" assets in the game for later use during a patch or update, because they were unable to meet the deadline. Example Devil's Pit from The Witcher 3.
> 35 votes

# Answer
It can be harder than you think to find *all* the referenced content in a large game that is worked on by multiple people. Even when there are explicit tools in place to help (we built such tools at ArenaNet, anybody who uses Unreal has access to Unreal's version of those tools, Bungie has tools that do the same thing and even gave a talk about them, et cetera)

There are several ways content could be referenced that can defeat such systems, generally simply by referencing the content by something that system can't track (such as creating a implicit or hard-coded reference in code to some asset).

Even assuming you have solved the problem of finding all content inter-references, you have the problem of not being able to tell if something is actually *used*. Maybe some asset is referenced in a script somewhere, but the trigger volume for that script is incorrectly placed inside a wall and the content can thus never spawn in-game. Testing *this* exhaustively is quite difficult as well.

When automated (or automat*able*) methods for detecting and filtering out unused content fail, you are left with the old-fashioned way: human intervention. Humans make mistakes, bad assumptions (they may think a file is still used even though it isn't because somebody *else* made a change), and yes even sometimes choose to intentionally leave irrelevant content in the game as Easter Eggs. It's just natural human fallibility that leads to this.

It's *usually* not a sufficient amount of content to really move the needle much for load or file size optimizations. There are also tools for reporting the largest or slowest assets in any large build chain or engine, but the focus there is to reduce the impact of the major offenders and not find and locate every single wasted byte. Usually.
> 34 votes

# Answer
What's missing in the other answers is that this has nothing to do with games. It affects all applications.

There are always files, and code that isn't going to be used in any reasonably complex program. This happens because of the following 2 things:

* Programs evolve over time.
* It's requires effort to figure out if some piece of code or some file is no longer being used.
    + If you remove stuff without spending said effort, the behavior of the application becomes unpredictable
> 9 votes

# Answer
Adding to/ehancing Uri Popov's answer:

3. Programs may install updates packages that contain new, improved versions of existing asset files and an update to the program itself. For my part, I do not overwrite previous versions of the asset files, because I want to allow a fallback to an earlier program version (imagine, for example, the panic of having distributed a totally disastrous update :-)). The original program version may be using texture\_0.dds and the updated one texture\_1.dds (hence texture\_0.dds is no longer needed). Overwriting (using a single name only) would prohibit a removal of the program update, i.e., the fallback to the original version, unless there was also the tricky mechanics of overwriting newer asset files with older ones. And that is not something anyone wants to support.

Edit:

Reacting on a comment to the original question,

> Nobody remembered to delete them

4. I would say that nobody **dared** to delete them. What happens if the game lacks sufficient error trapping (by mistake, ignorance, error, key-person left the company, etc.) at the loading point of that (now missing) file X, and the problem was undiscovered despite intense testing? Say the loading occurs only "every 3rd time", only at level 35 of 36, which you reach only in 4 weeks of intense gaming :-). Lost reputation by crashing software is a brutal phenomen, and it may in the worst case end up in a bankrupt company. Better not touch that file :-).
> 7 votes

# Answer
> Why do game developers leave old and unused files in the final game?
>
> Surely this just takes up extra space on a disc and means more data has to be downloaded if you download the game?
>
> Also, aren't the developers afraid of what people could find?

Game developers leave unused files in the final game because they don't want to spend the effort to find and remove all unused files. After all the games runs just fine with a bit of extra material and time is money. Cleaning up increases the costs (depending on how automatized this happens).

While it takes extra space and means more data has to be downloaded, this is usually not the developers problem and even customers usually do not care much about slightly bigger download sizes.

Not sure if developers need to be afraid of anything people might find? Why should they? As long as there is nothing compromising in the extra files (really bad artwork, jokes about their bosses or the customers, ...) they probably do not care much. Although in some cases they are actually afraid of what players might detect in the assets.
> 3 votes

# Answer
It's been hinted at, but it hasn't been fully touched on by the other answers: it all boils down to cost, and some of the costs are trickier than you might think.

The most obvious cost is that someone has to delete them. Now you could just put an intern on the case and have him go searching through files and whatnot to remove the ones that aren't needed in the actual game. But still, you have to pay for this and, even if you don't (because you're a monster who doesn't pay interns) you still could have had that intern doing something useful like ordering pizza for the dev team, so it still costs you.

The less obvious cost is that the resource you're about to remove was put in for a reason: are you *absolutely* sure that reason is obsolete? Sure, you wrote this code for a demo and don't need it anymore, but is that entirely true? Did you write a useful function that you forgot to migrate to the other libraries? Did Stacey make a really cool graphic for the demo that ended up in the real game? Does an internal simulator still make use of that old level you used for testing?

Making games is a business. Even if it isn't a money-making business, it's still a business with limited resources. Every decision requires a cost-benefit analysis, even if you don't go writing business cases for each one. And the simple fact is that cost of leaving those assets in the game is a slightly larger download, and the benefits are a significantly reduced risk of something blowing up right before release.

All those question marks in the "less obvious" paragraph represent uncertainty. You just don't know. And when you're running a business, you have to trade your unknowns for knowns. And what is known is that the package you built passed testing, even if it has a little bloat to it.

There other potential costs such as information leaks around the development process that could potentially be used to derive hacks, but you made it through the testing process as-is, you shouldn't really be worried about that.

tl;dr: No one will notice a 4% larger download, but they will notice if you broke the game by removing necessary files.
> 1 votes

---
Tags: assets
---


# Question
Title: How can I fire a bullet from an actor's position?
I want to shoot a bullet from an actor.

I know I need a location in space to fire a bullet from, which I've got in the form of a model set as an actor. Now I need to create a new object (in this case, a bullet) with the same starting coordinates as that actor and set its movement direction to be the direction the actor is facing.

(Imagine a gun, a bullet is to be created at the coordinates of the tip of the barrel and the bullet will move forward in the direction that the gun was facing).

I can't figure out how to get the gun to generate the bullet or how to set the speed of the bullet. How can I do that in Unreal?

# Answer
> 1 votes
To create a new actor, you can use `SpawnActor`. It's a member of `UWorld`, so you'll need one of those. `SpawnActor` takes a position and rotation.

Given your character actor instance called `Character` (the one firing the gun), and your custom bullet actor `ABullet`, you could do:

```
UWorld* World = characterActor->GetWorld();
ABullet* Bullet = World->SpawnActor<ABullet>(
  Character->GetActorLocation(),
  Character->GetActorRotation()
);

```

Now you have a `Bullet` you can work with. Actors in Unreal don't implicitly have a velocity property (they derive one from their movement component, if any). To handle velocity for your bullet, either give `ABullet` a velocity property and set it after you spawn (`Bullet->Velocity = FVector(...)`) and then update the actor's position in `ABullet`'s tick function, or attach a movement component, such as `UProjectileMovementComponent` to the bullet actor. The latter is probably the better option.

Note that the above code for spawning the bullet spawns it at the world location of the character actor, which probably isn't ideal. Chances are you really want to spawn the bullet at the end of the character's gun barrel. A simple way to do this is to put a named socket on the character's mesh at the point you want the bullet to spawn, get the actor's static mesh component, and from there get the relative position of the named socket on the `UStaticMesh` object for the character. Add that relative location to the initial position given to the bullet to spawn it at the location of that socket.

---

---
Tags: c++, unreal-4
---


# Question
Title: Why does the Unity manual add "Quaternion.identity" to an instantiated object?
In Unity's documentation you can find an example usage of `Instantiate`:

https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

```
using UnityEngine;

public class InstantiateExample : MonoBehaviour
{
    public GameObject prefab;

    void Start()
    {
        for (int i = 0; i < 10; i++)
            Instantiate(prefab, new Vector3(i * 2.0f, 0, 0), Quaternion.identity);
    }
}

```

Why do they add the "Quaternion.identity" instead of leaving it blank? Wouldn't the engine instantiate the object with the original object's rotation anyway?

# Answer
> 2 votes
Presumably because it is better to be explicit about it rather than implicit.

For example if I saw an Instantiate method that did not take a parameter for Rotation I might assume that this Object could not rotate. This way it is explicit that it can indeed rotate and it is up to the user to specify its rotation and indeed you do say how much you want it to be rotated by, namely the quaternion identity.

It basically comes down to software design and showing a methods contract with its parameters rather than having to look it up in the documentation. In practice though, yes they could have supplied an overload that did not take a rotation but that would add unnecessary bloating to the API.

# Answer
> 4 votes
Well It does instantiate object as it is if you do not provide second parameter i.e information regarding the rotation.

**Setting the Quaternion to Quaternion.identity will effectively set its euler rotation to (0 , 0 , 0) or no rotation. Otherwise the instantiated object will have same rotation as of prefab.Please Check Again**

so if you write

```
tranform.rotation = Quaternion.identity;

```

all x,y,z rotation will reset to zero.

# Answer
> 3 votes
Reading the doc, we can see that if we want to use a *position* (vector3) in the second parameter, we need to supply also a quaternion as the 3rd parameter.

# Answer
> -1 votes
Probably at the Unity developer's view, if position is changed, then rotation has a high possibility to be changed.

So they prefer this way. Anyway

```
Instantiate(prefab, new Vector3(i * 2.0f, 0, 0), prefab.transform.rotation);

```

Still make it no harder than leave it blank.

---
Tags: unity
---


# Question
Title: Aggregated assets from demo projects in UE4
Unreal engine allows you to download demo projects under the "Learn" tab of their launcher.

**How do I access the resources and assets used in these projects in an aggregate form?**

To put it simply, there are textures and meshes and such that i would obviously like to utilize in my projects. These assets do not however seem to be readily available for use in any and all projects. How do i get them all in one place so i can access them?

Thanks in advance.

EDIT: I should note that i am aware of the "Hard way" of doing it, im kinda just hoping there is a better solution...

EDIT: The hard way doesn't seem to be immediately effective... Thinking...

EDIT: It seems that some are able to be directly added to projects, im still working on figuring out how to add these to the viewport. But others (like "a boy and his kite") provide no such option. thinking...

# Answer
You can't really put them in a central place where you can pick and choose from them. You have to copy them into the various projects you want to use them in. That's just how Unreal works (it's methods of packaging and traversing content assume a content root that is project-specific).

*Some* `uasset` files can sometimes be dragged, manually, from the filesystem. This is error prone and tedious, however.

The way you're intended to to it is from the Epic Launcher. Choose your Library tab. This will show you all your project and all your Marketplace-purchased content (under the Vault section). From there, click the "Add to Project" button and select the projects you want to migrate the content to. You cannot add the content to projects with mismatched engine versions.

Another option is to open the project that already has the content, or the sample project for the content if one is provided, right-click the content folder you want in the Content Browser and choose the "Migrate" option to move all the assets to another project of your choosing.

A third option is to create a new blank project and populate that project with all your desired content as above. Then convert that project to a template. That way you can just create a new project that as all the content you want available without having to repeat the hassle more than once.
> 1 votes

---
Tags: assets, unreal-4
---


# Question
Title: Is it possible to use OpenGL purely with C instead of C++?
Is it possible to use OpenGL purely with C instead of C++? I am wanting to make sure there won't be any problems with my using C and not C++. OpenGL does not depend on any C++ libraries right?

# Answer
> 11 votes
Yes, in fact OpenGL is a C library. You can perfectly use it with C.

# Answer
> 0 votes
OpenGL can be used in C. Some libraries can't, though. For example if you want to use GLM you will have to use C++ instead of C.

# Answer
> 0 votes
OpenGL is a C library, which means that it's made with and for C, so of course it works with C. The reason why it also works with C++ is because C++ is actually nothing else than C with some things added so any C code is also valid in C++. So OpenGL uses C code which is also valid in C++, and it doesn't use anything that is specific for C++.

---
Tags: c++, opengl, c
---


title: How to draw an arc between two angles?

text:
# Question
Title: How to draw an arc between two angles?
I'd like to draw an arc between two specific angles. For example, "draw an angle between 0 and 90 degrees" and it will draw only that part of the circle and ignore the rest.

# Answer
> 5 votes
You can define an arc with a radius and start and end angle. Then you simply need to create a series of points to define the arc.

```
List<Vector2> arcPoints = new List<Vector2>();
float angle = startAngle;
float arcLength = endAngle - startAngle;
for (int i = 0; i <= segments; i++)
{
    float x = Mathf.Sin(Mathf.Deg2Rad * angle) * radius;
    float y = Mathf.Cos(Mathf.Deg2Rad * angle) * radius;

    arcPoints.Add(new Vector2(x,y));

    angle += (arcLength / segments);
}

```

This example creates a list of points that define an arc. The arc can be made "smoother" by increasing the number of segments.

Drawing the arc is your choice, you can create a mesh, use the LineRenderer or something like GL.LINES.

---
Tags: unity, geometry
---


# Question
Title: Timing while calling update more than once per frame
**TL;DR: Using a timestep method that calls `update()` multiple times per frame. After an event happens, need to add a wait time before it can happen again. What's the best way to do this so the wait times are always the same across all hardware?**

Lets say that a bullet is spawned every time the player presses the mouse button. If the player holds the button down, a new bullet will spawn every frame (which is obviously WAY too many). The way I always got around this was to create a variable `shotCoolDown` and set it equal to some arbitrary number (usually 60). Then, in the `update()` function, I would subtract 1 from `shotCoolDown` every frame, and only allow the player to shoot if `shotCoolDown` was less than or equal to 0, and then after creating the bullet, set `shotCoolDown` back up to 60. At 60 FPS, this created a maximum of 1 bullet per second. This worked when calling `update()` once per frame. However, I'm now using a new timestep method from this article, which calls `update()` multiple (always different) times per frame. Because I don't know how many times `update()` will be called, I can no longer use my original `shotCoolDown` method.

I've also tried comparing the current time to the time at the mouse button press, and if the difference is more than 1000 ms (1 second), spawn a bullet. However, this doesn't exactly work. Since the computer's clock continues to tick while the game is paused, the player can simply shoot, pause the game and wait for the limit to pass, then unpause the game and shoot again.

Is there a better way to add these time limits? I know I can use timers, but some of my limits will be as small as 1/10th of a second; I'd rather not use a timer for such a small period of time.

# Answer
> 0 votes
First, stick with your `shotCooldown` variable but set it to (for example) `1000 ms`.

Next, create a clock class. Your clock class only needs to store a tick count and have a method that when called, returns the time elapsed by subtracting the old tick count from the new tick count, and then updating the old tick count to be the new tick count. Call this method every frame/update.

By using the time elapsed, you can update your `shotCooldown` variable every frame/update.

Now, to get around the pause problem, you simply have to not update your cooldown variable while the game is paused. (Your clock will still be updating during the pause.) This works because the clock is not returning the absolute time that you're getting from SDL\_GetTicks but the time delta instead.

Hope that helps

# Answer
> 0 votes
Generally speaking, for any graphics/game/physics library, there will be some way to get the amount of time that has elapsed since the last render/update call. That article that you mentioned looks like it's basically explaining how to implement this... but the overall idea is simple: just call `SDL_GetTicks()` with each iteration of whatever main application loop your engine is running, and calculate the difference between the current call and the value from the previous iteration. This value is what you should use to determine everything time-related: timer increments, animations steps, physics simulation steps, etc.

You don't want to rely on "number of times update/render has been called" because, as you alluded to in your question, that is prone to changes in FPS, which can vary wildly. If you want to only be able to fire "X bullets per second," you need the actual time difference since the last bullet was fired, not the frame count.

Hope this helps.

---
Tags: timing
---


# Question
Title: Unity Capture And Display Live Camera Feed
I want to display the video using the device camera on specific part of the screen on iOS, android and Editor. I was able to find the WebCamTexture which display the camera video on the Quad (3D Object). Now I want to record the video and save it on the disk. Is there are way to do that ? Or is there a better way to do that using unity or through plugin ?

# Answer
> 0 votes
There are some assets available for this. With the free one you have to do it little technically, the second one in this list is straight forward I guess. Check them out.

1. **Free solution:** https://www.assetstore.unity3d.com/en/#!/content/16005 (EveryPlay). This records the screen so what you can do is record your screen while making the video, then save this.
2. **Paid Solution:** Also there is a paid plugin out there in Unity asset store that records and save recorded video https://www.assetstore.unity3d.com/en/#!/content/19682

---
Tags: unity, android, ios
---


# Question
Title: Configurable Dice Cup Sound Effect for HTML5 Game
I am developing an HTML5/javascript based game, where the players will have to roll virtual dice. I am working on a 3d model of a dice Cup and plan on having the users shake it and turn it upside down in order to roll the dice. I would like some realistic sound effects to go along with this interaction, but do not know how to achieve this. The problem is that the number of dice, the duration, intensity and speed of the dice cup shake will vary. Consequently, I don't think I will be able to create a convincing sound experience by using a prerecorded sound effect. How does one deal with making such sound effects configurable?Would I need to programmatically generate the sound using the web audio API? If so I would be grateful for any pointers as to how to do it.

# Answer
# The easy way out

You can always (assuming there is a maximum number of dice in a cup) record multiple sounds (one for one dice, two for two dice, etc.), then play them with the volume lower or higher depending on the shake strength.

Depending on your experience and time, I'd go for this solution. It's easy to implement and because you're not actually simulating / showing the inside of the cup, probably good enough.

---

# Generating the sound

If you're set on **generating** realistic sounds (or at least more / different sound when more dice are present), I'd suggest you use the *AudioContext* JavaScript API and 'simulate' the dice sounds inside the cup.

Depending on the reality that you require, you can do something like this:

* For each dice in the cup, add an audio node with the sound of a dice hitting the cup side (*thud*). These can be played at semi-random intervals.
* For each dice pair, add an audio node with the sound of the dice hitting each other (*clicking*). 'For each dice pair' might be a little much, so try different number of nodes. These can also be played semi-randomly.

The trick here is to determine when to trigger a sound node (semi-randomly). This is really a trial-and-error thing, but shouldn't be too hard (and since you're not simulating the inside of the cup, you can keep it easy).

Then, with the shaking strength, adjust the volume of these nodes. You can do this by connecting them to a **gain** node and setting the gain lower or higher depending on the shake strength.

For the 'fade out' effect (that is, when you shake a cup with dice, and stop, the dice keep bouncing for a little while longer), you can manipulate the gain node to fade out after some time (or use a function for a smoother curve). Of course, triggering less and less audio nodes makes it even more realistic.

## Afterwards...

You can even use this system after the dice leave the cup; triggering *clicking* when dice hit each other (you simulate this, so you **know** when to trigger those nodes) while rolling from the cup on to the board.

Hitting the board requires some more nodes with a sound, but this works the exact same way.

### More on AudioContext

The AudioContext API has a lot of other neat features for manipulating the sound, and I'm sure you can hook up some nodes that actually create the 'duller' sound of dice in a cup. That means you can actually record the sound of dice yourself and simply use the API to modify them in code.

I highly recommend you check out this HTML5 rocks article, which explains the details of what I've written here (with images! And live examples!). In case this is all a little much, you can always use a library; there are plenty to go around. Depending on the abstraction it provides, the points above still apply.

---

# Hybrid solution

You could use the pre-recorded audio when shaking the cup, and actually generating (with *AudioContext*) the sound when you simulate the throw. This has the advantage that the audio exactly matches the physical simulation, and keeps the system simpler because you're not writing an audio simulation for the dice shaking in a cup (which you can't see anyway).
> 1 votes

---
Tags: javascript, audio, sound-effects
---


# Question
Title: OpenGL: Does it make sense to use an Index Buffer With GL_TRIANGLE_FAN?
When trying to draw circles in webGl (You can answer the question even in openGl terms, I'll understand both), I came across the TRIANGLE\_FAN flag when calling either glDrawArrays (with only a vertex buffer) or glDrawElements (with a vertex and index buffer). Since TRIANGLE\_FAN expects the first point to be the 'hub" or "center" of the polygon and all other points are the outside points. So, the first thing that came to mind is to break out of my index buffer habit, as there seems not to be a lot of data that can be saved. But, does it make sense to use an index buffer in my case? Can you even use one? Which one saves more data and is more efficient? Any feedback would be appreciated. \- Thank you

# Answer
It could possibly make sense if you try to draw something like a huge polygon, or some sort of sphere, where the edges connect. This is really inefficient, since the index buffer is most probably going to be bigger than the saved space, but it is possible.

Conclusion: It is possible, but doesn't make sense for any to me known application.
> 2 votes

# Answer
You're generally better off using plain triangles and an index buffer to draw multiple fans (and other shapes) in a single draw call.

It's easier on the GPU/driver in terms of draw call and some drivers/GPUs have to break down the indexed fan into indexed triangles before drawing by regenerating the index buffer on the fly.

The small amount of memory space saved may not be worth the extra work the driver/GPU has to do.

Same applies to quads and indexed triangle strips.
> 1 votes

---
Tags: opengl, opengl-es2, webgl, vertex-buffer, index-buffer
---


# Question
Title: How do you create a grid using a wire-frame shader?
So I'm having trouble going about creating an 80s neon color grid wire-frame, like the examples.

How would you go about making the floor into an 80s styled grid floor? I'm just looking for square grids.

Here is what I'm currently using

```
Shader "Custom/Grid" {
  Properties {
    _GridThickness ("Grid Thickness", Float) = 0.01
    _GridSpacingX ("Grid Spacing X", Float) = 1.0
    _GridSpacingY ("Grid Spacing Y", Float) = 1.0
    _GridOffsetX ("Grid Offset X", Float) = 0
    _GridOffsetY ("Grid Offset Y", Float) = 0
    _GridColour ("Grid Colour", Color) = (0.5, 1.0, 1.0, 1.0)
    _BaseColour ("Base Colour", Color) = (0.0, 0.0, 0.0, 0.0)
  }

  SubShader {
    Tags { "Queue" = "Transparent" }

    Pass {
      ZWrite Off
      Blend SrcAlpha OneMinusSrcAlpha

      CGPROGRAM

      // Define the vertex and fragment shader functions
      #pragma vertex vert
      #pragma fragment frag

      // Access Shaderlab properties
      uniform float _GridThickness;
      uniform float _GridSpacingX;
      uniform float _GridSpacingY;
      uniform float _GridOffsetX;
      uniform float _GridOffsetY;
      uniform float4 _GridColour;
      uniform float4 _BaseColour;

      // Input into the vertex shader
      struct vertexInput {
          float4 vertex : POSITION;
      };

      // Output from vertex shader into fragment shader
      struct vertexOutput {
        float4 pos : SV_POSITION;
        float4 worldPos : TEXCOORD0;
      };

      // VERTEX SHADER
      vertexOutput vert(vertexInput input) {
        vertexOutput output;
        output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
        // Calculate the world position coordinates to pass to the fragment shader
        output.worldPos = mul(unity_ObjectToWorld, input.vertex);
        return output;
      }

      // FRAGMENT SHADER
      float4 frag(vertexOutput input) : COLOR {
         if (
          frac((input.worldPos.x + _GridOffsetX)/_GridSpacingX)
            < (_GridThickness / _GridSpacingX)
             ||
          frac((input.worldPos.z + _GridOffsetY)/_GridSpacingY)
            < (_GridThickness / _GridSpacingY)) {
          return _GridColour;
        }
        else {
          return _BaseColour;
        }
      }
      ENDCG
    }
  }
}

```

# Answer
Use a texture like this one:

* Create a grid in your favorite paint program.
* Apply a blur filter.
* Cut the texture to contain just 1 tile.

In Unity:

* Create a material
* Assign that texture to the material
* Set the material properties to repeat the tile how many times you want
* Apply the material to an object such as a plane.
> 1 votes

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


# Question
Title: How to rotate actors around the actor like a satellite around the earth?
**I'm not a pro in LibGDX and physics but I know basics, vectors, actor's actions and so.**

I'm trying to achieve a movement like on the gif below:

For now, let's say that I have a stage and a central actor that the moon and comet will rotate around.

The problem is here that I have no idea if this is achievable with 2D. Should I implement some sort of 3D in LibGDX?

Also, is there a way so these objects move in a 'random' path, not the straight line like the comet below? (Moon is a little bit randomized)

I know that this question is too broad, but I really didn't know where to ask about this. I'm here to learn cause I always wanted to build a thing like this. I personally think that this is achievable with LibGDX's actions cause I saw something similiar somewhere.

If someone could point me the way I would be grateful :) Thanks!

# Answer
> 4 votes
Well its a type of circular motion but with planets or satellite circular path is changed into elliptical path. Look at the picture below.

It is easy to implement all you have to do is:-

**Add a continuous force on satellite or any object you want to move around.** **And The Direction of force should be towards the center of Planet**

Suppose p1 is the position of satellite and p2 is the position of planet then direction will be p2-p1.

its implementation in unity3D:-

```
using UnityEngine;
using System.Collections;
/// <summary>
/// This script is attached to that object around which another object will rotate
/// </summary>
public class Spin : MonoBehaviour {
    public float maxGravitationalFieldDistance;
    public Transform satellite; // This is refrence of our satalite
    public float Fnet;      //
    public float velocity;

    private float radius;

    void Start()
    {
        radius = Vector3.Distance(transform.position, satellite.position);
    }

    // Update is called once per frame
    void Update () {

        MoveSatellite();
        ApplyForce();
    }

    void MoveSatellite() {
        // satellite will move
        satellite.transform.Translate(SetSatelliteMoveDirection(false) * velocity * Time.deltaTime);

    }
    void ApplyForce()
    {
        if (radius <= maxGravitationalFieldDistance)
        {
            //p2 - p1 (direction of force is always towards the center of planet)
            Vector3 forceDir = transform.position - satellite.position;
            forceDir = forceDir.normalized;

            //Apply force (it depend upon the mass of satellite so adjust mass of satellite carefully)
            satellite.GetComponent<Rigidbody>().AddForce(forceDir * Fnet * Time.deltaTime); // constant force
        }
    }

   Vector3 SetSatelliteMoveDirection(bool tengintial = true)
    {
        if (tengintial)
        {
            //cross product tengintial direction
            Vector3 Direction = (Vector3.Cross((transform.position - satellite.position), Vector3.forward)).normalized;
            return Direction;
        }
        return Vector3.right;
    }

}

```

# Answer
> 0 votes
You could try to rotate it from the exact position of the actor you want it to rotate around and set the offset.

In the matrix multiplication you just have to transform it after rotating it (so inversed matrix multiplication).

I hope this was helpful. :)

---
Tags: libgdx, 3d, rotation, orbit
---


# Question
Title: Multiple bodies or multiple fixtures for a wall in Box2D?
I am making a game with a sort of "playfield" where the game takes place, acting as boundaries on a top-down shooter. I am using Box2D for physics, and I am questioning which of the following would be the most efficient. One option would be to have the playfield represented by a single static body, with four fixtures attached to it (top, bottom, left, and right walls). The other option would be to have four static bodies, one for each border fixture. Which is the fastest for Box2D to process?

# Answer
> 0 votes
I know this is probably late but an answer can be found here: https://stackoverflow.com/a/21172599.

"It is faster to attach several shapes to a static body than to create several static bodies with a single shape on each one. Internally, Box2D sets the mass and inverse mass of static bodies to zero. This makes the math work out so that most algorithms don't need to treat static bodies as a special case."

---
Tags: libgdx, box2d
---


# Question
Title: Player Controller not working with rotation?
I have created a player character controller. It rotates first time good but not after rotate to its original position before rotation. I am sharing code with you so any one can help me, How can I rotate character controller to 60 on Z-axis and again back to 0 degree on Z-axis?

```
void Update()
{
    var inputDirection = inputDetector.DetectInputDirection();

    if (Input.GetKeyDown (KeyCode.Space)) {
        moveDirection.y = JumpSpeed;
        anim.SetBool ("RunToJump", true);
    } else {
        anim.SetBool ("RunToJump", false);
    }

    if (Input.GetKey (KeyCode.S) && controller.isGrounded) {
        anim.SetBool ("RunToSlip", true);
        controller.transform.Rotate (0, 0, 60);
        Invoke ("StopSlidding", 0.1f);
     }
  }
   void StopSlidding(){
   anim.setbool("RunToSlip", false);
   controller.transform.Rotate(0,0,0);
}

```

First `controller.transform.Rotate(0,0,60);` works fine but second time I invoke `StopSlidding` method `controller.transform.Rotate(0,0,60);` It doesn't work. So my player character controller remains same on Z-axis 60 degree. I want to rotate it again to Z-axis 0 degree. So Any one can help me on this problem? My player starts moving with game scene start so there are no matter about moving player. I am using `Controller.Move();` to move my player.

# Answer
Because you are telling it to rotate by 60 on the Z axis, and then the 2nd time you are telling it to rotate by 0 (no change).

Either change your 2nd to (0, 0, -60) or use transform.rotation instead of transform.Rotate()
> 2 votes

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


title: when to do A* pathfinding?

text:
# Question
Title: when to do A* pathfinding?
I'm trying to build my first game, a really simple RTS like Age of Empires but I have a question about pathfinding.

**When** do this kind of games usually do pathfinding?

I've read some games do a global pathfinding once at game start but I'm not sure if that will fit this kind of games.

Do they usually calculate pathfinding each time a game entity starts a new task and has to move?

How do they handle when a obstacle suddenly appears on the path? Do they re-calculate pathfinding on every step? Or do they check if the current path is clear on every step? Or they just walk the current path until they actually hit the unexpected obstacle?

Actually if you know a link to a source code of pathfinding on some RTS game I would really appreciate it.

Thanks in advance

# Answer
There are many ways to make pathfinding work..

Given AoE as example you will likely:

* build a path each time a unit should go somewhere
* check every next step and if it is impassable (e.g. blocked by a house) - rebuild path
* check every next step and if it is blocked by another unit - do a quick side-step around it or wait a bit for it to walk away (cos units are small and mobile)
* maintain areas connectivity map, to quickly discard pathfinding between unconnected areas on the map
* use hierarchical pathfinding if you plan to have large maps
* maintain a heat map and let units prefer paths over less used areas
* schedule pathfinding across several ticks (or even move to threads) if you plan to have massive amounts of units
> 1 votes

# Answer
Well it depend upon the situation all thing you have stated above happen, it depend upon your game or project. if you do not want processing every time to get high frame rates you just do path finding few times or if your game environment is static you don't have to use path finding every time. if your environment is dynamic i.e object moves then you have to use path finding frequently or you can detect if there is an obstacle and then take another path and follow A\* path later.

You can view this nice tutorial on A\* pathfinding:-

https://www.youtube.com/watch?v=-L-WgKMFuhE&list=PLFt\_AvWsXl0cq5Umv3pMC9SPnKjfp9eGW

watch the tutorials first and then you can use the below scripts that I have created watching the tutorial with minor tweaks https://www.dropbox.com/sh/6r5o8u8vmcwyscx/AACAoqEK33qweGmm8uxcu57Ja?dl=0
> 1 votes

---
Tags: path-finding, rts
---


# Question
Title: Best strategy on VAO and texture coordinates for voxel rendering?
I'm working on a game that has to render a large amount of cubes (voxels) with OpenGL. All cubes have the same geometry (so I can re-use the vertex position VBO) and a single sprite sheet texture is used for all of them. This means the texture coordinates will have to vary for the cubes, depending on which sprite to use. All six sides of a cube will use the same sprite (in other words, the same texture coordinates).

**Now, what is the best strategy to approach this with a modern OpenGL renderer?**

I came up with two possibilities:

1. Create as many VAOs as there are cube sprites in the sprite sheet. Bind the same vertex position VBO to all of them, but a different texture coordinate VBO (according to what sprite / part of the texture to show). In my specific case, this would make for about 600 different texture coordinate VBOs and therefore 600 VAOs.
2. Create only one VAO. Set up the texture coordinate VBO in a generic way (e.g. `0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0`). In the rendering loop, send the actual texture coordinates (only 4 values) as uniform variable to the shaders. In the shader, the generic texture coordinates can be used to figure out which two of the four values from the uniform should be used.

Are there other possibilities that I'm missing? What is best regarding performance?

# Answer
> 1 votes
With modern OpenGL, you can solve this elegantly by using instancing and texture arrays.

**Texture arrays**
Please see https://www.opengl.org/wiki/Array\_Texture for an overview.

Using a texture array you can retain the same texture coords for all faces in all cubes (i.e. `0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0`) with the only thing you need to specify any differently being which array slice to use. That's where instancing comes in.

Using a texture array also allows you to properly implement mipmapping and texture filtering without having to worry about adjacent textures bleeding into each other, or other issues you typically hit with sprite sheets (which are *very* OpenGL 1.1).

**Instancing**
Please see https://www.opengl.org/wiki/Vertex\_Rendering#Instancing for an overview.

Because it's part of your design that "All six sides of a cube will use the same sprite (in other words, the same texture coordinates)" you're ideally set up to use instancing. Each cube is an instance, and the array slice is set up as a per-instance vertex attribute, then passed from the vertex shader to the fragment shader for to do the texture lookup.

As an alternative to instancing, you could also send the array slice as a standalone glVertexAttrib1f call, but at the expense of having to make a separate draw call per cube instead of being able to handle all cubes in a single draw call.

---
Tags: opengl, voxels, vbo, texture-atlas, vao
---


title: Reseting animation

text:
# Question
Title: Reseting animation
I'm writing little fps game in Unity 5.3.5. So, I've got my gun object and two animations, idle and shot. I've got transition from idle to shot with trigger condition and "Has Exit Time" unchecked. In the idle animation after few seconds gun do some cowboy-style spinning. Problem is, when I fire my trigger during the spin, shot animation starts exactly from point where idle animation was interrupted, which causes shooting to the sky or to the ground.

I know i can make no transitions and do everything from code, and reset every animation to start position before playing another, but is this elegant way to do such a thing? Are there any good practices someone could share with me?

# Answer
> 1 votes
Ok, I think I figured this out. Disabling root motion made my gun act properly. I'm surprised, because i thought that if I would turn this option off, gun will stuck in his base position on map, like global 0,0,0. Surprisingly, it's transform is properly inherited from parent object.

# Answer
> 0 votes
Reduce `transition duration` of the intended transition.

---
Tags: unity, animation, first-person-shooter
---


# Question
Title: How does Vector3.MoveTowards work in Unity?
What I mean is that I don't understand what each part does, like in the example in the API, it didn't give much on what did what! I kinda need this for an aim script in a shooter game I'm working on. Any help will be good, but a direct answer would be great!

# Answer
You would use the function if you need to move an object towards a specific position that you know. The function takes in the current position of the object you want to move, the target position you want to reach, and the distance that you want to move towards the object.

So, if for an example you had an object at position (0, 0, 0), and you wanted to move it to the position (0, 7, 0), 2 units at the time, the function translates the position first from (0, 0, 0) to (0, 2, 0), then to (0, 4, 0), then to (0, 6, 0) and finally to (0, 7, 0). Notice, that in the last step, only one unit was moved. That way, you can safely call the function with values that don't happen to match up at some point.

Now, `Vector3.MoveTowards`, can be used for a broad set of things, but for a basic example you could use it to move your player to where the user has clicked their mouse. The Unity docs link shows a very basic example, including a description, which should tell you enough about the usage (you could also try the script out, debug it and see what values get assigned and when).

You would simply feed in `transform.position` as the first parameter, the click position as the second position, and a suitable speed as the final parameter. I'm not an Unity user, so I can't suggest a speed to use off-hand like this. Try out a few different values and see which feels good.

At the basic level, similar functionality can be achieved using a more basic linear interpolation, however this utility function guarantees that you will hit your target and the usage here is quite simple and easy.
> 2 votes

---
Tags: unity
---


# Question
Title: What is wrong with my Item collection/Itemcounter Script
So I am making a script for item collection and a counter for it. I have a script made but for some odd reason I can't seem to the get the GUI part right. The compiler error says something like "This isn't a member of UnityEngineGUI" IDK what I am doing wrong. Could someone help out?

```
#pragma strict
var Collectable : GameObject;
var Counter : int;
var CounterGUI : GUI;

function OnTriggerEnter (other : Collider){
    if (other.gameObject.tag == "Player"){
        Collectable.SetActive(false);
        Counter += 1;
        CounterGUI.GUI = Counter.ToString();
    }
}

```

# Answer
> 1 votes
You need to call `OnGUI()` in old system.

```
function OnGUI ()
{
    GUI.Label (Rect (10, 10, 100, 20), Counter.ToString());
}

```

If you use new UI system, you will need to update the `text` component of the `Text` UI object. No need of `OnGUI()`.

```
CounterTextGUI.text = Counter.ToString();

```

# Answer
> 0 votes
It could be that it's not reacting to the tag of the player. Javascript does it all the time to me. The easiest fix is to have this: If (other.gameObject.name == "//name of player object in scene//") { //rest of code follows... }

---
Tags: unity, javascript, software-engineering
---


# Question
Title: Plane won't move with transform.Translate
Code:

```
    void Update () {
    transform.position += transform.forward * 0.1f;
    float temp = Input.acceleration.x;
    float z = Input.acceleration.z;
    float x = Input.acceleration.x;
    float y = Input.acceleration.y;
    //Debug.Log (temp);
    transform.Translate (0,-y * speed * Time.deltaTime, 0);
    transform.Translate (-x * speed * Time.deltaTime,0, 0);
    transform.Rotate (0,0,-temp * speed);
}

```

The rotation seems to work fine, but when I tilt the phone, nothing happens to the plane's position in space. What's wrong?

EDIT: I know there are some silly aspects to the code, just bear with me while I debug it.

I also think it has something to do with the plane's constant velocity in the top of the code, but I don't know how to make it move with a constant speed forward but still let the user change the Z-Y coordinates via tilting.

# Answer
> -1 votes
Instead of trying to have some crazy math to move the plane, try it first with a set speed whenever you tilt the phone. Then, try adding a if and else if that changes the speed depending on the angle of tilt. I've always seen that it's easier to build on to a script than to do it as complex as possible first.

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


# Question
Title: Object moving in a hollow pipe, want collision detection, how do I do that?
Do I need to add a rigidbody and sort the collider to fit to both the pipe and the object? I'd like the game to end if the object touches the pipe.

I've only seen sphere and box colliders. How would it work with a hollow pipe?

# Answer
> 3 votes
Let me start by stating the assumption that you have imported a mesh to use as your hollow pipe. If this is not what you are currently doing, it will either not work, or be far more complicated than it needs to be. This answer might be a bit more in-depth than you were looking for, but I feel it is more important to explain the *concepts* behind what your wanting to do, in order to greatly expand what you can actually do with your game.

### Setting up the `Collider` on your hollow pipe

The first thing we need to do is add a collider to your pipe. We can not use the generic `CapsuleCollider`, as although it fits the rough shape, it does not give us the hollow center we need to move the player.

You want to add a `MeshCollider` component via the inspector. With your hollow pipe selected, scroll to the bottom of the inspector, and select "Add Component". From here, you can look at all the possible components you can add to your game object. This is very useful for seeing what is available, as alternates or in general. For example, if you type "collider" in to the search bar, it will show you all the available `Collider` components. We want to select "Mesh Collider".

Assuming you have a `Mesh` attached to your game object (the model of your hollow pipe - set this up, first!), the `MeshCollider` should automatically store a reference to it under its *Mesh* parameter. While the default is to use the same mesh used to render the game object, you can change the `MeshCollider` to any other mesh you may have. We won't need to do this, now, but it is useful to know. For example, if you were to create a complex character model, you could save a copy containing far less polygons to use as the collider. This would make collision easier to manage, as Unity would be dealing with a less-complex shape.

You will also want to ensure that both *Convex* and *Is Trigger* are left unchecked, although you should not be able to check *Is Trigger* unless *Convex* is already checked. This tells Unity that this collider will enforce collision detection, and force other colliders (the player, for example) to bounce off it. You don't necessarily want this behavior, but it prevents the player from clipping through the pipe in ideal circumstances, so it goes towards quality improvements.

### Setting up the player

The player will also need a `Collider`, but we can leave it up to you to decide what type fits best. Again, ensure that no matter what, *Is Trigger* is not selected. You will also want a `RigidBody`. It is important to note that a `RigidBody` is required on at least *one* of the game objects involved in a potential collision. Without it, Unity will not detect a collision. Since `RigidBody` also manages the physics side of things, you will probably already need to have one on the player. Apart from that, it is usually best to place it on the *moving* object, if you are not entirely sure what side to implement it on.

*If you find yourself having to place a `RigidBody` on a stationary object*, you can use the *Constraints* fields at the bottom of the component view to lock movement and/or rotation along the X, Y and Z axis. You would probably also want to ensure *Use Gravity* is deselected. Again, none of this should apply to this example, but it is good to know.

### Handling the collision

As far as basic collision goes, that should pretty much set you up. Assuming you are not going at crazy speeds, your character should "bounce off" the hollow pipe. But how do you set the game up to react to the collision with "Game Over"? Why, with some basic scripting!

Add a script to your player. Any script will do, as long as it still inherits from `MonoBehaviour`. Any script that inherits from `MonoBehaviour` will have a bunch of different functions called under certain situations, and a bunch of them are for collision. You can check them all out at the Unity API; it is ***extremely*** helpful, and will definitely broaden your horizons on exactly *what* you can react to in your code.

There are two types of collision you will generally handle events for, in 3D; `OnCollision` and `OnTrigger`. Remember how we made sure our colliders were not set to *Is Trigger*? Trigger collisions, where we want to know if an object is within a certain area but do not want to force physical collision, is handled differently to physical collisions. They also take in different information;

* `OnCollision` takes in an actual `Collision` object, which represents the collision, itself. From this you can derive the other game object involved, as well as other information, such as the point of contact and the applied velocity.
* `OnTrigger` takes in just the `Collider` of the object we hit, itself. In context of using `OnTrigger`, we do not need to know about the other stuff. We only really want to know *what* we collided with.

There are also *three* different events for each of these collision types. It might sound confusing, now, but with practice you will see how it all comes together. If you are familiar with input, and the likes of `GetKey`, `GetKeyUp` and `GetKeyDown`, it is the same principle.

* `OnCollisionEnter` | `OnTriggerEnter`: calls on the **first** frame where the collision occurs. You would put code here that you wish to carry out *the instant* there is a collision, but would not wish to repeat itself *for each frame* where there is collision. A player initially receiving a buff for touching a magic fountain, for example.
* `OnCollisionStay` | `OnTriggerStay`: calls on every frame where there is collision **after** the first frame. You would put code here that you wish to repeat for as long as there is collision. A player slowly taking damage while they are touching a spiky obstacle, for example.
* `OnCollisionExit` | `OnTriggerExit`: calls on the frame where the collision has first **ended**. You would put code here that you wish to carry out on the first instance where there is *no longer* collision.

You are looking for the `OnCollisionEnter(Collision collisionInfo)` method. Simply set up a simple script, as follows, and work your way from there.

```
using UnityEngine;   // we are using the UnityEngine library

public class Player : MonoBehaviour   // Our player script inherits from MonoBehaviour
{
    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log("Colliding with " + collisionInfo.gameObject.ToString();
    }
}

```

### When things get more complex, manage your collision with tags

One final word of advice: *as you describe*, you initially have a very simply game. A player and a hollow pipe. Eventually, maybe even already, you will have a lot more objects. Some of them will also have colliders, and you may not want to have the player automatically die when they trigger `OnCollisionEnter` with *every* non-trigger collider at play. This is where *tags* come in. You can read up on them via the Unity Manual, but basically, you can give objects unique tags and look for the tags in the collision code with `collisionInfo.gameObject.tag` or `collider.tag` to determine *exactly* what it is you have collided with.

# Answer
> -1 votes
Put a `RigidBody` and respective `Collider` on the object you want to move around. Then, put a `MeshCollider` on the pipe. These can be selected from the component button. Then, add physics whenever you click on an object.

Afterwards, hit play and watch it go through the pipe! Note that the pipe doesn't need a `RigidBody` to have it collide with the moving object.

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


# Question
Title: General Octree question: What do you actually store?
Ok, So I'm experimenting with various terrain generation methods, primarily in Unity, but i'll admit to not use all its features because I started learning about Game Dev in XNA YEARS ago. So, I made a blocky setup like minecraft several times, and made it ineractive. Kool Beans... I did it in chunks, not an Octree method. I've also had a broken version of Marching cubes, but it really wasn't broken, it made the look I was going for at the time.

So I've never really worked with Octrees, and I started reaseaching Dual Contouring and Surface Nets, and a lot of em talk about Octrees. I get the idea logically, but I kinda don't understand some basic "Mechanics" of Octrees, and finding "basic" answers to some of these topics is rough.

So, sticking really to just Octrees, what kind of data to really store in em? I mean, I get I literally could break up a 3D array of strings, but I'm asking about best practices and practicality. I've been using an array of bools generated by another object, really because I'm really trying to make something that does more "computing" than "hashing", and I was thinking bools would be the smallest type to store if I'm going to "blow it up" with other techniques.

So, when I first create this bad boy, and give it a 3D array of data, Do I really go through a method of recusivly testing each value before I "break" the "Master Node" into "Children nodes"? Or Do I start by testing each value in pairs, building Up to larger children nodes?

Any other pointers would be appreciated.

# Answer
> 2 votes
Octrees store data, indexed by a 3 dimensional position. That data could be a reference to an object, reference, bool, or whatever you need.

Inserting items into an Octree is typically done from top down. You have a maximum number of items per cube, once that maximum is reached, the cube is split into 8 (hence the oct prefix in Octree). When splitting, the items from the parent cube is distributed into the 8 new children (octants). If you know you're going to have a large number of items inserted right off the bat, you can pre-allocate the Octree with an initial depth of nodes. Pre-allocating can speed things up when inserting items, since there's a performance hit when splitting a parent and reinserting its items.

However, balancing node max item count and depth is something you'll have to test out for your needs. The balancing is between adding new items and finding existing items. If you don't have a lot of depth, adding new items is rather fast. However, that means you'll have more items in each node and that means searching through all those items when trying to find items closest to a specific position.

Best thing you can do is to implement an octree and play around with it. Hook up some performance indicators so you know what effect your changes are making. Get a good idea of how you're going to use it. In reality, using an octree for a minecraft-esq voxel game is overkill. Since cube voxel positions are exactly predictable, it would be much faster to implement a chunk-based index to a specific cube, instead of using an octree to locate the cube.

---
Tags: data-structure, terrain-rendering, octree
---


# Question
Title: Box2D: How can I speed up a physics simulation with many, many overlapping box bodies?
I'm new to physics libraries and am trying to use Box2D to help implement the procedure described in this article: http://www.gamasutra.com/blogs/AAdonaac/20150903/252889/Procedural\_Dungeon\_Generation\_Algorithm.php

(Edit for clarification:) The algorithm involves rectangular bodies of random dimensions being created in a random point in a circle. They are meant to intersect initially and have those intersections resolved by the simulation, so as to evenly distribute the bodies.

I've managed to get the algorithm working but it runs extremely slowly. Even with only sixty bodies to distribute, it takes over thirty seconds for all intersections to be solved and the bodies to return to sleep. For 120 bodies, it takes well over three minutes, which is horrendously slow.

The simulation progresses quickly when many bodies are overlapping, but slows down dramatically as the area becomes increasingly crowded with bodies. I suppose each body must have more work to do, in an abstract sense, to push an increasingly large number of bodies and interlocking rows of bodies out of the way.

I've tried making each body 0.00001f units in density (therefore lowering mass?), I've tried increasing the restitution value of each body and lowering the friction and linear damping values, but the simulation runs at about the same speed. Even multiplying the number of time steps, position iterations, and velocity iterations by ten doesn't seem to do anything.

**So my question is, how can I tweak the simulation or each body's parameters as to greatly increase the speed at which every intersection will be solved?** Accuracy of the simulation is no issue; I am subverting it anyway by rounding the coordinates to the nearest 32 px in the end.

Description of my physics bodies and fixtures:

```
b2BodyDef roomGenBody;
b2PolygonShape roomGenPolygonShape;
b2FixtureDef roomGenFixture;

roomGenBody.type = b2_dynamicBody;
roomGenBody.fixedRotation = true;
roomGenBody.linearDamping = 0.001f; // Seems to have no effect.
roomGenBody.allowSleep = true;

roomGenFixture.density = 0.00001;
roomGenFixture.restitution = 60.0f; // As far as I understand, more bouncy objects repel each other with greater force?
roomGenFixture.friction = 0.0f;

```

Concerning the world and running the simulation:

```
b2Vec2 physicsGravity(0.0f, 0.0f); // No gravity and at no angle.

float32 timeStep = 1.0f / 60.0f;  // Increasing timestep doesn't seem to have a very noticible effect.
int32 velocityIterations = 10;
int32 positionIterations = 8;

physics->Step(timeStep, velocityIterations, positionIterations);

```

Attached is an image describing my problem- Orange lines are the boundaries of my boxes, labelled 1-160:

Please let me know if any necessary information is missing. Thanks!

# Answer
> 1 votes
I was able to come up with a quick solution for you. I tested the algorithm and came across your problem. I found that by increasing the position iterations in the world.step() function and reducing the velocity iterations, the collisions resolve much faster. For 140 rooms it took about 5 or 6 seconds to set all of the rooms to sleep. I set "1" for the velocity iterations and "10" for the position iterations. I also set the fixtures restitution to 0. I hope this helps.

# Answer
> 0 votes
Ok, this may not be a bonafied answer, but its some food for thought.

Have you considered using quad trees? In a nutshell, a quad tree is all your data in a container, that gets smart by breaking itself into smaller containers as needed.

How could this be usefull? Well, it sounds like initiall, all your rectangles are colliding, and pushing themselfs out from the center, and repeating over and over. All your rectangling are "testing" each other every time. We can reduce the numbers of tests by breaking your circle into four parts, and every rectangle test every other rectangle in that part of the circle. It saves your machine from doing tons of extra work.

Hope my "answer" helps.

---
Tags: c++, physics, box2d
---


title: What is used for border parameter?

text:
# Question
Title: What is used for border parameter?
I'm learning OpenGL and have a question. I read about Texturing and found border param in glCopyTexImage and glCompressedTexImage functions. In book: "OpenGL Programming Guide" wrote that border is reserved and must be zero? If it reserved why they place it into parameter?

P.S.: I have one idea, is it used for border texture? Like don't read data below that border, isn't it?

# Answer
In *modern* OpenGL border is required to be 0, but in *legacy* OpenGL it could have had a value of either 0 or 1. A good source of documentation for this, and similar legacy OpenGL quirks, is the MSDN site: glTexImage.

The purpose of a non-0 border is for the GL\_CLAMP texture wrap mode (set via glTexParameter); quoting from the MSDN documentation:

> Border texture elements are accessed only if wrapping is set to GL\_CLAMP

This wrap mode is also deprecated in OpenGL, and the old concept of border texels no longer exists (modern OpenGL instead has GL\_CLAMP\_TO\_BORDER and border colors).

The *border* parameter was, however, retained in glTexImage (and friends) to avoid having to change the API. When the API did eventually change (to glTexStorage) you'll note that there is no longer a *border* parameter.
> 1 votes

---
Tags: opengl
---


title: Grid Pathfinding with known points

text:
# Question
Title: Grid Pathfinding with known points
What is the best way to, in a grid, to find a path (not necessarily shortest) from a start point to an end point (for both of which the coordinates are known)?

The grid is approximately 60x60, and has some obstacles in it. The coordinates of the start point, the end point, and all of the obstacles are known and easily accessible. Searches such as Breadth-first and A\* work, however they seem to do an unnecessarily large amount of "searching" when you should already know where you are going.

# Answer
Grids with known start and end points are the ideal inputs for algorithms like A\*. Especially considering you have some obstacles in your grid. A\*, in fact, would not work if you didn't know the start point, end point and obstacles.

Your program does not know where it's going until you tell it where to go. While it may seem trivial for you to look at a grid and find a path from one point to another, computers have no idea unless you tell them. With the information you've provided, A\* would be ideal for pathfinding.

However, if you don't actually need pathfinding, and just want to *go from A to B*, you don't have to find a path first, you can just start going. You can essentially find the path as you go, with movement that emulates a depth-first search algorithm. Simply head directly towards the goal, if something gets in the way, move left or right to go around.
> 4 votes

# Answer
If you're not concerned with finding an optimal path & want to reduce the searching, tweak your preferred algorithm to bail out when the first path is found. This tweak is pretty straight forward, but keep in mind that you can get some pretty dumb looking answers this way.

Sometimes a hybrid approach is used. For this you start with an optimal path finding algorithm, keep the best path found so far & return that if the search is taking too long.

As suggested by @DMGregory, it's wise to actually check your performance via profiling before customizing / optimizing your path finding. Personally, I wouldn't commit dev time to a hybrid approach unless I knew it was warranted. On the other hand, the bail out approach might actually take less time to develop since only only need to test the result is a legal path & you don't need to test if the result is actually optimal.
> 1 votes

---
Tags: path-finding
---


# Question
Title: finding the angle to launch a projectile at a 3d coordinates
I have a game where the user can shoot a bullet and the bullet flies through 3 dimensional space and eventually hits the ground somewhere. My question is how can I calculate the `pitch` of the angle to make the bullet hit a specific coordinates **with possibly different elevations.**

My known factors are:

* The gravity force
* The initial projectile velocity
* The shooting position
* The target position

In my case I do not need to factor for target movement, I am trying to make something similar to an artillery weapon that fires into the sky and have the bullet land somewhere else at a target. Because I am trying to make an 'artillery-like' weapon I need the weapon to aim up at the sky, not directly at the target.

# Answer
> -1 votes
Ok, I don't have Images to help you, but heres how I would try to tackle the problem.

Your ultimately trying to calculate a parabola. We should start by calculating the distance between the firing point and landing point. I don't know how to adjust for the height differential.

Now, lets talk about the projectile. If we were to track it in the game, technically, along it path, if it were a line going from -x to positive x, and lifting on the y in its arc, we really don't sway left or right on the z axis. so Really, the math problem will boil down to a 2D problem.

So, in 2d, a parabola is basically y2 = x. If y=0, your at the peak, and x =0. But As you go down on the y axis("that's what she said"), technically, both x and -x are possible solutions, a positive one and a negative one.(Again what she said)

To visualize a little more, your position will be one of those two answers, and your target is the other. There are other methods of "changing" the parabola to fit your height scenario, but I want you to try to remember the y2=x part. Its what your doing in a nutshell.

That parabola is the key. Technically, you just need to take a sample of two points on one arc, and translate that into whatever method you use for rotation, like vector or matrix or however other ways you can define an angle. Really, you can make the barrel point at the target, then you add the rotation in degrees.

I would also like to point out though, that modern artillery takes in to account how much force to use when firing the projectile. Technically, you can a variety of angles with different charge to reach many angles. This control may have cool outcomes for a game. Like programming one artillery piece to fire several rounds in succession, that ALL STRIKE SIMULTANIOUSLY! Or could simplify your targeting system. Instead, you give it a angle that is "close" and then calculate how much force to give the projectile. This fact could make your approach this a bit different. For example, you may always want to have a nice curve, instead of some straight up arc that seems to go forever before making a quick U-ey and come screaming back down.

So we can start by turnin your Artillery piece to face the target, then measure how far away, and the difference between heights. If we want to pick the arc, lets say the same one I used as an example(y2=x), we need to find out where we fit on that scale. The mid-point between the two points is where y=0, so lets cut that number in half, and use that as our "y" input in that formula. X could end up being either one, but it doesn't really matter, YOU have your arc and where your stand on it. Now sample the arc from your point towards the center by the length of your barrel, turn those two points into a vector, and theres your rotation. Now you'd have to do some more math to figure out what velocity to use, but really, you only need to calculate how to "hit" the "peak." I'd imagine you have some constant force of gravity, so it will "slow" as it rises at the same rate it will "speed up" as it falls. So that velocity requirement will grow paraboliclly as distance increases, so that distance you measured between each point will be important, so there probably is means of using the same arc formula to figure that out.

All this might also be helpful to consider if you want these items to act autonoumsly, getting optimal rounds per minute on a target under AI control.

---
Tags: physics, javascript, projectile-physics, trajectory
---


# Question
Title: Does DirectX implement Triple Buffering?
As AnandTech put it best in this 2009 article:

> In render ahead, frames cannot be dropped. This means that when the queue is full, what is displayed can have a lot more lag. Microsoft doesn't implement triple buffering in DirectX, they implement render ahead (from 0 to 8 frames with 3 being the default).
>
> The major difference in the technique we've described here is the ability to drop frames when they are outdated. Render ahead forces older frames to be displayed. Queues can help smoothness and stuttering as a few really quick frames followed by a slow frame end up being evened out and spread over more frames. But the price you pay is in lag (the more frames in the queue, the longer it takes to empty the queue and the older the frames are that are displayed).

As I understand it, DirectX "Swap Chain" is merely a render ahead queue, i.e. buffers cannot be dropped; the longer the chain, the greater the input latency. At the same time, I find it hard to believe that the most widely used graphics API would not implement such fundamental functionality correctly. Is there a way to get proper triple buffered vertical synchronisation in DirectX?

# Answer
As mh01 says, DirectX does support a form of triple buffering. It works around one downside of double buffering, which is that with double buffering and vsync on your frame rate drops from 60 to 30 to 20 (assuming 60Hz refresh rate). There's nothing in between because you don't have a free back buffer to render to until after the vsync. Triple buffering allows it to have up to three frames on the go at once:

1. The frame being displayed - the front buffer.
2. The frame to be displayed at the next vsync (one back buffer).
3. The frame currently being rendered (the other back buffer).

I think what the Anandtech article is saying is that if your game is rendering frames much faster than the vsync it would reduce latency if D3D could drop a previously rendered frame. That is, if while one frame is being displayed you manage to render both the next frame and the one after (so you run out of back buffers) then D3D could choose to drop the oldest of those two frames and proceed to render the next frame immediately.

What D3D actually does is to block waiting for the vsync, which reduces CPU and GPU load, but increases latency a little. And it can be worse than that because what D3D does when the CPU is producing frames faster than the GPU can render them is to let the game queue up three frames worth of GPU commands, and then block, giving you more latency.

That three frame CPU queue can be avoided either in the game software (the easiest option is issuing and waiting for queries with the appropriate delay in between), or with driver settings (it's there on Nvidia drivers, not sure about AMD).

The main advantage of that three frame command queue is that if you have more than one GPU then when there's more than one frame in the queue you can give one to each GPU and improve performance. It can also help smooth out an uneven frame rate a bit.
> 5 votes

# Answer
Yes, see D3DPRESENT\_PARAMETERS structure and the description of the "BackBufferCount" member for D3D9, or DXGI\_SWAP\_CHAIN\_DESC for DXGI, for example.

Note that this is not a render-ahead mechanism as described by the AnandTech article; this is managed by a separate API, such as IDirect3DDevice9Ex::SetMaximumFrameLatency or IDXGIDevice1::SetMaximumFrameLatency. Note that in both cases the BackBufferCount (or BufferCount for DXGI) is still set separately during device creation.

I'm not sure how AnandTech managed to get the impression that this wasn't implemented or that it was somehow different, as it has been documented in every DirectX SDK.
> 4 votes

# Answer
The behavior of the Direct3D swapchain has, traditionally, been a FIFO queue. Windows 7 addressed this problem in Direct3D 9 Ex by advancing the read target that the Desktop Window Manager uses for composition each time a frame is presented. It matters not how far behind the GPU is, the DWM always scans-out the most recent finished frame and drops late frames.

This is referred to by Microsoft as the Flip Presentation Model. It is available in Windows 7 in D3D9Ex devices if the Desktop Window Manager is enabled. In D3D11, this feature is part of DXGI 1.2 (Windows 8); it should be available in Windows 7 with Platform Update but I have had very limited success getting that to work.

For games that use neither D3D9Ex nor DXGI 1.2 in order to use the Flip Presentation Model, NVIDIA's recent drivers expose "Fast SYNC" on Pascal GPUs. This violates the D3D sequential presentation design and has to be enabled in the driver because it is not technically correct VSYNC behavior. NVIDIA touts this as a hardware feature unique to Pascal GPUs, but that simply is not true.
> 1 votes

---
Tags: directx, vsync
---