title: Added video to Unity as an asset

text:
# Question
Title: Added video to Unity as an asset
I am unable to run the video. Here is the detailed definition. What should I write to run it?

After moving script file to plane, I get this debug output:

Here is the code on my button which is related to the plane object:

```
using UnityEngine;
using System.Collections;

public class Button : MonoBehaviour
{
    public MovieTexture movie;

    void Start()
    {
        GetComponent<Renderer>().material.mainTexture = movie as MovieTexture;
        movie.Play();
    }
}

```

I am following this tutorial and getting an "Unassigned reference error".

# Answer
> 2 votes
# Docs

The Unity documentation is very good. To play videos in unity you must use a `MovieTexture`

The unity docs provides a lot more information, but I shall summarise it here.

# How to

First import the movie file, this requires QuickTime

> Video files are imported via Apple QuickTime. Supported file types are what your QuickTime installation can play (usually .mov, .mpg, .mpeg, .mp4, .avi, .asf). On Windows movie importing requires Quicktime to be installed (download here).

Then create a material for the movie and drag the movie asset to the texture argument (This albedo in the Unity 5 standard shader)

Drag that material onto the object you wish to show the movie on

Then add the following script to the game object which has the movie material on

```
// Use this for initialization
MovieTexture movie; //This is private as we get the movie texture from the renderer

void Start () {
    Renderer r = GetComponent<Renderer>(); //The renderer will give us access to the material
    movie = (MovieTexture)r.material.mainTexture; //Get the texture and cast it to a MovieTexture

    if (movie == null) //Check the texure exists and is a MovieTexture
    {
        Debug.LogError("There is no movie texture on the material");
        Debug.Break(); //Pause the editor
    }
}

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (movie.isPlaying)
        {
            movie.Pause();
        }
        else
        {
            movie.Play();
        }
    }
}

```

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


# Question
Title: OpenGL Uniform Standard Buffer Alignment confusion
Although i asked the same question over StackOverflow, i thought i can get more info from here too.

I have been reading about std140 Uniform block in OpenGL Superbible 6th edition, where in page 111 the following example is given :

```
layout(std140) uniform TransformBlock
{
      //Member                        base alignment    offset  aligned offset
      float scale ;                   // 4              0       0
      vec3 translation;               // 16             4       16
      float rotation[3];              // 16             28      32 (rotation[0])
                                      //                        48 (rotation[1])
                                      //                        64 (rotation[2])
      mat4 projection_matrix;         // 16             80      80 (column 0)
                                      //                        96 (column 1)
                                      //                        112 (column 2)
                                      //                        128 (column 3)
}

```

I am having hard time understanding the alignments, even using the rules that have described earlier in that page, it still don't make sense.To be specific thing that confuses me is :

1. What is the Offset and what is aligned offset, why 2 different offset?
2. Why is the rotation\[0\] offset starts at 28, and why aligned offset is 32?

Hopefully someone can clear my confusions.I would highly appreciate. Thanks

# Answer
Offset refers to the offset you would have in your original data without adjustment, basically all the sizes added up.

Aligned offset is the actual result on the opengl side.

So in this case vec3 has to be aligned to 16. So the first available spot is actually 16 instead of 0.

```
GLint viewPosLoc = glGetUniformLocation(shader.program, "ViewPos");

GLint lightCountLoc = glGetUniformLocation(shader.program, "lightCount");
GLint dLightCountLoc = glGetUniformLocation(shader.program, "dLightCount");

GLint materialShininessLoc = glGetUniformLocation(shader.program, "material.shininess");

glUniform3f(viewPosLoc, cameraView.position.x, cameraView.position.y, cameraView.position.z);

glUniform1i(lightCountLoc, pls.length());
glUniform1i(dLightCountLoc, dls.length());

glUniform1f(materialShininessLoc, material.shininess);

```

That is a little example code of setting the normals. If you set them one at a time then everything shall work properly and you do not have to worry too much about alignment.

Where this really comes in is when you use a UBO to set a data block all at once. That is because the format of your data in C++ will not necessarily line up to the same positions as your data in OGL and then you get garbage on the other end.

The easiest solution to this is to make sure that your data structures in C++ have the same memory alignments as those in OGL. How to set this is compiler specific but you can always add padding data to get the right result.

For example a vec3 is 12 bytes in C++ because it is 3 floats. In OGL it is aligned to 16. You can either align it to 16 in C++ as well by padding it with an extra float, or by declaring it to be aligned to 16 in your compiler.

Then you can safely use a UBO to fill the whole thing at once.

Here is a basic tutorial on UBOs and buffer blocks:

http://www.learnopengl.com/#!Advanced-OpenGL/Advanced-GLSL
> 2 votes

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


# Question
Title: Do Google Play and the Apple App Store allow symbols such as square brackets app names?
For instance, if I wanted to call my game \[GAME\].

I tried searching for apps on both marketplaces using both symbols and didn't get any errors, although no apps were found with square brackets.

---

\[Removed portion of the question on ( ) and !'s per Gnemlock's answer. Part of the reason I'm asking is this is my very first app launch and I'm about to spend some money on Trademarks, so I really wanted validation from experienced developers since I'm a noob.\]

# Answer
> 4 votes
It seems fairly obvious that exclamation marks, brackets and square brackets are legal characters in application names, on both the Google Play Store and Apple iTunes Store. We find evidence of this in applications that are already available on the two stores.

## Examples from both markets

### !! Exclamation Marks !!

Very easy to find across both stores, as they are use quite regularly. Android has the likes of Angry Birds GO!, and over at Apple we find examples such as Mahjong!!.

### (( Circular Brackets ))

Still very common across both stores. Android has examples such as Tsumego Pro (Go Problems), while Apple features applications such as Piano Tiles (Don't Tap The White Tiles).

### \[\[ Square Brackets \]\]

While not as common, we find evidence of such use on Android, in applications such as Random Reader \[Prototype\]. Apple provides us an interesting example, showing off various other allowed characters with (:3 )+\[\____\].

## Further Investigation

### Google character use

While Google is not as friendly in allowing mass application search, there is theoretically no real reason that *any* character would be disallowed from application names. The name you see, and use to find the application via searches, is not the same name too which it is actually listed.

Google list the applications under the *package name*, which is typically of the format *name.domain.com*. We can see that formatting and special characters are often omitted from the package name, for example Angry Birds GO! has the package name of angrybirdsgo. This is the name used in the physical URL for the application, and the actual name in which it is saved to your device.

This makes it substantially easier to differentiate between two applications that have the same name. If two companies make an application of the same name, the two applications could theoretically coexist on the same system, because the inclusion of the unique company names would provide enough differentiation to prevent a computer system from overwriting one with the other. In fact, if you change the name of an application you are making but not the package name, it will still overwrite its predecessor version.

### Apple character use

On the Apple side of things, I can only infer that special character use is greatly permitted, as I have had no experience in publishing to an Apple device. That said, they provide far greater allowance in performing searches of their application marketplace.

Of great importance, you can effectively browse **all** games (as opposed to *categories* on the Play store), sorted alphabetically. Of particular interest, we have the standard "other" option to select, which lists all applications starting with a special character or number. Roughly the first 10 pages show applications starting with a special character.

We can infer that if a character is permitable, there are good chances that *someone* will have published an application that starts with that character. While this is not a definitive way to identify characters that are *not* allowed, this makes it much easier to find evidence of characters that *are* allowed.

---
Tags: google-play, appstore
---


# Question
Title: Text not instantiating under a canvas (unity)
Below is my code for a text I want to spawn under a canvas. Both spawn and I no longer get errors, but the text isn't spawning under the canvas.

```
        Instantiate(canvasparent);
        Text savescore = Instantiate(score) as Text;
        savescore.transform.SetParent(canvasparent.transform, false);

```

# Answer
Remember to capture a reference to the instance of the object when you instantiate it, something like this:

```
Canvas canvasInstance = Instantiate<Canvas>(canvasPrefab);

Text scoreTextInstance = Instantiate<Text>(scoreTextPrefab);

scoreTextInstance.transform.SetParent(canvasInstance.transform, false);

```

The code you showed is trying to parent the newly-spawned text to the *prefab* of the canvas, not the *instance* of the canvas you've spawned into your scene.

This is probably the most common error I see in Unity code, so be very careful to keep track of which variables refer to spawned instances and which to prefabs.
> 1 votes

---
Tags: unity, gui
---


# Question
Title: Can't get my android device to be connected to my game via Unity Remote5
Im trying to test out my game on Unity Remote5, but no matter what I try I can't seem to get it to work...

I enabled the needed settings in the dev settings. downloaded the android sdk and adb controller, tried having my phone on different usb settings (MTP, PTP,etc...) and still can't get it to work.

I'm using a Meizu m3 note, if anyone else has got one to work.

# Answer
> 1 votes
Having had many problems with the Unity Remote, I suspect you are missing the same critical requirement that I had.

As mentioned, and for the point of clarity, there are a few initial requirements you need to check to get Unity Remote working:

* You must have the respective USB drivers installed, corresponding with the manufacturer of your phone. You will often find these on the manufacturers website, and sometimes, the phone has an installer available to install the drivers when you first connect to your computer. In most cases, you should need these drivers before you can even access your phone, through file manager.
* You must have the Android SDK installed. If you are unsure, you can simply install Android Studio; it comes with it.
* You must have developer mode enabled on your android device, with *at least* "USB Debugging" enabled. You may have to enable more features for greater compatibility, or further debugging capability. If Unity Remote *did* work, and all of a sudden stops, double check that developer mode is *still* enabled. As I have found, it can turn it self off after a set period of time.

Once you have ticked these boxes, you may find that it still doesn't work. This is where I got stuck for some time - there is something else that Unity fails to tell you.

In most cases, you must have Unity Remote connected and running **before** you open Unity. That said, I find that this is an "initial" requirement. If you should accidentally close (or crash) Unity Remote during the same session, you generally do not have to close Unity again, to ensure that it opens *before* Unity.

---
Tags: android, unity
---


# Question
Title: Trying to implement forward rendering in OpenGL
I'm working on implementing forward rendering in my 2D engine, as far as I'm aware everything should be set up correctly, I've ran into some issues earlier but I'm sure I've fixed those at this point.

So what I'm doing to achieve this (May or may not be the correct way of going about this) is that I'm rendering the object first with ambient light (Which works), and then for each light affecting the object, I render it once again using a different shader for point lights. I've set that shader to only output the color red atm, but nothing shows up apart from the first render of the object (The one with the ambient light).

Here are some pieces of my code.

**Rendering of the object**

```
        shader.Use();

        shader.SetUniform("_Model", transform.Model);
        shader.SetUniform("_Color", color.Normalized.ToVector3());
        shader.SetUniform("_Diffuse", texture.ArrayPos);

        VertexAttributePointer.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 5, (System.IntPtr)0);
        VertexAttributePointer.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 5, (System.IntPtr)(3 * sizeof(float)));

        //Render sprite
        quad.VAO.Bind();

        GL.Enable(EnableCap.Blend);

        //Transparency
        GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);

        //Draw object
        GL.DrawElements(PrimitiveType.Quads, 4, DrawElementsType.UnsignedInt, 0);

        //Forward rendering
        GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One);

        GL.DepthFunc(DepthFunction.Equal);
        GL.DepthMask(false);

        Shader pointLightShader = Shader.GetShader("Forward-Point");
        if (pointLightShader != null)
        {
            pointLightShader.Use();
            shader.SetUniform("_Model", transform.Model);
            shader.SetUniform("_Color", color.Normalized.ToVector3());
            shader.SetUniform("_Diffuse", texture.ArrayPos);

            foreach (Light l in Light.lights)
            {
                pointLightShader.SetUniform("_PointLight.position", new Vector3(l.position.X, l.position.Y, 0));
                pointLightShader.SetUniform("_PointLight.color", l.color.Normalized.ToVector3());

                GL.DrawElements(PrimitiveType.Quads, 4, DrawElementsType.UnsignedInt, 0);
            }
        }

        GL.DepthFunc(DepthFunction.Lequal);
        GL.DepthMask(true);
        GL.Disable(EnableCap.Blend);

        quad.VAO.Unbind();

        texture.Unbind();

```

**Forward-Point fragment shader**

*Note that it is temporarily set to only output red, which should globally tint all objects if it works.*

```
#version 330 core

struct Light {
    vec3 position;
    vec3 color;
};

uniform vec3 _CameraPos;
uniform vec3 _Color;
uniform sampler2D _Diffuse;
uniform Light _PointLight;

out vec4 color;
in vec2 TexCoords;
in vec3 FragPos;

void main()
{
    vec4 diffuse = texture(_Diffuse, TexCoords);

    float distance = length(_PointLight.position - FragPos);
    float attenuation = 1.0;

    vec3 finalLight = _PointLight.color * attenuation;

    color = vec4(1.0, 0.0, 0.0, 1.0);
}

```

# Answer
Here is a short list of things to check:

* Does Forward-Point shader compiles successfully?
* Does point light shader program (Program Object) links successfully?
* Do you call ***`glClear`****`(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)`* before rendering?
* Have you enabled depth test (***`glEnable`****`(GL_DEPTH_TEST)`*)?
> 1 votes

# Answer
One of the big benefits of forward rendering is that you can do all your lights in one shader. Switching programs is very expensive so you should not be switching programs for each rendering of objects. At the least you should do all of the rendering for all objects with the first shader THEN switch to the point light shader.

Here is a tutorial illustrating this idea:

http://www.learnopengl.com/#!Lighting/Multiple-lights

My guess is that you are doing something incorrect with the quad draw however, and that is the current error. Probably the wrong space is being used for the position or something like that. There are too many possible errors to know for sure without spending a lot of time on it though.
> 0 votes

---
Tags: c#, opengl, glsl, lighting, opentk
---


# Question
Title: Would adding delay to inbound traffic give you an advantage in online games?
Wouldn't adding a latency delay to inbound traffic and limiting your download speeds to a low but playable standard give you an advantage in online games, especially shooters?

Because wouldn't your shots be registering as normal (using upload/outbound) while anything that attempts to hit you (download/inbound) would be delayed and/or slow?

# Answer
> 2 votes
It depends on the game. There is no such thing as "the" online game. Every game has its own network protocol with its own lag mitigation techniques.

However, properly developed games do not allow the client to decide whether or not they got hit or hit something. Otherwise it would be too easy to cheat. Usually the server decides which shots hit, how much damage they inflict and when a player is fragged. Usually... as said, different developers do things differently. I have seen games which do hit detection client-sided. Such games can usually be recognized by the huge amount of cheaters running around invulnerable and/or hitting things they can not actually hit. This can be the result of less experienced teams which aren't aware of what cheat developers are capable of. Other cases are games which were first developed with only single-player in mind and then very late in development someone decided that every game needs a multiplayer mode, so one was added in a very rushed manner on top of a software architecture which was never designed for that.

But even properly-constructed multiplayer games with authoritative servers are not immune to ping trickery.

It gets interesting when it you look at lag compensation. Many games try to compensate for the latency of players to make the game seem more fluent even when the connection is bad. So the server might take the ping into account when calculating hits. When a player has a very high ping (let's say 200ms) the server might calculate hits not based on the current game situation but on how the game was 200ms ago. This makes the game appear more fair for the high-pinger.

But this does open potential for cheating when the client can trick the server into thinking that it has a different ping than it actually has. This can be achieved by intentionally delaying packets, faking timestamps on certain packets, anticipating when ping packets arrive and sending one earlier etc. Whether a higher or a lower ping is better depends on the game and the circumstances. It's usually not much the player can gain from this, but it is something you need to keep in mind when you design a network protocol for a multiplayer game.

# Answer
> 2 votes
No, because in a good and fair multiplayer game design such calculations would always happen on the server side and there'd be at least some lag compensation.

Something like this might work on a peer to peer game without dedicated servers, but then again people might not play there in the first place.

---
Tags: networking, anti-cheat
---


# Question
Title: Are mathematical models a good way to test strategy games?
I am currently working on a simple strategy game. The game is a space exploration game where the player has to try to keep the game going for as long as possible to score as many points as possible. To go from planet to planet the player needs to use resource points; each explored planet also gives the player points (decreases gradually with time), yet a small expense in resource points is also added for each explored planet. Therefore, the player has to keep exploring to avoid running out of points.

The knowledge points allow the player to try to discover more planets, before exploring them.

I am looking for a methodical way to test the game. At the moment I keep adjusting the formulas used for the points given by each planet, or the expenses, or the travel/exploration costs, yet this trial and error method is pretty tedious and not really efficient. At the moment my "strategy" game seems more like a "click as much as you can" kind of game.

Since each type of planet has its own advantages and inconveniences, I'd really like that to show in the game play.

I was thinking of using mathematical models in Excel, by inputting all my formulas and adjusting the parameters there, but the more I think about it the more I think I will have to use some "randomness" to reflect the player choices, which defeats the purpose of testing the game for its "strategic" aspect.

Here's a screenshot of the game:

# Answer
> 4 votes
Having a good understanding of your game mechanics is essential to balancing a game properly. Modeling your game as a set of equations and graphs is a great way to obtain that understanding.

Regarding randomness: Many random events balance out over time (law of large numbers), so when there is a 50% chance that X happens and a 50% chance that Y happens, you can often simply model this as half of the effect of either event. But player actions are not random! Any player who is not playing the game for the first time will not randomly click on buttons but pursue a certain strategy. So player behavior should be another variable in your model. In a 4x game you could model how the game will develop when the player focuses their resources on expansion, development, military or different splits between either. Even better when you can model different strategies in different phases of the game. This might tell you if there is an ideal strategy (in which case you need to guide the player towards it) or if there are many viable strategies with similar chances of success (in which case you need to encourage the player to experiment).

However, you also need to verify that your game model is correct. The only way to test that is through **playtesting**. Preferably by testers who are not yourself. As the developer you have certain preconceptions about how you want your game to be played, so you subconsciously play it like that. But real players have a completely different perspective and might play it in a completely different way.

So when your models predict that the player's KP income grows quadratically over the course of the game but in test games it grows more linearly, it's time to find out where your model is wrong. Or maybe the players just overlook some feature your game didn't make obvious enough? Or maybe KP income isn't as crucial to winning your game as you thought, so players have no reason to focus on that? Time to analyze test matches and interview the players.

Then you need to decide based on your tester's feedback what would make a better game: To change the game to better fit your model or leave the game as-is and change your model to better represent it? The best course of action can often be to do a bit of both.

But what if your model gets completely confirmed by the playtests but your players still didn't like it? **Congratulations, you failed!** Yes, that's a good thing, because the faster you fail the better. You can now go back to the drawing board, come up with a better game concept, update your spreadsheet models, implement them in your game, and start another round of playtesting.

---
Tags: testing, playtesting, automated-testing
---


# Question
Title: Cannot enable 4X MSAA Anti-Aliasing in DirectX 11
I am currently learning how to use DirectX11 but I am unable to use 4X MSAA. Here is my code (Since I'm just learning I haven't used any headers or classes, sorry for the messy code) If anybody can point out what I need to do or fix that would be great.

```
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600

// include the basic windows header files and the Direct3D header files
#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
#include <DirectXMath.h>

using namespace DirectX;

// include the Direct3D Library file
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")

// global declarations
IDXGISwapChain *swapchain;             // the pointer to the swap chain interface
ID3D11Device *dev;                     // the pointer to our Direct3D device interface
ID3D11DeviceContext *devcon;           // the pointer to our Direct3D device context
ID3D11RenderTargetView *backbuffer;    // the pointer to our back buffer
ID3D11Buffer* triangleVertBuffer;
ID3D11VertexShader* VS;
ID3D11PixelShader* PS;
ID3D10Blob* VS_Buffer;
ID3D10Blob* PS_Buffer;
ID3D11InputLayout* vertLayout;

                                       // function prototypes
void InitD3D(HWND hWnd);    // sets up and initializes Direct3D
void RenderFrame(void);     // renders a single frame
void CleanD3D(void);        // closes Direct3D and releases memory
void InitScene(void);

                            // the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
    HWND hWnd;
    WNDCLASSEX wc;

    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = L"WindowClass";

    RegisterClassEx(&wc);

    RECT wr = { 0, 0, 800, 600 };
    AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);

    hWnd = CreateWindowEx(NULL,
        L"WindowClass",
        L"Eagle Engine (Alpha)",
        WS_OVERLAPPEDWINDOW,
        SCREEN_WIDTH,
        SCREEN_HEIGHT,
        wr.right - wr.left,
        wr.bottom - wr.top,
        NULL,
        NULL,
        hInstance,
        NULL);

    ShowWindow(hWnd, nCmdShow);

    // set up and initialize Direct3D
    InitD3D(hWnd);

    // enter the main loop:

    MSG msg;

    while (TRUE)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);

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

        RenderFrame();
    }

    // clean up DirectX and COM
    CleanD3D();

    return msg.wParam;
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_DESTROY:
    {
        PostQuitMessage(0);
        return 0;
    } break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

// this function initializes and prepares Direct3D for use
void InitD3D(HWND hWnd)
{
    // create a struct to hold information about the swap chain
    DXGI_SWAP_CHAIN_DESC scd;

    // clear out the struct for use
    ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

    // fill the swap chain description struct
    scd.BufferCount = 2;                                    // one back buffer
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;     // use 32-bit color
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;      // how swap chain is to be used
    scd.OutputWindow = hWnd;                                // the window to be used
    scd.SampleDesc.Count = 4;                               // how many multisamples
    scd.Windowed = TRUE;                                    // windowed/full-screen mode
                                                            // create a device, device context and swap chain using the information in the scd struct

    HRESULT hr = E_FAIL;
    hr = D3D11CreateDeviceAndSwapChain(NULL,
        D3D_DRIVER_TYPE_HARDWARE,
        NULL,
        NULL,
        NULL,
        NULL,
        D3D11_SDK_VERSION,
        &scd,
        &swapchain,
        &dev,
        NULL,
        &devcon);

    // get the address of the back buffer
    ID3D11Texture2D *pBackBuffer;
    swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

    // use the back buffer address to create the render target
    dev->CreateRenderTargetView(pBackBuffer, NULL, &backbuffer);
    pBackBuffer->Release();

    // set the render target as the back buffer
    devcon->OMSetRenderTargets(1, &backbuffer, NULL);

    ID3D11Texture2D* pDepthStencil = NULL;
    D3D11_TEXTURE2D_DESC descDepth;
    descDepth.Width = SCREEN_WIDTH;
    descDepth.Height = SCREEN_HEIGHT;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_R32_TYPELESS;
    descDepth.SampleDesc.Count = 4;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    hr = dev->CreateTexture2D(&descDepth, NULL, &pDepthStencil);

    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
    descDSV.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice = 0;

    // Create the depth stencil view
    ID3D11DepthStencilView* pDSV;
    hr = dev->CreateDepthStencilView(pDepthStencil, // Depth stencil texture
        &descDSV, // Depth stencil desc
        &pDSV);  // [out] Depth stencil view

    devcon->OMSetRenderTargets(1, &backbuffer, pDSV);

    // Set the viewport
    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = SCREEN_WIDTH;
    viewport.Height = SCREEN_HEIGHT;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;

    devcon->RSSetViewports(1, &viewport);
    InitScene();
}

// this is the function used to render a single frame
void RenderFrame(void)
{
    // clear the back buffer to a deep blue
    devcon->Draw(3, 0);
    // switch the back buffer and the front buffer
    swapchain->Present(0, 0);
}

// this is the function that cleans up Direct3D and COM
void CleanD3D(void)
{
    // close and release all existing COM objects
    swapchain->Release();
    dev->Release();
    backbuffer->Release();
    devcon->Release();
    triangleVertBuffer->Release();
    VS->Release();
    PS->Release();
    VS_Buffer->Release();
    PS_Buffer->Release();
    vertLayout->Release();
}

struct Vertex
{
    Vertex() {}
    Vertex(float x, float y, float z)
        : pos(x, y, z) {}
    XMFLOAT3 pos;
};

D3D11_INPUT_ELEMENT_DESC layout[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE(layout);

void InitScene()
{
    //Compile Shaders from shader file
    D3DX11CompileFromFile(L"Effects.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);
    D3DX11CompileFromFile(L"Effects.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);

    //Create the Shader Objects
    dev->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
    dev->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);

    //Set Vertex and Pixel Shaders
    devcon->VSSetShader(VS, 0, 0);
    devcon->PSSetShader(PS, 0, 0);

    //Create the vertex buffer
    Vertex v[] =
    {
        Vertex(0.0f, 0.5f, 0.5f),
        Vertex(0.5f, -0.5f, 0.5f),
        Vertex(-0.5f, -0.5f, 0.5f),
    };

    D3D11_BUFFER_DESC vertexBufferDesc;
    ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));

    vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexBufferDesc.ByteWidth = sizeof(Vertex) * 3;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = 0;
    vertexBufferDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA vertexBufferData;

    ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
    vertexBufferData.pSysMem = v;
    dev->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &triangleVertBuffer);

    //Set the vertex buffer
    UINT stride = sizeof(Vertex);
    UINT offset = 0;
    devcon->IASetVertexBuffers(0, 1, &triangleVertBuffer, &stride, &offset);

    //Create the Input Layout
    dev->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),
        VS_Buffer->GetBufferSize(), &vertLayout);

    //Set the Input Layout
    devcon->IASetInputLayout(vertLayout);

    //Set Primitive Topology
    devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}

```

When I compile the code above this is what I get. Notice the jagged edges although I put the multisample count as 4X? (If you can't see the jagged edges view it in fullscreen)

I have tried the following

```
// fill the swap chain description struct
scd.BufferCount = 2;                                    // one back buffer
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;     // use 32-bit color
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;      // how swap chain is to be used
scd.OutputWindow = hWnd;                                // the window to be used
scd.SampleDesc.Count = 4;                               // how many multisamples
UINT maxQuality;
hr = dev->CheckMultisampleQualityLevels(scd.BufferDesc.Format, scd.SampleDesc.Count, &maxQuality);
scd.SampleDesc.Quality = maxQuality;
scd.Windowed = TRUE;
scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;     // allow full-screen switching// windowed/full-screen mode
                                                        // create a device, device context and swap chain using the information in the scd struct

HRESULT hr = E_FAIL;
hr = D3D11CreateDeviceAndSwapChain(NULL,
    D3D_DRIVER_TYPE_HARDWARE,
    NULL,
    NULL,
    NULL,
    NULL,
    D3D11_SDK_VERSION,
    &scd,
    &swapchain,
    &dev,
    NULL,
    &devcon);

```

But I get the error `Identifier 'hr' is undefined`.

# Answer
> 1 votes
I think sample quality should be greater than 0. You can check the maximum supported quality by calling the ID3D11Device::CheckMultisampleQualityLevels method. For example:

```
HRESULT hr;
UINT maxQuality;
hr = dev->CheckMultisampleQualityLevels(scd.BufferDesc.Format,scd.SampleDesc.Count,&maxQuality);

```

If `hr == S_OK` when the function returns, the maximum supported quality level will be written into maxQuality variable. You can then add this line to the swapchain desc:

```
scd.SampleDesc.Quality = maxQuality; // or something less than maxQuality

```

Also provide the quality to the depth stencil descriptor:

```
descDepth.SampleDesc.Quality = scd.SampleDesc.Quality;

```

Your depth stencil texture should also be declared as multisampled. This is done by the following line:

`descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D`;

That should be `D3D11_DSV_DIMENSION_TEXTURE2DMS`

---
Tags: directx, directx11, antialiasing
---


# Question
Title: Vulkan vkEnumeratePhysicalDevices Returning Unexpected Device Count
In the machine I'm running I have two GTX 980 Tis. When I query the physical device count with `vkEnumeratePhysicalDevices` it always returns 1 despite having 2 physical discrete graphics cards. When I use `vulkaninfo` the only device listed is `GPU0` which is a `DISCRETE_GPU` / `GTX 980 Ti`.

This happens in Windows 10 as well as GNU/Linux 4.5 using Vulkan API 1.0.11 with proprietary Nvidia drivers.

Is this normal behavior and I'm not using the API correctly or is this a bug? I feel like I've made a glaring obvious mistake but I can't find anything in the Vulkan specification about it.

For clarity, this is exactly how I query physical device count:

```
auto deviceCount = uint32_t{0};
instance.enumeratePhysicalDevices(&deviceCount, nullptr);
// At this point deviceCount is 1

```

Also, to confirm that the OS sees the cards:

Windows 10:

```
C:\Users\matt>wmic path win32_VideoController get name
Name
NVIDIA GeForce GTX 980 Ti
NVIDIA GeForce GTX 980 Ti

```

Linux 4.5:

```
+------------------------------------------------------+
| NVIDIA-SMI 364.19     Driver Version: 364.19         |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 980 Ti  Off  | 0000:01:00.0      On |                  N/A |
|  0%   56C    P8    34W / 300W |    444MiB /  6140MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 980 Ti  Off  | 0000:02:00.0     Off |                  N/A |
|  0%   43C    P8    25W / 300W |     22MiB /  6143MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

```

# Answer
From the LunarG FAQ:

> **There is no multiple GPU support in version 1.0. That was unfortunately a feature Khronos had to cut in order to preserve schedule. It is expected to be near the top of the list for Vulkan 1.1. It is perfectly possible for a Vulkan implementation to expose multiple GPUs. What Vulkan currently can’t do is allow resource sharing between them. So from a point of view of, for example, a Windows system manager, its possible to recognize multiple ways to render to a surface and then use operating system hooks to transfer that to the screen. What Vulkan doesn’t have is the ability to share a texture or a render target between multiple GPUs.**

I'd write this issue off as being something that wasn't implemented because it wasn't required that they implement it yet. When Vulkan adds better multi-GPU support to be required in their spec these issues will most likely be fixed. It is odd that it still won't expose the GPUs available, but even if it did, Vulkan 1.0.x isn't ready for utilizing multiple GPUs in a way that would benefit games.

**Update as of 7/23/2016: With Nvidia GeForce driver v368.69 multiple GPUs are visible to Vulkan.**

Without changing anything (still using Vulkan API v1.0.11) and updating to Nvidia's latest driver, I have full access to both physical devices on my machine, this doesn't mean that Multi-GPU support is quite here, but it's the first step in Vulkan even being a viable choice when developing a game.
> 6 votes

# Answer
You should've disabled/removed the SLI bridge.
That's the ***glaring obvious mistake*** I'm seeing here AFAIK.
> 0 votes

---
Tags: vulkan
---


# Question
Title: How to detect collision during a cocos2d::Action
I spent a day trying to hack my own Action class, but given the hurdles I've hit trying to do so, I'm hoping there's some way to work around my problem while still using the built-in (and admittedly powerful) Action class.

To wit, I need to check collision on a linear movement type Action (like MoveTo). It appears the function simply calculates a vector and increases the Node's position on that vector as time elapses. All fine.

Now, I have a collisionHandler function set up within both my Player class and my custom Move class. However, cocos2d automatically schedules actions when they're added to a Node using the runAction method. Because of this, it seems that the collisionHandler never gets called on the Move class. The code, as I imagine it updates, looks like this:

```
Main{ //main loop
objects->update();
collisionManager->update();
} // all other cocos2d scheduled updates
actions->update(); // the collision doesn't get checked til next frame

```

Running the collision loop twice per frame must be the wrong answer. So, how do I get it so that both the objects and their actions update before the collision loop runs?

# Answer
> 0 votes
I did some more digging through the cocos2d lib files, and figured out how to substitute my own "ActionManager" class for the default one, thereby allowing me to determine when all of the Actions get updated. I haven't had any adverse side effects, as yet. Here's the implementation:

```
Scene::init{
this->ActionManager = new (std::nothrow) ActionManager(); // Director will handle safe deletion
Director::getInstance()->getScheduler()->unscheduleUpdate(Director::getInstance()->getActionManager());
Director::getInstance()->setActionManager(this->ActionManager);
Director::getInstance()->getScheduler()->unscheduleUpdate(ActionManager);
}

Scene::updateMethod{
// update players, monsters, etc.
this->ActionManager->update(); // update actions
// update collision here.
}

```

Hope this helps anyone with the same issue.

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


# Question
Title: How can I calculate the penetration depth between two colliding 3D AABBs?
I'm currently working on implementing a very basic collision system in my game at the moment that only uses 3D AABBs. My AABB `struct` currently looks like this at the moment.

```
/// <summary>
/// This struct represents a 3-dimensional bounding box that is aligned
/// to the three world axes.
/// </summary>
public struct AxisAlignedBB
{
    public Vector3 Position { get; set; }
    public Vector3 HalfScale { get; set; }

    /// <summary>
    /// Constructor for the AxisAlignedBB struct.
    /// </summary>
    /// <param name="position">The position of the AABB.</param>
    /// <param name="halfScale">The half scale of the AABB.</param>
    public AxisAlignedBB(Vector3 position, Vector3 halfScale)
    {
        this.Position = position;
        this.HalfScale = halfScale;
    }
}

```

I'm stuck on how the penetration depth between two different colliding AABBs with the AABB format I've laid out in the `struct` above is calculated. I've spent hours trying to come up with and look for a solution to this but I just can't seem to find anything.

# Answer
> 2 votes
Here is a method to find the penetration depth between two axis aligned bounding boxes at low velocities.

I've commented the code to explain how it works.

```
public static bool AABBAABB(AABB a, AABB b, ref Contact contact)
{
    // Minimum Translation Vector
    // ==========================
    float mtvDistance = float.MaxValue;             // Set current minimum distance (max float value so next value is always less)
    Vector3 mtvAxis = new Vector3();                // Axis along which to travel with the minimum distance

    // Axes of potential separation
    // ============================
    // - Each shape must be projected on these axes to test for intersection:
    //
    // (1, 0, 0)                    A0 (= B0) [X Axis]
    // (0, 1, 0)                    A1 (= B1) [Y Axis]
    // (0, 0, 1)                    A1 (= B2) [Z Axis]

    // [X Axis]
    if (!TestAxisStatic(Vector3.UnitX, a.MinPoint.X, a.MaxPoint.X, b.MinPoint.X, b.MaxPoint.X, ref mtvAxis, ref mtvDistance))
        return false;

    // [Y Axis]
    if (!TestAxisStatic(Vector3.UnitY, a.MinPoint.Y, a.MaxPoint.Y, b.MinPoint.Y, b.MaxPoint.Y, ref mtvAxis, ref mtvDistance))
        return false;

    // [Z Axis]
    if (!TestAxisStatic(Vector3.UnitZ, a.MinPoint.Z, a.MaxPoint.Z, b.MinPoint.Z, b.MaxPoint.Z, ref mtvAxis, ref mtvDistance))
        return false;

    contact.isIntersecting = true;

    // Calculate Minimum Translation Vector (MTV) [normal * penetration]
    contact.nEnter = Vector3.Normalize(mtvAxis);

    // Multiply the penetration depth by itself plus a small increment
    // When the penetration is resolved using the MTV, it will no longer intersect
    contact.penetration = (float)Math.Sqrt(mtvDistance) * 1.001f;

    return true;
}

private static bool TestAxisStatic(Vector3 axis, float minA, float maxA, float minB, float maxB, ref Vector3 mtvAxis, ref float mtvDistance)
{
    // Separating Axis Theorem
    // =======================
    // - Two convex shapes only overlap if they overlap on all axes of separation
    // - In order to create accurate responses we need to find the collision vector (Minimum Translation Vector)
    // - The collision vector is made from a vector and a scalar,
    //   - The vector value is the axis associated with the smallest penetration
    //   - The scalar value is the smallest penetration value
    // - Find if the two boxes intersect along a single axis
    // - Compute the intersection interval for that axis
    // - Keep the smallest intersection/penetration value
    float axisLengthSquared = Vector3.Dot(axis, axis);

    // If the axis is degenerate then ignore
    if (axisLengthSquared < 1.0e-8f)
        return true;

    // Calculate the two possible overlap ranges
    // Either we overlap on the left or the right sides
    float d0 = (maxB - minA);   // 'Left' side
    float d1 = (maxA - minB);   // 'Right' side

    // Intervals do not overlap, so no intersection
    if (d0 <= 0.0f || d1 <= 0.0f)
        return false;

    // Find out if we overlap on the 'right' or 'left' of the object.
    float overlap = (d0 < d1) ? d0 : -d1;

    // The mtd vector for that axis
    Vector3 sep = axis * (overlap / axisLengthSquared);

    // The mtd vector length squared
    float sepLengthSquared = Vector3.Dot(sep, sep);

    // If that vector is smaller than our computed Minimum Translation Distance use that vector as our current MTV distance
    if (sepLengthSquared < mtvDistance)
    {
        mtvDistance = sepLengthSquared;
        mtvAxis = sep;
    }

    return true;
}

```

---
Tags: c#, collision-detection, physics, collision-resolution
---


# Question
Title: Pitch/Yaw in circle causes undesired Tilt
I've made my own Camera object, with a `forward` vector as well as a `up` vector. I happen to be programming in Android using OpenGL ES 2.0 but I think this question is relevant to all frameworks, it seems to be some math issue I'm not understanding.

Here's a gif of my Pitch/Yaw working correctly:

Here's a gif of Pitch/Yaw in a circle, causing the square to rotate, because the camera is tilting (the `up` vector becomes negative as I continue).

Here's pseudocode for my pan/yaw functions:

```
function pitch(amount) {
    if (amount == 0) return;
    forward = normalize(forward + up * amount);

    // Now fix the incorrect up vector
    right = cross(forward, up);
    up = normalize(cross(right, forward));
}

function yaw(amount) {
    if (amount == 0) return;

    right = cross(forward, up);
    forward = normalize(forward + right * amount);
}

```

I get the same issue if I use Vector rotations instead of Vector Addition (amount is an angle and I use a Rotation Matrix in the X or Y axis)

```
Pitch: forward = normalize(rotated(forward, angle, Vector3(1, 0, 0)));
Yaw: forward = normalize(rotated(forward, angle, Vector3(0, 1, 0)));

```

Why is this happening? Is there a way to stop it?

**EDIT:** I followed the instructions at Why is the camera tilting around the z axis when I only specified x and y? to pitch using the local X axis and yaw using the world Y axis, same result.

Here's the new pseudocode:

```
function pitch(angle) {
    if (angle == 0) return;

    right = cross(forward, up);
    forward = normalized(rotated(forward, angle, right));

    // Fix the now incorrect up vector
    up = normalized(cross(right, forward));
}

function yaw(angle) {
    if (angle == 0) return;

    forward = normalized(rotated(forward, angle, Vector3(0, 1, 0)));
}

```

You can see all the code at https://github.com/repwolfe/paper-escaper-android/tree/master/app/src/main/java/com/studioussoftware/paperescaper

# Answer
> 2 votes
You're using the previous value of the `up` vector to update the `right` vector and the `up` vector itself. That means any small deviation from the vertical will tend to accumulate in the `up` vector and snowball over repeated updates.

Instead, you can define `right` in reference to the global up vector `(0, 1, 0)` so this error can't accumulate:

```
right = normalized(cross(forward, Vector3(0, 1, 0)));
up = cross(forward, right);

```

Note that this is not suitable when `forward` points nearly parallel to the vertical axis. You can either clamp the camera's pitch to stay away from this trouble spot, or apply the up correction gradually over multiple frames to avoid a sudden pop or lurch.

---
Tags: 3d, camera, vector, opengl-es2, linear-algebra
---


# Question
Title: Libgdx drawing a circle with large radius causes exception
When drawing a circle using the ShapeRenderer and using a really big radius (in millions, planet/sun size, given in metres) libgdx throws an exception

```
Exception in thread "LWJGL Application" java.lang.ArrayIndexOutOfBoundsException: 20003
    at com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20.color(ImmediateModeRenderer20.java:116)
    at com.badlogic.gdx.graphics.glutils.ShapeRenderer.circle(ShapeRenderer.java:880)
    at com.badlogic.gdx.graphics.glutils.ShapeRenderer.circle(ShapeRenderer.java:844)
    at com.kacpr.solar.system.Planet.draw(Planet.java:74)
    at com.kacpr.solar.system.SolarSystem.render(SolarSystem.java:66)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:223)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

```

This didn't happen when I used smaller values. The question I have is whether I'm doing something wrong using such high numbers for a radius and should scale this down before drawing (I use this radius for some other calculations) or is this a bug?

# Answer
The number of segments used to draw a circle is something like `6 × cube root (radius)`. This means for a sufficiently large radius you will break the number of allocated vertices in the `ShapeRenderer`, which is defaulted to 5000 I think.

One approach could be to scale everything down by some factor before drawing it. Another approach would be to use the other overload of `circle` that accept an argument that indicates the number of segments to use and tweak that value.
> 1 votes

---
Tags: libgdx
---


# Question
Title: In JBox2d when dragging a Body, why is the direction is flipped vertically?
Why is it when I drag a JBox2d Body with the mouse, the vertical component is flipped?

e.g. If I drag down-right, the Body moves up-right.

Is this expected behaviour, a bug in JBox2D, a Mac incompatibility or something else?

I'm on a Mac (10.9.3) with Java 1.7.60, JBox2d 2.2.1.1. I thought it might be Mac's "natural scrolling" but changing that setting didn't have any effect.

# Answer
There was change in the directions between versions of the JAR. I updated to the later JAR and the drag direction became correct.
> 0 votes

# Answer
As you did not show your code it's hard to answer. This is my answer.

When pressing the mouse I move my 'kicker' into position and stun it's velocity. When the mouse is released I apply the mouse direction as an impulse.

```
void mouseDragged()
{
  kicker.setPosition(physics.screenToWorld(new Vec2(mouseX, mouseY)));
  kicker.setLinearVelocity(new Vec2(0,0));
}

void mouseReleased()
{

  Vec2 impulse = physics.screenToWorld(new Vec2(mouseX - pmouseX, mouseY - pmouseY));
  impulse = impulse.mul(10);
  kicker.applyImpulse(impulse, kicker.getWorldCenter());
}

```

If you do not stop the 'kicker' it retains it's current impulse and it's new direction will not match the users intent.
> 0 votes

---
Tags: java, jbox2d
---


# Question
Title: How to do multi-agent 2d pathfinding when agents can block each other?
I recently restarted on my long time game development project and had a few questions about how to improve my games AI.

I am a little stuck on the best way to implement my Enemy path finding when there are multiple enemies that can collide with each other. Here is an example of the way my AI works at the moment.

The melee enemy has the following states:

Aggressive Attacking - Is in range of attacking player

Aggressive Stuck - Is trying to reach the player but blocked by a collision object

Aggressive Clear - Is trying to reach the player but is not blocked by a collision object

Passive - not currently looking for the player but if it moves in it's line of sight it will move to the aggressive state

Currently I am using a uniform tile system. Here is the basics on how the pathing works.

```
FIND PATH FROM ENEMY TO PLAYER

    IF [BLOCKED BY A COLLISION TILE]

             CALL A STAR ALGORITHM

    ELSE IF [NO COLLISION ON PATH]

            MOVE TO PLAYER

```

I do this every frame. This seems to work ok, but things have got more complicated when I bring in multiple enemies. What would be the best way to achieve the following.

Find a path for the enemy to the player when there are multiple enemies that can all collide with each other? If I just call A STAR it won't work correctly as the other enemies who are collision objects are also moving.

Sorry I hope this made sense, any help would be great.

# Answer
You will need to augment your A-star search to keep track of **when** tiles will be occupied and in which **direction** the blocking AI is going.

If a path is temporarily blocked at the time it would reach this tile the A-star can pick an alternative path or the A-star completes but a free tile (with no AI planning on moving through) should be targeted instead to wait for the path to clear to avoid deadlocks.

If tiles are busy in the same direction the other AI does not need to stay clear of the path.

The waiting time vs detour time can be used to select what to do, this becomes part of the travel cost.

This requires marking tiles with potentially multiple "busy from tick X to Y in direction Z" and properly keeping track of changes (AI get killed, redirected, etc) to recalculate the path finding.
> 2 votes

---
Tags: xna, 2d, ai, path
---


# Question
Title: Managing left and right direction buttons being pressed at the same time
I am currently programming a Tetris clone. In Tetris, there is a system being used called DAS, or Delayed Auto Shift. It works similarly to the keyboard auto-repeat used in Windows. For example, if you press left, the block immediately jumps one Column to the left. Then a certain amount of time goes by till it jumps a second time, and the following jumps move at a constant rate. I have this implemented as `moveHorizontal(boolean moveRight)`, and can call it with a boolean that determines the direction the movement is going in.

However my main problem is handling the left and right direction buttons at the same time. More specifically, the state where you hold down one button, while pressing another button. The more recently pressed button should overwrite the old one, and the DAS should be reset once it switches directions. I feel like I can't really get a grasp on how to implement this kind of logic.

How do I logically change the state so as to correctly respond to the user input as I have described?

I hope I explained the problem in enough detail. If I didn't, please let me know, so I can provide more information.

# Answer
> 1 votes
Easiest solution is to act as if neither are pressed if both are pressed.

```
if(key_left && key_right){
  key_left = false;
  key_right = false;
}

```

For using the most recent instead:

```
if(key_left && !last_frame_key_left){
    // key pressed: start left and stop right
    go_left = true;
    go_right = false;
    ResetRepeatTimer();
} else if(!key_left && last_frame_key_left){
    // key released, stop
    go_left = false;
}
// save state for next game update
last_frame_key_left = key_left;

// same thing the other way
if(key_right && !last_frame_key_right){
    go_right = true;
    go_left = false;
    ResetRepeatTimer();
} else if(!key_right && last_frame_key_right){
    go_right = false;
}
last_frame_key_right = key_right;

```

---
Tags: java, libgdx, input, keyboard
---


# Question
Title: Game-Design: Turn-based ship-to-ship combat with *simultaneous* movement
Im currently building a browser-based game, which basicly goes like: 2 Players place starships on a 2d plane, move them around and fire their guns at each other. The game is divided by turns, each one has 2 phases Phase 1 - Movement Phase 2 - Firing

Summarized, it is basicly a table-top game played in the browser.

Due to earlier experience i want to avoid the issue of Players talking movement in turns, i.e. Player A moves ship 1, B moves 2, A moves 3, B moves 4. It makes for some awkward experience and delays the actual firing Phase too Long.

So instead im aiming for something along the lines of "Both Players move all their ships in one step and see the actual Resolution of ALL ships movement afterwards - they then can issue weapons fire".

The Problem is: Manovering ships in this game is Kind of important, because weapons have different arcs of fire and ships different parts of structure. So ideally i want to make "smart" movement choices in order to bring as many weapons as possible to bear while also protecting damaged parts of my fleet / ships.

However, with parallel, "blind" movement, i cant really make smart choices.

**What would be a way, from a game-design Point of view, to allow parallel, blind movement while also ensuring impactful choices ?**

# Answer
> 2 votes
Don't fight it, embrace it.

It adds a new layer of psychology to the game. When a player anticipates their opponents next move, they can plan their move in a way which keeps the enemy in their firing arc while staying outside of theirs.

The hardest part to get this to work will be to figure out how much players can move during their turn. When you allow players to move too much in their move-phase, it will be impossible to guess moves. When they move too little, it will be too easy for players to keep each other in range.

Limiting movement actions per round to turning a certain amount of degree and moving forward a certain distance might make their movement more predictable.

---
Tags: game-design
---


# Question
Title: How can I detect a clicked element in an Editor Script?
I want to implement a custom LayoutManager, e.g. a HorizontalLayout. (Yes I know, that this already exists, but I want my own behaviour) So when I let my script calculate the width, that works. But now I want to adjust the width of one Element and let the script recalculate the width of the other elements accordingly, I run into the problem, that the width is "locked" because the script is calculating all the time. So I want to tell the script, that it should only recalculate for the elements which are not clicked on the layout for the moment. I hope something like this is possible.

# Answer
You can use the UnityEditor.Selection class to determine which objects are selected.

For example, when iterating over child objects to determine whether to adjust their scale, you can test whether `UnityEditor.Selection.Contains(thisChild)`
> 2 votes

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


# Question
Title: How to create a generic character entity in Entity System?
In the below code is the way I create a character in Entity System. But I think this is the decouple, I'm having hard time decoupling this class.

**1st approach**

```
public enum CharacterType {

     PLAYER_CHARACTER,      // PC or a character controlled by a player
     NON_PLAYER_CHARACTER   // NPC or a character controlled by a computer it self (artificial intelligence), but notice that it is a friendly character

}

public class Character {
     // Player-Character can be controlled by the player it self
     // None-Player-Character is a autonomous and cannot be controlled
     // Player-Enemy target a player-character
     // Player-Allied target a player-enemy and friendly to a player-character
     // All character is moving
     CharacterType type
     CharacterMovement movement
}

// or

public class PlayerCharacter extends Character {

}

public class NonPlayerCharacter extends Character {

}

public class Merchant extends NonPlayerCharacter {

}

public class Enemy extends Character {

}

public class CharacterComponent implements Component {
     public Character character;
}

```

**2nd approach**

```
public class PlayerComponent implements Component {
     public static final int IDLE = 0;
     public static final int MOVE_UP = 1;
     ...
}

public class NonePlayerComponent implements Component {
     public static final int IDLE = 0;
     public static final int MOVE_UP = 1;
     ...
}

public class EnemyPlayerComponent implements Component {
     public static final int IDLE = 0;
     public static final int MOVE_UP = 1;
     ...
}

public class AlliedPlayerComponent implements Component {
     public static final int IDLE = 0;
     public static final int MOVE_UP = 1;
     ...
}

```

Noticed in the 2nd approach that it has a redundant data.

# Answer
> 1 votes
Make the constants protected field variables under a new class: CharacterComponent, have the other components extend CharacterComponent (inheritance is not the devil)

# Answer
> 1 votes
Instead of having:

```
public class PlayerComponent implements Component {
 public static final int IDLE = 0;
 public static final int MOVE_UP = 1;
 ...
}

public class NonePlayerComponent implements Component {
 public static final int IDLE = 0;
 public static final int MOVE_UP = 1;
 ...
}

public class EnemyPlayerComponent implements Component {
 public static final int IDLE = 0;
 public static final int MOVE_UP = 1;
 ...
}

public class AlliedPlayerComponent implements Component {
 public static final int IDLE = 0;
 public static final int MOVE_UP = 1;
 ...
}

```

Why not use something like:

```
public class Actor {
 public static final int IDLE = 0;
 public static final int MOVE_UP = 1;
 ...
 public InputComponent;
 public PhysicsComponent;
 ...
}

```

And then have your input components control the Actors regardless of what they are? For your player your input would be controlled by keyboard and your NPCs would be controlled by an AI.

---
Tags: libgdx, entity-system
---


# Question
Title: How to export an animation from blender to Ethan (third person character) in unity 5
I've made a human animation in blender with the intention of exporting it into unity to add to the animations of the third person character 'Ethan'. Does any one know how I can export the animation into unity for the third person character and make a trigger for the animation?

# Answer
Well there are two methods which i used but the first would be simpler. First your human rig's bones must be properly named, if you used the skeleton that comes with Blender instead of a custom one then you are okay.

You simply have to export the animated model to FBX using blender's built in plugin. On the version select 7.4 Binary and leave the rest of the options as is. This assumes the fbx plugin is enabled in blender via the menu options File -\> User Preferences -\> Addons -\> Import-Export:Fbx format.

After that you copy the output fbx file to your unity project folders and import the animation. When you select the fbx model in unity, in the inspector under Rig tab change Animation Type to Humanoid and leave the rest as is then click Apply.

Next, in the Animations tab of the inspector you may need to select the Loop Time option depending on whether your animation should be looped, like a walking or running animation. The rest of the options are usually good on default but experiment and see what you get.

You can then use Ethan's animation controller to add an action for the custom animation and simply drag and drop or assign it to the newly created action. Hopefully that is clear enough.

The second method involves converting the animation to an anim file but after it becomes the same.
> 2 votes

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


# Question
Title: custom SetInterval function in javascript
i am trying to make an custom set interval function for my game but everytime i tried, i end up with a infinite loop. I can't use the default javascript's set interval because it can not take the random number. any idea?

# Answer
> 2 votes
If i understand your question correctly then make a custom function that calls itself using setTimeout.

```
var watchUntil = 10;
var start = new Date().getTime();
function watchDog() {
  console.log("watchDog called!");

  if(new Date().getTime() - start > (watchUntil * 1000)) {
    console.log("watchDog terminated!");
    return false;
  }

  var pause = (Math.random() * 3) * 1000;
  setTimeout(watchDog, pause)
}
watchDog();
```

An alternative method would be to create a watchdog function that ticks at the update rate of your app, and keeps track of the tasks you want to fire in the future.

This method means that you can get away with using a single setInterval, ticking at your minimum desired refresh rate, and simple pile on the tasks:

```
var Watchdog = (function () {
    /**
     * Creates an instance of Watchdog.
     *
     * @param {number} [interval=1000 / 60]
     */
    function Watchdog(interval) {
        if (interval === void 0) { interval = 1000 / 60; }
        this.interval = interval;
        this.tasks = [];
        this.start();
    }
    /**
     * @param {Watchdog} self
     */
    Watchdog.prototype.tick = function (self) {
        for (var key = 0; key < self.tasks.length; key++) {
            var task = self.tasks[key];
            task.ticks--;
            if (task.ticks <= 0) {
                task.callback();
                self.tasks.splice(key, 1);
                key--;
            }
        }
    };
    /**
     * callback: what to do when this task is ready
     * ticks: how many times the counter shall run over this task before executing it
     * @param {() => any} [callback=function () { }]
     * @param {number} [ticks=0]
     * @returns Watchdog
     */
    Watchdog.prototype.register = function (callback, ticks) {
        if (callback === void 0) { callback = function () { }; }
        if (ticks === void 0) { ticks = 0; }
        this.tasks.push({
            callback: callback,
            ticks: ticks
        });
        return this;
    };
    /**
     * @returns Watchdog
     */
    Watchdog.prototype.stop = function () {
        clearInterval(this.interval);
        return this;
    };
    /**
     * @returns Watchdog
     */
    Watchdog.prototype.start = function () {
        var self = this;
        this.stop();
        this.setIntervalHandle = setInterval(function () {
            self.tick(self);
        }, self.interval);
        return this;
    };
    return Watchdog;
}());
//Create a watchdog and add some tests
var w = new Watchdog(1000 / 60)
    .register(function test1() {
    console.log("Test 1 has completed");
}, 100)
    .register(function test2() {
    console.log("Test 2 has completed");
}, 30)
    .register(function test3() {
    console.log("Test 3 has completed");
}, 150);
//Add another test later, that will still be fired before some of the others:
w.register(function test4() {
    console.log("Test 4 has completed");
}, 50).register(function test5() {
    console.log("Test 5 has completed");
});
```

---
Tags: javascript
---


# Question
Title: OpenGL 2D instancing: glDrawArraysInstanced with a divisor renders nothing
I've been learning OpenGL for the past week, following tutorials here and there. I was looking to create a SpriteBatch-type of solution for 2D rendering, and for it I thought of utilizing instanced arrays, examples of which could be found in a couple of places.

To render the instances of my sprites, I'm using the function glDrawArraysInstanced, utilizing the glVertexAttribDivisor to get the correct instance in the shaders. I must be missing something however, because when ever I set my vertex attributes' divisors to 1 (to increment them each instance), nothing renders on the screen. When I don't set the divisors, only the first instance of sprites renders.

Additionally, I should probably mention that I am using OpenGL version 3.3 and SDL2.

For the relevant code, the SpriteBatch's initializer which set's the projection, creates the single VBO and VAO and whatnot:

```
#define BATCH_SIZE 2048

struct SpriteBatchItem
    {
    Texture * texture = NULL;
    GLfloat position[2];
    GLfloat dimensions[2];
    };

struct SpriteBatch
    {
    bool batching_started = false;
    unsigned int sprite_count = 0;

    glm::mat4 projection;
    GLuint shader;
    GLuint vao;
    GLuint vbo;

    SpriteBatchItem sprite_buffer[BATCH_SIZE];
    GLfloat vertex_buffer[BATCH_SIZE * 18];

    static constexpr GLfloat quad_data[18] = {
        //Position      //ID
        -1.0f, -1.0f,   0,
         1.0f, -1.0,    1,
        -1.0f,  1.0f,   2,

        -1.0f,  1.0f,   3,
         1.0f, -1.0f,   4,
         1.0f,  1.0f,   5};

    void init()
        {
        projection = glm::ortho(0.0f, (GLfloat)SCREEN_WIDTH, (GLfloat)SCREEN_HEIGHT, 0.0f, -1.0f, 1.0f);
        shader = createShaderProgram("VertexShader.glsl", "FragmentShader.glsl");

        glUseProgram(shader);

        glGenVertexArrays(1, &vao);
        glGenBuffers(1, &vbo);

        glBindVertexArray(vao);

            glBindBuffer(GL_ARRAY_BUFFER, vbo);

            //Position
            glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
            glEnableVertexAttribArray(0);
            glVertexAttribDivisor(0, 1);

            //ID, for texture positioning
            glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat)));
            glEnableVertexAttribArray(1);
            glVertexAttribDivisor(1, 1);

            glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);
    glUseProgram(0);
    }
...

```

The begin() method starts the batching process:

```
void begin()
    {
    if (batching_started) return;

    sprite_count = 0;
    batching_started = true;
    }

```

The draw method can be used after begin() has been called, and it's intention is to simply queue a sprite, remembering which texture it was using and what was it's position (I haven't gotten around to texturing yet, so only the position is really relevant.)

```
void draw(Texture& texture, GLfloat x, GLfloat y)
    {
    if (!batching_started) return;

    SpriteBatchItem& item = sprite_buffer[sprite_count];

    item.texture = &texture;
    item.position[0] = x;
    item.position[1] = y;
    item.dimensions[0] = texture.getWidth();
    item.dimensions[1] = texture.getHeight();

    ++sprite_count;
    }

```

Finally, the end() method is called. It calculates the vertices' final positions and sends the data to the GPU:

```
void end()
    {
    if (!batching_started || sprite_count < 1) return;

    glUseProgram(shader);

    for (int i = 0; i < sprite_count; ++i)
        {
        SpriteBatchItem& item = sprite_buffer[i];

        GLfloat tex_w = item.dimensions[0];
        GLfloat tex_h = item.dimensions[1];

        glm::mat4 model;
        model = glm::translate(model, glm::vec3(item.position[0], item.position[1], 0.0f));
        model = glm::translate(model, glm::vec3(1.0f * tex_w, 1.0f * tex_h, 0.0f));
        model = glm::rotate(model, 0.0f, glm::vec3(0.0f, 0.0f, 1.0f));
        model = glm::translate(model, glm::vec3(-0.5f * tex_w, -0.5f * tex_h, 0.0f));
        model = glm::scale(model, glm::vec3(glm::vec2(tex_w/2, tex_h/2), 1.0f));
        //For each vertex...
        for (int j = 0; j < 6; ++j)
            {
            glm::vec4 pos = projection * model * glm::vec4(quad_data[j*3], quad_data[j*3+1], 0.0f, 1.0f);
            vertex_buffer[i*18 + j*3    ] = pos.x;
            vertex_buffer[i*18 + j*3 + 1] = pos.y;
            vertex_buffer[i*18 + j*3 + 2] = (GLfloat)j;
            }
        }

    //Send the data to the GPU
    glBindVertexArray(vao);

        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, sprite_count * sizeof(quad_data), vertex_buffer, GL_DYNAMIC_DRAW);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        glDrawArraysInstanced(GL_TRIANGLES, 0, 6, sprite_count);

    glBindVertexArray(0);

    glUseProgram(0);

    batching_started = false;
    }

```

The VertexShader looks like this:

```
#version 330 core

layout (location = 0) in vec2 position;
layout (location = 1) in float index;

out float out_index;

void main(void)
    {
    gl_Position = vec4(position, 0.0f, 1.0f);
    out_index = index;
    }

```

The fragment shader I don't suppose is relevant at this stage as it simply sets everything to the same colour in it's current state.

Now, to get to the crux of the problem, the above code causes no output. Nothing renders on the screen with the following render function in the main loop:

```
void render()
    {
    glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    batch.begin();
        batch.draw(snow_tex, 375, 275);
        batch.draw(snow_tex, 50, 45);
        batch.draw(snow_tex, 155, 55);
        batch.draw(snow_tex, 200, 2);
    batch.end();

    SDL_GL_SwapWindow(WINDOW);
    }

```

What I would expect it to do is to render four rectangles on the screen. But this does not happen. Curiously, if I remove the following line from the batch init function...

```
glVertexAttribDivisor(0, 1);

```

...the first rectangle does render. However, the rest three do not. So, there's obviously something fundamental I am not quite understanding about instancing and how it's intended to work. Some help would be damn greatly appreciated, even if its a suggestion of a change of approach or something similar.

# Answer
> 1 votes
So the problem might be in this place:

```
 glBindVertexArray(vao);

        glBindBuffer(GL_ARRAY_BUFFER, vbo);

        //Position
        glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
        glEnableVertexAttribArray(0);
        glVertexAttribDivisor(0, 1);

        //ID, for texture positioning
        glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat)));
        glEnableVertexAttribArray(1);
        glVertexAttribDivisor(1, 1);

        glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindVertexArray(0);

```

There is no GL call that feeds **vbo** with data (quad\_data). Try calling *glBufferData()* (with proper parameters) after binding the **vbo** buffer.

---

Above might not be totally correct since I didn't notice the following code:

```
//Send the data to the GPU
glBindVertexArray(vao);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sprite_count * sizeof(quad_data), vertex_buffer, GL_DYNAMIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glDrawArraysInstanced(GL_TRIANGLES, 0, 6, sprite_count);

glBindVertexArray(0);

```

First of all this is not allowed to call glBufferData() every frame. Since this call creates and initializes data store on GPU. What you want to do is to create and allocate memory on GPU once (tip above the line) and in this piece of code you want to do something similar to (to update data in the buffer vbo):

```
//Send the data to the GPU
glBindVertexArray(vao);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferSubData(GL_ARRAY_BUFFER, 0 /* offset */, sprite_count * sizeof(quad_data), vertex_buffer);

    glDrawArraysInstanced(GL_TRIANGLES, 0, 6, sprite_count);

glBindVertexArray(0);

```

# Answer
> 0 votes
http://www.learnopengl.com/#!Advanced-OpenGL/Instancing

Debugging someone's code when nothing obvious leaps out takes too long to reasonably expect someone to do (especially in OGL where there's many things to go wrong) but this tutorial on the subject should make it easy to get something on the screen if no one immediately spots your error. From there you should be able to get things actually going in your own code.

> What makes this code interesting is the last line where we call glVertexAttribDivisor. This function tells OpenGL when to update the content of a vertex attribute to the next element. **Its first parameter is the vertex attribute in question and the second parameter the attribute divisor.** By default the attribute divisor is 0 which tells OpenGL to update the content of the vertex attribute each iteration of the vertex shader. By setting this attribute to 1 we're telling OpenGL that we want to update the content of the vertex attribute when we start to render a new instance. By setting it to 2 we'd update the content every 2 instances and so on. By setting the attribute divisor to 1 we're effectively telling OpenGL that the vertex attribute at attribute location 2 is an instanced array.

Looks like you are sending in the IDs manually which is not necessary.

By itself this function is a bit useless. Rendering the same object a thousand times is of no use to us since each of the rendered objects are rendered exactly the same and thus also at the same location; we would only see one object! For this reason GLSL embedded another built-in variable in the vertex shader called gl\_InstanceID.

> When drawing via one of the instanced rendering calls, gl\_InstanceID is incremented for each instance being rendered starting from 0. If we were to render the 43th instance for example, gl\_InstanceID would have the value 42 in the vertex shader. Having a unique value per instance means we could now for example index into a large array of position values to position each instance at a different location in the world.

Seems you set an attribute for them as well but you do not actually send them.

I won't be surprised if you remove this issue things start working as expected.

Anyway, regardless of where the problem lies (or problems), should be easy to get it going with that tutorial as a starting place. Worst comes to worst just implement the tutorial first then add in the functionality you want afterwards. Trying to do batch objcts and such before you even have the basic rendering happening is just too much.

---
Tags: opengl
---


title: Simple framerate counter?

text:
# Question
Title: Simple framerate counter?
I'm making a first person shooter, and I've seen questions like this before, but the answer is either overly complicated or they're using SDL, GLFW, GLUT, or something else. I'm not using any of that. OpenGL, C++, and GLEW for me.

I am just a little confused on how to do a framerate counter, so if I could get pseudo-code or some code-snippets that would point me in the right direction, that would help.

# Answer
To measure framerate you need two counts:

* How many **frames** (*not* draw calls) have passed, and,
* How much time has passed.

Your framerate is therefore calculated as:

```
frames / time

```

There are a few subtle complexities to this.

First thing is that you need a good, accurate, high resolution timer. You don't say what platform you're on so I'm not going to make any assumptions beyond:

* You have such a timer available, and,
* You're **not** using Sleep calls to control framerate (if you are, **stop it now**).

Let's say that you're storing the time in a variable called "timepassed". It's a double and it starts at 0 and counts the time (in seconds) since the game started. Our framerate counter begins like this:

```
static int frames = 0;
static double starttime = 0;
static bool first = TRUE;
static float fps = 0.0f;

```

The first thing we do is check if this is the first time we've passed through the counter and set some stuff up:

```
if (first)
{
    frames = 0;
    starttime = timepassed;
    first = FALSE;
    return;
}

```

Next we increment the number of frames that have passed; I'm assuming here that you're updating the framerate counter once per frame only:

```
frames++;

```

And here we evaluate the actual FPS number.

```
if (timepassed - starttime > 0.25 && frames > 10)
{
    fps = (double) frames / (timepassed - starttime);
    starttime = timepassed;
    frames = 0;
}

```

Here we update the FPS count every 0.25 seconds. This isn't strictly speaking necessary but otherwise if you have a variable framerate you're going to be getting numbers wildly flashing on your screen and you won't be able to read them too good. (It's also important that timepassed - starttime is greater than 0.) After calculating the FPS we then update our static variables for the next pass through.

This is prety much my standard FPS counter (it's C heritage shows in some of the code) and I've cross-checked it with the values provided by FRAPS and found it highly accurate.
> 7 votes

# Answer
Since you are using SLD then the first thing to do is look up SDL\_GetTicks();

Obviously it's very easy to figure out what to display on your counter from there but you need to actually display it, too.

Generally you want to use something like FreeType to allow you to load entire font sets. This gives you a great deal of information about each "glyph", which represents a single character; and additionally allowing you to create a texture or textures full of your glyphs.

http://www.learnopengl.com/#!In-Practice/Text-Rendering

This tutorial takes you through the basics.
> 0 votes

---
Tags: c++, frame-rate, first-person-shooter
---


# Question
Title: Ended up with left handed coordinate system OpenGL but I need right handed
So I started to make my own engine, and got my Z axis pointing away from my camera. I don't know why it happened, I followed this tutorial pretty much.

I'll post my persprojection and view calculations of my camera, please comment what other code should I post, and I'll update my post.

PersProjection

```
void Camera::setPerspective(float width, float height, float nearZ, float farZ, float angleDeg) {
perspectiveTrans.toZero();

float ar = width / height;

angleDeg = Math3D::ToRadian(angleDeg);

perspectiveTrans(0, 0) = 1.0f / (ar * tanf(angleDeg / 2.0f));
perspectiveTrans(1, 1) = 1.0f / tanf(angleDeg / 2.0f);
perspectiveTrans(2, 2) = (-nearZ - farZ) / (nearZ - farZ);
perspectiveTrans(2, 3) = (2.0f * farZ * nearZ) / (nearZ - farZ);
perspectiveTrans(3, 2) = 1.0f;
}

```

View and Projection calculations

```
Matrix4x4f Camera::getViewProjection() {
Matrix4x4f cameraRotationTrans(MatrixType::IDENTITY);

Vector3f N = target;
N.normalize();
Vector3f U = up;
U.normalize();
U = U.cross(target);
Vector3f V = N.cross(U);

cameraRotationTrans.setRow(0, Vector4f(U, 0));
cameraRotationTrans.setRow(1, Vector4f(V, 0));
cameraRotationTrans.setRow(2, Vector4f(N, 1));

Matrix4x4f cameraTranslationTrans(MatrixType::IDENTITY);
cameraTranslationTrans.setCol(3, Vector4f(-position, 1));

return perspectiveTrans * cameraRotationTrans * cameraTranslationTrans;
}

```

# Answer
Not to be glib but obviously you have something out of order in your operations or some other basic error like that. It is not immediately clear where that is happening though.

https://sourceforge.net/projects/ogl-math/

You might consider using GLM at least as a starting point. That way you won't always be wondering whether it is your current code that has an issue, or your base code. Then later when you are confident you have lots of stuff working you can switch it out completely.

http://www.learnopengl.com/#!Getting-started/Transformations

This tutorial starts off kind of basic but talks about glm and shows how to get the perspective etc. working with it. You can also compare the implemenation to what you are doing and see if anything jumps out as obviously wrong.
> -1 votes

---
Tags: opengl, c++, 3d
---


# Question
Title: Machine learning to improve strategy game AI
I am currently working on a simple strategy game as a hobby and I am starting to think about designing an AI to add opponents in the game. The idea behind the game is that you are a space explorer and that you have to achieve the highest possible score. Your score is the sum of the total number of planets you have explored + the length of time you have managed to keep the game going. Each planet that you explore gives you some resources points which decay with time and a fixed expense which remains constant over time and is discounted from your resource point pool every Unit of Time. As you can see if you don't explore fast enough then you will eventually run out of resource points, which is when the game stops.

I am now looking into adding an AI and I was wondering if it wouldn't be easier to use machine learning algorithms than code an whole AI entirely based on conditionals.

My idea was to record the player's activity every X amount of time as well as the current state of some game variables.

So I would have something like :

```
actions = {0 : nothing, 1: move, 2: explore, 3: search, etc ... }

```

And then I would record variables such as:

```
 variables = [ time_since_last_action, resource_pts, knowledge_pts, number_of_discovered_planets, number_of_explored_planets, time_in_game, current_expenses, current_resource_income, current_knowledge_income, current_active_events, etc...]

```

Then I would use some machine learning algo (as a black box) to find a relationship between game variables and actions to make. I would also record the final score at the end of each game so that the AI learns more from successful games than unsuccessful ones (or even better set a score threshold above which to send the data to the AI).

I am also thinking that by maybe feeding two different AI's with different data over a few games I could then let them teach one another.

And finally, since I am not quite sure myself what the optimal game strategy should be maybe I could get some valuable information out of the process (eg: how does each variable affects the action outcome, or the overall score).

I'm thinking that since my game is relatively simple that could be a good opportunity to get into machine learning as well (since I am also doing this project to learn).

Any thoughts or directions towards interesting resources /tutorials would be very welcome.

# Answer
> 6 votes
Firstly, I'd try a **simple greedy AI strategy** that just goes to the nearest unexplored planet and explore it. It could be enough to make the game interesting while not making the AI invincible.

With that said, supposing you want to practice ML, or want it just for fun, there are a few options:

* Store the input-output vectors you mentioned from human game-playing and use **supervised learning** (start with logistic regression) to teach the AI;
* Instead of supervised learning, you may want to try **Reinforcement Learning**. You can apply it with a human playing the game on-the-fly or fully autonomously, by letting the agent select actions (this is the common setup for RL, but may be too much slower to train). The reward at each step is the difference of points from last step. Since you have continuous input variables and discrete actions, I'd recommend to use some form of function approximation. This paper shows how to use Q-learning (and TD-Learning) with linear function approximation correctly.
* Finally, you may want your AI to play the game and use only the final score to improve. This would lead you to **Genetic Algorithms**. Basically, run a lot of random AI's (may be a bunch of logistic regressors with random weights). Select the best ones, apply crossover and mutation and start over with a new generation of agents. After doing it for many generations, you'll find pretty good agents.

Other interesting references:

---
Tags: game-design, ai, strategy, reinforcement-learning
---