# Question
Title: How can I interpret NSF (Nintendo Sound Format) data as audio?
First, I'm not asking about details regarding the layout and format of an NSF file. The original spec (see here) covers most of the information that I need regarding finding the data associated with each track.

My question is that once I've loaded an NSF and consumed the header, how can I meaningfully interpret the data for audio playback? I've found multiple sites that talk about the NSF format, but I've yet to find a site that explains how the data can be used once the file has been dissected into all of it's components. How do I read and prepare this audio information for playback?

I'm not looking to emulate an NES device but I would like to pull out the raw audio information (or calculate/convert the information to raw audio data.)

For those who are interested, this is for a personal fun project. I'd like to dissect some of these sound-bytes and convert them to audio that I can manipulate within my own application. I'm completely new to audio processing but I've done my share of low-level work. This seemed like a fun project where I'd be jumping in way over my head but I'd have fun trying to figure out all that I want to accomplish.

To start, though, I need to get audio data that I can manipulate from sources that I am interested. in this case it's NES carts. Since the cartridge data is already available in NSF files, I figured I'd dissect the NSFs rather than the ROM files for audio content.

Apologies if this questions is to big for a simple specification of data layout. Any answer that can point me in the right direction is what I'm looking for.

# Answer
Looking at the spec you linked it seems like you'd need to write an emulator for the NES's sound systems at the very least. The NES uses a highly documented 6502 which should be easy to get some info on.

https://en.wikipedia.org/wiki/MOS\_Technology\_6502

There are many many articles and guides surrounding NES development. I suggest pulling a find on the phrase "6502 instruction decoding & execution techniques" on this document: http://nesdev.com/NES%20emulator%20development%20guide.txt

To playback sound from .NSF formatted files you'll need to emulate the 6502 to synthesize the squarewaves to send to your sound card.

This may not be the best place to *start* with audio manipulation but it's certainly a cool project. You should be able to find more info on the subject by searching for more info related to the 6502 and NES emulation in general.

As @Ocelot mentioned Famitracker might be a good project to check out. Maybe ask around for some resources in the famitracker irc: http://irc.lc/esper/famitracker/irctc@@@
> 2 votes

---
Tags: audio, nintendo
---


# Question
Title: Static spawning locations for players, creatures, items in Tiled map editor
I am using Tiled map editor. I am trying to add static spawning locations (x,y) for various entities (lets say 15) in my game. The best idea I had so far is something like this:

I am using a polygon collider named `Player` to declare the spawn location of the player. The width and height of this box is irrelevant. I have placed all "spawning colliders" in the same layer. I am using the `Name` tag to identify the type of the object.

This works fine, however, inside the editor, I would like to be able to see the type of entity (Player, monster, item, etc.) without having to select the polygon collider and look at the `Name` tag each time.

If I continue doing this I am going to end up with 100 grey boxes one next to the other. Is there any way of adding an indication on the collider that would represent its type (Player, monster, item, etc.) ?

# Answer
> 2 votes
One thing you can do is to use multiple layers. Instead of using the **Name** tag of the object/collider to identify the type of the entity to be spawned, you use the layer name, so you would have **Player**-layer, **Monster**-layer, **Item**-layer etc (and everything in that layer is implicitly of the type specified by the layer).

Then you can set the Color of the layer, in the *layer properties* to a different color for every entity.

Another advantage with this is that you can hide layers you don't want to see during editing.

# Answer
> 2 votes
If you would use the **Type** field instead of the **Name** field, then you could set a color for each type of object in the preferences. It would also autocomplete in this field for the types you have defined.

But maybe a better way to make your objects visually more recognizable, especially when the size is irrelevant, is to use **tile objects** instead of rectangle objects. That way you can use any image for your objects and you do not even need to repeatedly set any name or type on them. Instead, you could put this property just on the tile.

---
Tags: libgdx, tiled
---


# Question
Title: What is a lobe, in reference to lighting and graphics
I sometimes see references to lobes when talking about lighting, especially with specular lighting, but also with spherical harmonics which doesn't do specular.

Can anyone explain what exactly a lobe is?

# Answer
It's a peak in a function defined in polar or spherical coordinates.

If we look at the function `y = cos(x)` in rectangular coordinates, it looks like a wave, with peaks at 0 and 2pi:

If we look at the function `r = cos(theta) + 1` in polar coordinates, it looks like a bulge, or "lobe" that's greatest at 0:

(Images above via Wolfram MathWorld)

The same thing can happen in 3 dimensions:

(Image via Wikipedia)

Just like the polar graph above, the value of the function is represented as distance from the center, here with blue lobes positive and yellow negative.

Each bulge of the function is commonly called a lobe - that's some region of the angular domain in which the function takes similar values.

For lighting, the lobes usually correspond to the directions reflecting light - taller lobes meaning more light. In spherical harmonics, some complicated function of direction (like a reflection cubemap) is approximated as a sum of these lobed functions - analogous to how DCT transforms are used to represent jpeg image data.
> 11 votes

---
Tags: graphics, lighting, graphics-programming
---


# Question
Title: DirectX 11 throws out my pixel shader when I multiply verts by MVP
Been following some tutorials online for DirectX 11. I was able to successfully get a triangle to render in screen space. But the moment I add a MVP matrix, my triangle disappears!

Looking at it in the graphical debugger that ships with VS2015, I can see my render pipeline is just skipping my pixel shader entirely, but I have no idea why!

my code: #include "stdafx.h"

```
#include "graphics.h"

#include "types.h"

#include <d3d11.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
//#include <DirectXPackedVector.h>

#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dcompiler.lib")

namespace graphics {

    IDXGISwapChain *swap_chain;
    ID3D11Device *device;
    ID3D11DeviceContext *context;
    ID3D11RenderTargetView *back_buffer;

    ID3D11Texture2D *depth_stencil_buffer;
    ID3D11DepthStencilState *depth_stencil_state;
    ID3D11DepthStencilView *depth_stencil_view;

    ID3D11VertexShader *sh_vertex;
    ID3D11PixelShader *sh_pixel;
    ID3D11Buffer *vertex_buffer;
    ID3D11Buffer *index_buffer;
    ID3D11Buffer *shader_constants;
    camera main_camera;

    ID3D11InputLayout *layout;

    struct vertex {
        float x;
        float y;
        float z;
        D3DCOLORVALUE color;
    };

    HRESULT compile_shader(LPCWSTR file, LPCSTR entry_point, LPCSTR features, ID3DBlob** program);
    void init_pipeline();
    void init_graphics();
    void build_shader_constants();
    void build_depth_stencil(unsigned int width, unsigned int height);

    void init(HWND hWnd, int width, int height) {
        DXGI_SWAP_CHAIN_DESC description;
        ZeroMemory(&description, sizeof(DXGI_SWAP_CHAIN_DESC));

        description.BufferCount = 1;
        description.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
        description.BufferDesc.Width = width;
        description.BufferDesc.Height = height;
        description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        description.OutputWindow = hWnd;
        description.SampleDesc.Count = 4;
        description.Windowed = TRUE;
        description.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

        D3D11CreateDeviceAndSwapChain(NULL,
            D3D_DRIVER_TYPE_HARDWARE,
            NULL,
            D3D11_CREATE_DEVICE_DEBUG,
            NULL,
            NULL,
            D3D11_SDK_VERSION,
            &description,
            &swap_chain,
            &device,
            NULL,
            &context);

        ID3D11Texture2D *buffer_texture;
        swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&buffer_texture);
        device->CreateRenderTargetView(buffer_texture, NULL, &back_buffer);
        buffer_texture->Release();

        context->OMSetRenderTargets(1, &back_buffer, NULL);

        D3D11_VIEWPORT viewport;
        ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

        viewport.TopLeftX = 0;
        viewport.TopLeftY = 0;
        viewport.Width = (float)width;
        viewport.Height = (float)height;
        viewport.MinDepth = 0;
        viewport.MaxDepth = 1.0;

        context->RSSetViewports(1, &viewport);

        init_pipeline();
        init_graphics();
        build_depth_stencil(width, height);

        main_camera.position = DirectX::XMFLOAT3(-1000.0f, -1000.0f, -1000.0f);
        main_camera.look_at = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f);
        main_camera.aspect_ratio = (float)width / (float)height;
        main_camera.fov = DirectX::XM_PIDIV4;
        main_camera.near_clip = 1.f;
        main_camera.far_clip = 10000.0f;
    }

    void render() {
        float color[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
        context->ClearRenderTargetView(back_buffer, color);
        context->ClearDepthStencilView(depth_stencil_view, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0xFF);

        unsigned int stride = sizeof(vertex);
        unsigned int offset = 0;

        build_shader_constants();

        context->VSSetConstantBuffers(0, 1, &shader_constants);
        context->IASetVertexBuffers(0, 1, &vertex_buffer, &stride, &offset);
        context->IASetIndexBuffer(index_buffer, DXGI_FORMAT_R32_UINT, 0);
        context->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
        context->Draw(3, 0);

        swap_chain->Present(0, 0);
    }

    struct vs_constants {
        DirectX::XMFLOAT4X4 model;
        DirectX::XMFLOAT4X4 view;
        DirectX::XMFLOAT4X4 projection;
    };

    DirectX::XMVECTOR up = DirectX::XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);

    DirectX::XMMATRIX create_view_matrix(const DirectX::XMFLOAT3 &position, const DirectX::XMFLOAT3 &look) {
        DirectX::XMVECTOR eye_position = DirectX::XMLoadFloat3(&position);
        DirectX::XMVECTOR look_at = DirectX::XMLoadFloat3(&look);

        return DirectX::XMMatrixLookAtLH(eye_position, look_at, up);
    }
    void build_shader_constants() {

        D3D11_BUFFER_DESC buffer_desc;
        buffer_desc.ByteWidth = sizeof(vs_constants);
        buffer_desc.Usage = D3D11_USAGE_DYNAMIC;
        buffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        buffer_desc.MiscFlags = 0;
        buffer_desc.StructureByteStride = 0;

        vs_constants constants;
        DirectX::XMStoreFloat4x4(&constants.model, DirectX::XMMatrixIdentity());
        DirectX::XMStoreFloat4x4(&constants.view, DirectX::XMMatrixTranspose(create_view_matrix(main_camera.position, main_camera.look_at)));
        DirectX::XMStoreFloat4x4(&constants.projection, DirectX::XMMatrixTranspose(DirectX::XMMatrixPerspectiveFovLH(main_camera.fov, main_camera.aspect_ratio, main_camera.near_clip, main_camera.far_clip)));

        D3D11_SUBRESOURCE_DATA constant_data;
        constant_data.pSysMem = &constants;
        constant_data.SysMemPitch = 0;
        constant_data.SysMemSlicePitch = 0;

        HRESULT hr = device->CreateBuffer(&buffer_desc, &constant_data, &shader_constants);
        if (FAILED(hr)) {
            return;
        }

        context->VSSetConstantBuffers(0, 1, &shader_constants);
    }

    void release() {
        swap_chain->SetFullscreenState(FALSE, NULL);
        sh_vertex->Release();
        sh_pixel->Release();

        vertex_buffer->Release();
        index_buffer->Release();

        swap_chain->Release();
        back_buffer->Release();
        device->Release();
        context->Release();
    }

// P R I V A T E //////////////////////////////////////////////////////////////

    HRESULT compile_shader(LPCWSTR file, LPCSTR entry_point, LPCSTR features, ID3DBlob** program) {
        *program = nullptr;
        ID3DBlob *program_code = nullptr, *error;
        HRESULT hr = D3DCompileFromFile(file, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, entry_point, features, D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION, 0, &program_code, &error);
        if (FAILED(hr)) {
            if (error) {
                OutputDebugStringA((char*)error->GetBufferPointer());
                error->Release();
            }
            else {
            }
            if (program_code) { program_code->Release(); }
        }
        else { OutputDebugStringA("Shader compiled successfully\n"); }
        *program = program_code;
        return hr;
    }

    void init_pipeline() {
        ID3DBlob *pg_vertex, *pg_pixel;
        compile_shader(L"shaders.shader", "VShader", "vs_4_0", &pg_vertex);
        compile_shader(L"shaders.shader", "PShader", "ps_4_0", &pg_pixel);

        device->CreateVertexShader(pg_vertex->GetBufferPointer(), pg_vertex->GetBufferSize(), NULL, &sh_vertex);
        device->CreatePixelShader(pg_pixel->GetBufferPointer(), pg_pixel->GetBufferSize(), NULL, &sh_pixel);

        context->VSSetShader(sh_vertex, NULL, NULL);
        context->PSSetShader(sh_pixel, NULL, NULL);

        D3D11_INPUT_ELEMENT_DESC ied[] = {
            {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
            {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}
        };

        device->CreateInputLayout(ied, 2, pg_vertex->GetBufferPointer(), pg_vertex->GetBufferSize(), &layout);
        context->IASetInputLayout(layout);
    }

    // TODO - function that will build buffers if given a list of verts
    // and a list of indices. Perhaps this is a mesh_data structure?
    void init_graphics() {
        vertex vertices[] = {
            {0.0f, 0.5f, 0.0f, {1.0f, 0.0f, 0.0f, 1.0f} },
            {0.45f, -0.5f, 0.0f, {0.0f, 1.0f, 0.0f, 1.0f} },
            {-0.45f, -0.5f, 0.0f, {0.0f, 0.0f, 1.0f, 1.0f} }
        };

        D3D11_BUFFER_DESC vertex_buffer_description, index_buffer_description;
        ZeroMemory(&vertex_buffer_description, sizeof(vertex_buffer_description));
        ZeroMemory(&index_buffer_description, sizeof(index_buffer_description));

        vertex_buffer_description.Usage = D3D11_USAGE_DEFAULT;
        vertex_buffer_description.ByteWidth = sizeof(vertex) * 3;
        vertex_buffer_description.BindFlags = D3D11_BIND_VERTEX_BUFFER;
        vertex_buffer_description.CPUAccessFlags = 0;

        D3D11_SUBRESOURCE_DATA vertex_data;
        vertex_data.pSysMem = vertices;
        vertex_data.SysMemPitch = 0;
        vertex_data.SysMemSlicePitch = 0;

        device->CreateBuffer(&vertex_buffer_description, &vertex_data, &vertex_buffer);

        unsigned int indices[] = { 0, 1, 2 };
        index_buffer_description.Usage = D3D11_USAGE_DEFAULT;
        index_buffer_description.ByteWidth = sizeof(unsigned int) * 3;
        index_buffer_description.BindFlags = D3D11_BIND_INDEX_BUFFER;
        index_buffer_description.CPUAccessFlags = 0;

        D3D11_SUBRESOURCE_DATA index_data;
        index_data.pSysMem = indices;
        index_data.SysMemPitch = 0;
        index_data.SysMemSlicePitch = 0;

        device->CreateBuffer(&index_buffer_description, &index_data, &index_buffer);
    }

    void build_depth_stencil(unsigned int width, unsigned int height) {
        HRESULT hr;

        D3D11_TEXTURE2D_DESC descDepth;
        descDepth.Width = width;
        descDepth.Height = height;
        descDepth.MipLevels = 1;
        descDepth.ArraySize = 1;
        descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
        descDepth.SampleDesc.Count = 1;
        descDepth.SampleDesc.Quality = 0;
        descDepth.Usage = D3D11_USAGE_DEFAULT;
        descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
        descDepth.CPUAccessFlags = 0;
        descDepth.MiscFlags = 0;
        hr = device->CreateTexture2D(&descDepth, NULL, &depth_stencil_buffer);

        D3D11_DEPTH_STENCIL_DESC dsDesc;
        // Depth test parameters
        dsDesc.DepthEnable = true;
        dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
        dsDesc.DepthFunc = D3D11_COMPARISON_LESS;

        // Stencil test parameters
        dsDesc.StencilEnable = true;
        dsDesc.StencilReadMask = 0xFF;
        dsDesc.StencilWriteMask = 0xFF;

        // Stencil operations if pixel is front-facing
        dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
        dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

        // Stencil operations if pixel is back-facing
        dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
        dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

        // Create depth stencil state
        device->CreateDepthStencilState(&dsDesc, &depth_stencil_state);

        D3D11_DEPTH_STENCIL_VIEW_DESC descDSV = {};
        descDSV.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
        descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
        descDSV.Texture2D.MipSlice = 0;
        hr = device->CreateDepthStencilView(depth_stencil_buffer, // Depth stencil texture
            &descDSV, // Depth stencil desc
            &depth_stencil_view);
    }
} // end namespace

```

and my shader:

```
cbuffer buffer {
    matrix model;
    matrix view;
    matrix projection;
};

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;

    output.position = mul(position, model);
    output.position = mul(output.position, view);
    output.position = mul(output.position, projection);
    output.color = color;
    return output;
}

float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

```

Any help is greatly appreciated!

# Answer
Many possible reasons why something would not be rendered but if the difference is only in the matrix, here's some that I think might be most likely:

* Camera is too far (a triangle of size 1 in distance ~1732 with 45 degree FOV might simply be too small to see)
* You're looking at the triangle from the other side and culling is enabled (seems a bit unlikely though, since z\<0 should be the right place for a viewpoint)
* Matrix multiplication might need to be done in the other order (by transposing the matrix/swapping `mul` arguments, depends on whether those are row/column-major matrices)
> 1 votes

---
Tags: directx, directx11, hlsl
---


title: how to instantiate UI image in unity2D

text:
# Question
Title: how to instantiate UI image in unity2D
I'm making 2d racing game .... and I'm using UI image in the canvas background (road) .my car and enemy cars and I have tried to instantiate enemy car with this script by attaching this script to empty gameObject then attaching the enemy prefab to the enemyCar image that in the script...but the strange thing is :the enemyCar is instantiated in the hierarchy but I can't see it in the game What is the wrong ? is the wrong related to the child and parent or what ? and how can I make that UI image a child of canvas in the script ?

```
using UnityEngine;
using UnityEngine.UI;
public class Generate : MonoBehaviour
{
public Image enemyCar;

// Use this for initialization
void Start()
{
 InvokeRepeating("CreateEnemy", 1f, 1.5f);
}

void CreateEnemy()
{
 Instantiate(enemyCar);
}
 }

```

# Answer
> 0 votes
Prefab the canvas and image then add this code to Instantiate it within the canvas.

```
public GameObject canvas;
public GameObject enemyCar;

void CreateEnemy(){
    var createImage = Instantiate(enemyCar) as GameObject;
    createImage.transform.SetParent(canvas.transform, false);
}

```

Almost exactly the same answer I posted yesterday on how to Instantiate A Button The main thing is to instantiate within the canvas.

edit:

If you are also Instantiating the canvas

```
    void CreateEnemy() {
        GameObject newCanvas = Instantiate(canvas) as GameObject;
        GameObject createImage = Instantiate(enemyCar) as GameObject;
        createImage .transform.SetParent(newCanvas.transform, false);
    }

```

---
Tags: unity, image
---


title: Achieving Retro Resolution with HD

text:
# Question
Title: Achieving Retro Resolution with HD
I couldn't really find any tips on this (or perhaps I just lack the proper words once again), but I'm thinking about how to get some retro looks (SNES 16 Bit, specifially) using a modern system. Basically, the game still runs with the native resolution, however, vertially and horizontally we're limited to 256x224 (512x448). The colour palette is not an issue nowadays.

So I basically came up with this idea and am wondering if it's a smart approach (using OpenGL):

1. Create Orthogonal Projection Matrix with 256 units width and 224 units wide.
2. Use a fragment shader that doesn't do anti-aliasing on the textures, so the textures are upscaled to look pixel-y.

Since I couldn't really find a shader for 2), I also came up with a plan b):

1. Same as 1a)
2. Don't use textures at all, replace pixels with 1x1 coloured quads, convert spritesheets to 3D models made of quads.

I think plan a) seems more realistic, however. But I do wonder how other games (Shovel Knight, Freedom Planet) approach a pixel-y, retro look that stays true to the systems of 20 years ago.

# Answer
> 4 votes
If you open the image above in its full resolution and look closely (with something like Magnifier on Windows), you should see that all the pixels simply have something like a blurred edge.

Since there can be seen standalone "edges" of pixels, it is clearly not a post-processing method. When looking at screenshots in different resolutions, the edge appears to be always one pixel wide.

This leads me to a conclusion that they're probably using textures with bilinear filtering disabled and they're doing the filtering manually in a shader, by taking multiple samples from the texture within the screen pixel distance.

The way I would implement this is by taking screen-space derivatives of texture coordinates and using multiple blur offsets.

In HLSL:

```
// define "offsets" as an array of float2 with each number between [-0.5;0.5], preferably random
float2 dx = ddx( texcoord );
float2 dy = ddy( texcoord );
float4 color = float4(0,0,0,0);
for( int i = 0; i < numOffsets; ++i )
    color += tex2D( texture, texcoord + dx * offsets[ i ].x + dy * offsets[ i ].y );
color /= numOffsets;

```

---
Tags: opengl, textures, shaders
---


# Question
Title: Networking with UDP, should I keep sockets open on the server
I am working on making a 2D platforming game that will have multiplayer functionality. Over the last few days, I have done a lot of reading regarding how to deal with the networking, and believe that I am on the way to implementing some of the concepts I have read about.

I have decided to go with an Authoritative server/client model, where multiple clients will send actions made by the user to the server, client will predict the players next steps before comparing against the Authoritative reply from the server, etc. This seems to have been suggested in numerous corners of the web regarding games networking, and seems reasonable.

Before jumping straight into trying to get snapshots sent from the server, I wanted to make sure that I had an idea of some of the technical nuances of a language, as conceptual knowledge can only get me so far. I have set up a simple Echo Server that has worked rather well for a single client, but now my next step is to have multiple clients connected to the server at a single moment, and have each message that is sent from a client echoed to all clients connected to the server.

I feel that the answer might be language dependent, so I will mention now that currently I am using Java for the networking (a little bit of preliminary testing may suggest that Java has significant overhead in its network implementation, so I am open to change upon suggestion). I am using UDP for speed sake (and this seems to be what is predominantly suggested).

My question is with the server, should I be keeping each DatagramSocket that represents a connected client open and send DatagramPackets directly out without ever closing them (until the program terminates, client disconnects, etc.), and have them stored in some form of Collection, or should I close them after each message is sent and create a new outgoing socket whenever I need to send a packet? There are obvious performance disadvantages of creating a socket whenever I need to send a message, but is there some fundamental reason that I have not come across that suggests leaving sockets open is not a good idea?

# Answer
You should be able to use java without any performance problems, the technology went way past that. Although services that work with massive number of clients still use c++.

As for your choice of sockets, it's not a matter of performance, as people usually think, it's about what are you going to use them for.
**On game servers** you don't care if messages are out of order or got lost, you just want updates going as fast as possible. Lost messages can be ignored and if you get messages in order: 1 2 4 3, you just ignore message 3, because you already got the newer update (4). In this case you use UDP sockets (which is actually a simple wrapper over internet protocol (IP)).
But **on the web** you want all the content to arrive in order. You don't want the footer of your .html page to be processed before the header, or to lose part of the .html page with the closing tags, because it would screw up everything, neither do you want to get second frame of your youtube video before the first one. So here you use TCP sockets that will rearrange the packets as they come to be in order and resend the request for parts that were lost (this is also a wrapper over IP, but it has a lot of optimization and features developed over past 30 years).

Many applications use both TCP and UDP on the same port, which is pretty handy, but if you're making a game server and want to make sure the "attack" command gets to the server when client on the mouse you would be better off implementing it using the same UDP socket you use for updates.

As for how to implement this, my practice is to have a single socket on the server that would receive all the requests and send all the responses (don't process the requests in the same thread that receives them). And identify the clients by their IPEndPoint (plus whatever type of token you use for security, if any). Just remember the IPEndPoint of the clients, so you know where to send the response, or in case you need to send them something asynchronously.

Making a new sockets for each client is something you do with TCP, when you use TCPListener. But UDP sockets aren't bound to any client, so making a new sockets for each client is useless, it just means you'll have to bind a lot of ports (and setup port forwarding for all ports to your computer if you're behind a router).
> 3 votes

# Answer
In client-server architecture, server is said to be always listening to its port(s) so that any client can connect to it at anytime. Also, clients usually have dynamic IP addresses and the port used for the connection may vary from machine to machine; on the other hand, servers should have static IPs (at least, DNS translation helps us) and the port(s) used to connect to them should be known to the clients.

That said, if you want to deal with one socket per client, you can set a main socket that listens to a "server port", through which a connecting client can tell the server its own IP address and the port it is using for the connection. Such socket just listens to incoming messages, and when a new connection request arrives the server creates another socket on a different port, and tells the client that communication is possible by using the same server IP but on our new socket (which listens to a different port than "server port").

Note that this client-server communication is not a real connection: clients just know they can send messages to the server and that such messages are likely to be received by it, and viceversa. Server should be keeping a list of clients' IPs and ports (one can use a dynamic Array, a data structure...) in order to track them and send packets when needed, as well as checking for clients' status or more.
> 2 votes

---
Tags: networking, client-server, udp
---


# Question
Title: Portal View/Projection Matrix near plane
For RenderToTexture/Camera based portal rendering, the basics seems simple enough.

However, with a free camera, most of the time it is going to be looking at such portals at an angle:

Now a regular near clipping plane will not always work here, it will either intersect with the wall the portal is sitting on, or possibly with objects in front of the wall.

The desired near clipping plane would be aligned like the portal, producing a view volume more like this:

or this in 3D:

So here is my question:

How does one construct or "truncate" a view/projection matrix to achieve such an off-camera-normal (near) clipping plane?

# Answer
You want to use the following technique to modify the projection matrix. It moves the near plane to a given location (like the plane of the portal).

http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
> 1 votes

# Answer
I have not implemented this myself, but I would imagine using the the stencil buffer would solve your problem. Render the portal to the stencil buffer and then render the objects in the portal's frustum. You will then get pixel-perfect culling of the object.

Here's a website with some details:

http://th0mas.nl/2013/05/rendering-recursive-portals-with-opengl/
> 0 votes

# Answer
Adapted from this page, which was linked in Eric Lengyel's paper. Given a view matrix, projection matrix, and a point and a normal for the desired plane, it produces the right projection matrix.

```
rplane plane;

D3DXPlaneFromPointNormal(&plane, &p, &normal);

D3DXMATRIX matClipProj, WorldToProjection;

WorldToProjection = matView * matProjection;

D3DXMatrixInverse(&WorldToProjection, NULL, &WorldToProjection);
D3DXMatrixTranspose(&WorldToProjection, &WorldToProjection);

D3DXVECTOR4 clipPlane(plane.a, plane.b, plane.c, plane.d);
D3DXVECTOR4 projClipPlane;

// transform clip plane into projection space
D3DXVec4Transform(&projClipPlane, &clipPlane, &WorldToProjection);
D3DXMatrixIdentity(&matClipProj);

if (projClipPlane.w == 0)  // or less than a really small value
{
    // plane is perpendicular to the near plane
    return;
}

if (projClipPlane.w > 0)
{
    // flip plane to point away from eye
    D3DXVECTOR4 clipPlane(-plane.a, -plane.b, -plane.c, -plane.d);

    // transform clip plane into projection space
    D3DXVec4Transform(&projClipPlane, &clipPlane, &WorldToProjection);

}

// put projection space clip plane in Z column
matClipProj(0, 2) = projClipPlane.x;
matClipProj(1, 2) = projClipPlane.y;
matClipProj(2, 2) = projClipPlane.z;
matClipProj(3, 2) = projClipPlane.w;

// multiply into projection matrix
D3DXMATRIX projClipMatrix = matProjection * matClipProj;

matProjection = projClipMatrix;

```
> 0 votes

---
Tags: 3d, mathematics, linear-algebra
---


# Question
Title: Drawing textures off screen optimization required?
I recently started using LibGDX and I am wondering if I have to optimize my code when drawing textures/sprites off-screen, just like I used to do with XNA.

My biggest concern here is specifically for the `TiledMapRenderer.render()` method, which draws a tiled map, imported from the `Tiled map editor` software.

I don't know how reliable this test I tried was (I just used the `Sprite` and `SpriteBatch` class here), but here it is:

```
// Doesn't cause frame drop
spriteBatch.begin();
for (int i = 0; i < 50000; i++) {
    mySprite.setPosition(i, i); // most of times this is off-screen
    mySprite.draw(spriteBatch);
}
spriteBatch.end()

// Less than 1 frame per second
spriteBatch.begin();
for (int i = 0; i < 50000; i++) {
    mySprite.setPosition(0, 0); // always inside the screen view
    mySprite.draw(spriteBatch);
}
spriteBatch.end();

```

So, from what I observe, I assume that anything drawn outside of the screen with LibGDX is not being drawn, to improve performance. Is this the case ? If so, in what degree should I be abusing this feature ?

Is LibGDX just checking a couple of logical conditions with the camera/viewport I am using and the u,v coordinates I am trying to draw the texture to and determines if this texture should or should not be drawn ? Or is it a process that takes requires lot of resources from the system ? Keep in mind that I mostly care about the android devices.

Should I be worried about this at all ? Again, `TiledMapRenderer.render()` is my biggest concern here, but I would also like to know if there is an optimization with drawing textures off-screen in general as well.

# Answer
Yes, libGDX does optimize in that area, but that is irrelevant to the code you've written here. In your first part where you drew off-screen, you went and drew off to position 50000 that would be taxing to the computer, but the fact of the matter is that your Gdx.graphics.getWidth() / Gdx.graphics.getHeight() is unlikely to be ever 50000 unless you are trying to make a game that only works on a very large screen. Therefore it is impossible for libGDX to draw after a certain point, cutting off the drawing once it leaves the viewport size. In the second part, you are drawing the same image 50000 times before continuing to the next frame, naturally that would slow the game by a lot. The difference between the two is that one is impossible after a certain point and stops, decreasing the workload to be like 2500 times the amount; whereas the other is possible and the workload remains the same.

So yes, libGDX does optimize, but the code you've written here doesn't test for that correctly. Naturally you should always try to avoid abusing the gift libGDX has given us, but at the same time you needn't fret over it ;)
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Animations won't transfer states until entire animation is completed
I am following the survival shooter tutorial and am using Unity 5.

I just completed this video (linked) and I tested played it to see my animations worked but it seems like it will only transition from idle to walking after the entirety of the idle animation completes. The idle animation is quite long so my character will move around when it looks like its idling since the movement responds right away.

Did I mess up something in my transitions? I followed the directions exactly and didn't change anything in the inspector that I wasn't told to do.

# Answer
> 3 votes
Found the issue. I needed to un-check the "Has Exit Time" option in the state transition line's properties.

---
Tags: animation, state, unity
---


title: Why is everything lit by default?

text:
# Question
Title: Why is everything lit by default?
I am following the unity tutorial here and when i drag my environment into the Hierarchy everything i already lit up on my Game view, i noticed this was also the case in the Space Shooter tutorial that i followed before this but i ignored it. Does Unity5 automatically light up things for you if you don't have any lights? I tried setting the ambient Intensity to zero but it literally changes nothing. When i drag in the lighting prefab it also doesn't seem to do much because the scene was already lit up somewhat.

It is still dark but it isn't pitch black like it should be in the Game view.

# Answer
It's part of the global illumination that will be set up by default for all your objects to receive ambient/reflections from the skybox. Click the Window -\> lighting. I won't go into detail as the official tutorial will explain everything:

https://unity3d.com/learn/tutorials/modules/beginner/unity-5/unity5-lighting-overview

Cheers.
> 1 votes

---
Tags: lighting, unity
---


title: Color key or transparent images?

text:
# Question
Title: Color key or transparent images?
Ive seen a lot of people make sprite sheets magenta instead of transparent and then they make the magenta transparent using code. What is best (Performance) to use transparent images or use a color (example : magenta) instead of transparency?

# Answer
It depends entirely on your needs: using transparency keys, you usually only have fully-transparent or fully-opaque colors\*; using an alpha component, you can have 255 different levels of opacity. Do you want transparent smoke and flames for your explosion sprites, or just Super-Mario-Fireball style ones, with all-or-nothing opacity? It depends on your application's needs.

\*Unless you use multiple transparency keys to represent different levels of opaqueness. For example, your program could treat magenta pixels as fully transparent; pixels with odd-numbered R-components as half transparent; and pixels with prime-number G components as 3/4 transparent. Whether that's a more memory-efficient option requires a lot of case-specific math to determine, but it's pretty much always more complicated than just using an alpha component in the source content, and it can really limit the colors available to you if you use too many color keys.

(Please comment if you'd like a code sample and/or images- I'm on mobile right now.)
> 2 votes

# Answer
It is quite the same thing. When rendering occurs, the program can compute opaque and transparent pixels to be drawn for color interpolation on the screen. The only difference on the two techniques you mentioned is that trasparent images carry transparency information on their own, and color key gives transparency information to an image from within the program, but when the engine draws on the screen it still checks for what to draw and what not to draw, every frame.
> 3 votes

---
Tags: color, transparency
---


title: How does Minecraft render chunks?

text:
# Question
Title: How does Minecraft render chunks?
I'm writing a simple Minecraft like game to test out a few world gen algorithms and to learn more about OpenGL. My first render code was `glBegin() ... glEnd()` style. Very ineficient and slow. I started learning VBOs for a heightmap project but using VBOs will force me to update the whole VBO of the chunk if something is added or removed due to it's size changing. That also sounds ineficient. The most plausable theory so far I can think of is instancing but even this isn't good due to multiple render types.

When I've been modding Minecraft all the render code i've seen there (and written my self) has been `glBegin() ... glEnd()` style. Is it really that? It just feels so wrong since it can render 64 chunks 20 fps no problem on an Intel intergrated GPU.

# Answer
> 6 votes
The bulk of Minecraft's chunk rendering goes through a vertex array. The world is split into 16x16x16-block render-chunks (which currently happen to be the same as storage-chunks, but it wasn't always that way).

Each render-chunk is converted to a vertex array, and rendered. It uses OpenGL display lists (one per render-chunk) as an older alternative to VBOs. If any blocks in a render-chunk change, the entire vertex array and display list for that chunk are regenerated.

# Answer
> 1 votes
Modern iterations Minecraft can use both VBOs or immediate mode (`glBegin` and friends).

The reason why it can get away with that is because of other rendering optimizations. Try refraining from rendering any blocks that are not adjacent to air (less bandwidth), building and optimizing meshes from chunk data (less vertices to draw), or cutting down on the size of each vertex element (less bandwidth). There are plenty of other ways to increase performance with such an engine.

> That also sounds ineficient.

Have you done any tests that show that this is a bottleneck? What is inefficient is trivial if it's using time that isn't needed elsewhere. If it works without problems then you're fine. Only start worrying about it if it's preventing you from achieving your target framerate.

AFAIK Minecraft does this whenever there are chunk updates. It isn't as expensive as you think, provided the chunk is of a reasonable size.

---
Tags: opengl, minecraft-modding, terrain-rendering
---


title: Opengl Best VAO model for voxel engine

text:
# Question
Title: Opengl Best VAO model for voxel engine
I make a voxel engine on LWJGL 3 (OpenGL binding for JVM). I store all object data in world class. World is subdivided into 32\*32\*32 chunks. Chunks use octree storage. The main part of all my rendering is cubes that share one mesh but have different transformation matrices and some other data. To render those i use one VAO per chunk, it contains only one cube mesh instance and has all cubes data (like transformations) stored in its VBOs. I construct each chunk VAO once and render it fully in one call - glDrawElementsInstanced. If i need to change some cube data in a chunk, i will reconstuct VAO from ground up or change individual buffer data. That should be pretty efficient, right ?

But I need some other stuff to be rendered, like complex mesh objects or effects or some debug stuff.

How should I render those objects ? Should I create a VAO for each mesh and then perform instanced rendering for each object with the same mesh ? Or should I batch all objects with their meshes into one VAO for each chunk and render it fully ?

I was trying to create a VAO recently, that contained one instance of each mesh and all object data. But i could not render it correctly. Because each time I needed to somehow switch object data VBO while rendering an instanced mesh. It didn't work.

Code for the last VAO: http://pastebin.com/WanNsR5L

# Answer
I don't think you should be instancing individual blocks. That's a lot of data you have to send back and forth to the GPU... it just isn't feasible, especially for a voxel engine.

I would construct a mesh from the chunk data and place it into a VBO. Every time there is a chunk update, discard the mesh and create a new one in it's place.

I feel that the "greedy meshing" algorithm is pretty easy to implement and its pretty fast, although it isn't always the most optimal. You can find more information on it here, and also more information on how to modify it to perform better: http://0fps.net/2012/06/30/meshing-in-a-minecraft-game/

Not only does meshing increase performance time, but it opens up a path to modularity. You can add different algorithms like dual contouring, marching cubes, etc, seamlessly without affecting any other code.
> 1 votes

---
Tags: opengl, lwjgl, voxels, vbo
---


# Question
Title: How do i make an idle-styled counter in Javascript & HTML
I just started making a basic game in HTML, CSS, Javascript, and JQuery, but I want to have the money add up after a certain amount of time (if you have ever played an idle game, you'd know what i mean) but i cant figure this out.

If anyone could help me out, i would appreciate that.

```
<!DOCTYPE html>
<html>
<head>
    <link rel='stylesheet' href='style.css' />
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
    <script src='http://code.jquery.com/jquery-latest.js'></script>
    <script src='script.js'></script>

</head>
<body>
    <div class='Main'>
        <div class='CUR'>
            <p id='CUR1'>Copper Coins: <span id='GC'>0</span></p>
        </div>
    </div>
</body>
<script>
    var max = 100;
    var copper = 0;

    while(copper <= max) {
        setInterval(1000);
        document.getElementById('GC').innerHTML = copper;
        copper++;
    };
</script>
</html>

```

# Answer
> 1 votes
This is not how `setInterval()` works. You need to pass the function directly, like this:

```
setInterval(function() {
    if (copper < max) {
        copper++;
        document.getElementById('GC').innerHTML = copper;
    }
}, 1000);

```

# Answer
> 1 votes
setInterval runs forever, or until you cancel it.

This will be a "fire and forget" call. You don't need the loop. The code will run forever, once every few milliseconds.

```
setInterval(function() {
    // move it up if its too small
    if (copper < max) {
        copper++;
        document.getElementById('GC').innerHTML = copper;
    // move it down if its too big
    } else if (copper > max) {
        copper--;
        document.getElementById('GC').innerHTML = copper;
    }
    // if there is no change to be made, don't bother redrawing the copper amount
}, 10); // do this 100x per second

```

---
Tags: javascript, html
---


# Question
Title: How do fps games do ironsights for weapons
How do games like **Call of Duty**, **Battlefield** and **Wolfenstein: the New Order** do their ironsights? Do they just align the model or is it an image?

# Answer
You can use a model. Often, HUD elements, sometimes including weapons, are rendered seperately from the environment. In the simplest example you'd set up the animation so that the ironsights line up with the zero-axis, and align the model's zero axis with the camera.

Using Unity as an example, you'd put the weapon in the HUD layer so that it's drawn with a camera that only draws the HUD layer.

Alternatively, you can set up the player avatar so that it lines up the same way, using the same camera. This has the added benefit of displaying to other players what you're doing without having to make a separate model, but re-positioning the gun with respect to the camera can be fiddly.

Of course, it's possible to use an image as well. If memory serves, TF2 uses a combination of these - with the sniper rifle animation leading into a sprite overlay with the sights dead center of the screen.
> 4 votes

# Answer
Both ways, but the model is more common in modern games

Only a few games use an image, the majority use a model and align the model to the centre of the screen.

This blog post gives much detail on the various systems, including ones not mentioned in the OP Aim systems in First Person Shooters
> 0 votes

---
Tags: first-person-shooter
---


# Question
Title: Java Game how to make image follow line?
Hello I have a game where circles rotate around the centre of the frame. When I click on two circles a line is drawn between the two circles. The circles are always moving and so is the line. I have an image at the start of the line and I want it to move along the line at stop at the end of the line. I knowhow to start the image at the start but I don't know how to move the image along the line. How can I move the image along the line?

Here is my code:

```
   public class ship {

public int sx,sy,ex,ey;
public boolean arrived,sel1,sel2;
public int amountOfPop = 0;

public int fc = -1,sc = -1;

public ship(int sx,int sy,int ex,int ey,int aop){
    this.sx = sx;
    this.sy =sy;
    this.ex = ex;
    this.ey =ey;
    this.amountOfPop = aop;

}

public void tick(){

}

public void render(Graphics g){
    g.setColor(Color.blue);
    g.drawLine(sx, sy, ex, ey);
}
 }

```

sx and sy are the starting x and starting y. ex and ey is where the image should finish. Please help me.

# Answer
I'm going to explain this using Vector mathematics. I would also recommend to store your x and y values as such, as it makes it easier to maintain. Here's an example:

```
public class Vector2 {

    public float x;
    public float y;

    public Vector2(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public static float length(float x, float y) {
        return Math.sqrt(x * x + y * y);
    }

    public static float distance(Vector2 first, Vector2 second) {
        return length(second.x - first.x, second.y - first.y);
    }

    public static Vector2 direction(float x, float y) {
        return new Vector2(x / length(x, y), y / length(x, y));
    }
}

```

You'll want to give your ship a `Vector2` to indicate its current position, the start position, the target position, and one for the direction. You'll also need a `speed` variable which indicates the rate at which your image will move (you could just use `1f` if you like), and a `distance` variable to indicate the distance from the current position:

```
private Vector2 position;
private Vector2 start;
private Vector2 target;
private Vector2 direction;

private float speed;

private float distance;

...

public Ship(Vector2 position, Vector2 target, float speed, ...) {
    this.position = position;

    // Initialize start as a new Vector2 with the same x and y coordinates as position
    this.start = new Vector2(position.x, position.y);
    this.target = target;

    distance = Vector2.distance(start, end);
    direction = Vector2.direction(end.x - start.x, end.y - start.y);

    ...
}

public void tick() {
    position.x += direction.x * speed;
    position.y += direction.y * speed;

    if (Vector2.distance(start, position) >= distance) {
        // The ship has reached the target
    }

    ...
}

```

I'm assuming your `tick()` method is where you're performing your logic. What we're doing here is adding the distance * speed to the current position of the ship, making it travel along the imaginary line between the start position and the target.

If your start and target points are changing as you say, all you need to do is update the `distance` and `direction` variables in your `tick()` method:

```
public void tick() {
    distance = Vector2.distance(start, end);
    direction = Vector2.direction(end.x - start.x, end.y - start.y);

    ...
}

```

---

Equations:

**Length:**

**Distance:**

**Direction:**

---

The Vector2 class in this example is very basic and can definitely be improved upon. I suggest learning more about Vector mathematics, as well as taking a look at existing implementations of Vector mathematics and calculations to get a better idea on the subject. Here's one such implementation of a Vector2 class in libGDX.
> 0 votes

# Answer
What you need to do is keep track of what distance or what percent the image has traveled down the path, and increase that amount by a small amount (based on your frame rate) in your update function.

When you want the image to start moving from start to end, you might set a percent variable to zero.

Then, in your update you might say: percent = percent + 0.01. For better results you would multiply that 0.01 by the number of milliseconds since the last update. Percent = percent + 0.01 * deltaTime. You will need to adjust that 0.01 to be larger or smaller depending on the desired speed.

Lastly, to actually calculate the location of the object so you can draw it, you just use a lerp (linear interpolation) between start and end.

PosX = startx * (1 - percent) + endx * percent

PosY = starty * (1-percent) + endy * percent

If you want to get fancy, you could make it so the object isnt a constant speed down the path. You can do this by using the squared percent in the lerp, instead of the raw percent, or you could use something like bias and gain.
> 0 votes

---
Tags: java
---


# Question
Title: Is GetFixtureA() of b2Contact guaranteed to return the body on which GetContactList() was called?
For example, in the code below, will the assert ever fail?

```
for (const b2ContactEdge *contactEdge = playerPhysicsBody->GetContactList(); contactEdge; contactEdge = contactEdge->next) {
    assert(contactEdge->contact->GetFixtureA()->GetBody() == playerPhysicsBody);
}

```

I wasn't able to determine this from the source code. From some brief debugging, it seems to be the case, but I want to avoid any subtle bugs if this assumption is wrong.

The reason that I want to do this is to find the particular fixture that belongs to the player that was involved in the contact.

# Answer
Shortly after posting I tested this out a bit more and found that the assert *will* fail. `GetFixtureA()` may or may not return a fixture belonging to `playerPhysicsBody`.

I'm now using this convenience function to safely find the fixture that I want:

```
inline const b2Fixture *contactFixtureFor(const b2Body *body, const b2ContactEdge *contactEdge) {
    return contactEdge->contact->GetFixtureA()->GetBody() == body
            ? contactEdge->contact->GetFixtureA()
            : contactEdge->contact->GetFixtureB();
}

```
> 1 votes

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


title: How to animate objects in Unity 3D

text:
# Question
Title: How to animate objects in Unity 3D
Yesterday I played around with Unity 4.6 and I came up with a question about animation.

I have an fps-survival project (most for educational purpose).

I use the default build-in fps camera controller that comes with unity asset and adding a script for head-mob.

Now I animate a "falling" animation. The animation is in the First Person Controller object. Although I have two "arms" as children in my FPS controller, I want in each frame of my animation to move the arms but when I click in the each arm , the animation window don't show me the correct state of the animation, and I need to get back to where I attach my animation to show again. I don't know what to do. I can't animate the hands in seperate file cause I don't see the falling frame from the FPS controller.(which is more a visual than a technical problem)I want to point out that I need to use both my hand objects and I am preety novice so if you could tell me in steps what to do.

I attach some images bellow to see how my enviroment is setted up.

When I select the FPS controller

After I select each hand

# Answer
> 1 votes
You want to add the different clips to the FPSController Animator so when you create your fall animation it will be with the others in that controller like walk , run ect ..

You will animate the hands movements and record the movements from the FPS Controller animation window.

Animation

The Animator Controller

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


# Question
Title: Libgdx libraries are missing from gradle cache after I reinstalled my system (IntelliJ)
I reinstalled my OS (Linux Mint) today and copied all my projects over to a flash drive. After I was done setting everything up I copied 'em back over again and started to fix the problems (caused by new jdk location, new android sdk, etc).

When I opened one of my libgdx game projects I found some errors (29) similar to the following:

```
Library gdx-1.6.1 has broken classes path:
  /home/gameplayjdk/.gradle/caches/modules-2/files-2.1/com.badlogicgames.gdx/gdx/1.6.1/bb5fe9832bcfe4bbc1de6bd357085b8a2a845d9c/gdx-1.6.1.jar [Fix]

```

Apparently the libgdx libraries are no longer present in the gradle cache, which makes sense since it's a whole new system.

Now I don't know how to make stuff work again. Any Ideas?

# Answer
> 1 votes
From the Terminal, run: `gradlew --refresh-dependencies`

Also, in the Gradle tool window, you can refresh all Gradle projects, though you should only need to do this if you make changes to your Gradle scripts:

---
Tags: libgdx, gradle
---


# Question
Title: How to get a pleasant path accelerating to a point
I am having trouble moving an object to a target position with a maximum acceleration limit.

If i just accelerate towards the target the object will fly in a doughnut a few times before hitting the target. example

If i first accelerate to reduce the vector rejection i get a nasty path directly away from the target and then a line straight to the target. example

Any ideas how to move in a natural human-like path?

*edit*

I now move in a circle at current speed with maximum acceleration until i am facing the target then accel towards it example1 example2

its not perfect but its quite predictable for players and i can calcuate time to reach target in constant time now (yey)

if anyone wants a break down of the math i can explain

# Answer
> 0 votes
You could try setting a threshold from the target, and multiplying the object's speed by distance / threshold:

```
acceleration = distance / threshold

if (acceleration <= 1) {
    speed *= acceleration;
}

```

Here's an interactive example I threw together quickly:

https://dl.dropboxusercontent.com/u/38185080/Flash/Examples/Deceleration.swf

Checking gradual movement will set speed to the acceleration value regardless of whether or not it is a value less than one. Without it checked, the speed will always equal the max speed unless it is within the threshold - it uses the same code displayed above, slightly modified:

```
if (gradual) {
    speed = acceleration;
} else {
    speed = maxSpeed;

    if (acceleration <= 1) {
        speed *= acceleration;
    }
}

```

Now you all you do is add the object direction to its position and multiply it by speed:

```
position += direction * speed;

```

# Answer
> 0 votes
If you don't need a strictly physics based solution, bias and gain can be great for giving a nice organic (accel / decel) feel to a simple linear interpolation.

http://blog.demofox.org/2012/09/24/bias-and-gain-are-your-friend/ http://demofox.org/biasgain.html

---
Tags: physics, vector, linear-algebra
---


# Question
Title: How to get a turret to shoot at player in a shmup
I'm developing a basic vertical shoot em up on the DS and am trying to get stationary turrets to shoot at the player in a shoot em up. Early on I simply had them shooting in fixed 8 directions N, S, E W, NE, NW, SE, SW, depending on the player's relative position, but I want something more specific. My attempts have been awkward at best, and my aiming algorithm is not very crude and often the turrets miss by a mile. I am looking for a simple algorithm that plots a basic straight line trajectory towards the player's xy position. Nothing fancy like predictive aiming. Does anybody know of an algorithm or an article that covers such an algorithm?

# Answer
Luckily it's pretty simple!

To have a turret shoot a bullet at a target point, you need to figure out the normalized vector from the turret to the target.

To get this, first subtract the target point from the turret point. This gives you a vector but the length is not normalized. To normalize this vector, you just divide x and y by the length of the vector.

Now you have a vector that has a length of 1, that points from the turret to the target.

If you multiply this normalized vector by the speed you want it to move per frame, you then can spawn a bullet at the turret and move it this amount every frame. It will move from the turret to the players position at the appropriate speed.

Like you pointed out though, this is not predictive, and if the player moves, the bullet will miss.
> 1 votes

# Answer
This can be achieved using trigonometry and vector mathematics. First, calculate the direction (or normalized vector) that the turret should face:

Where `a` is the target vector subtracted by the turret position:

```
direction = Vector2.Direction(targetPos - turretPos);

```

Assign this value to a `Vector2 direction` inside your bullet class. You should to increment your bullet position by its direction:

```
bullet.position += bullet.direction;

```

You won't need to update the direction unless you want the bullet to seek the target like a missile. The same direction code can be used to define the turret's rotation.
> 3 votes

---
Tags: ai, trajectory, aiming, shoot-em-up
---


# Question
Title: How can I determine "exact moment" of collision with ray casting?
I'm currently brainstorming how the physics for my game engine is going to be handled. It's top down and I'm thinking of using ray casting for collision detection. I've reached two potential problems (I want collisions to be pretty precise but of course not to operation heavy).

1. I'd like to use 2 different polygons for each object. One box to check collisions with first and then a polygon for precise checking. Is this wise to do when also checking collisions with ray casting? Or should I go for the more precise polygon right away?
2. Say I'm going to move an object 10 units X-wise and another object 10 units Y-wise how do I know "when" along this movement they collided so that if they collided after moving 5 units I could handle events at that point? (One might bounce and move back the same 5 units traveled in the same execution of my update or get instantly destroyed in which case it wouldn't collide with a third object it otherwise would have collided with)

This could be a bit overkill but I still wanna know how one could go about handling this.

# Answer
I recommend using some middleware, so that all these kind of things are worked out for you.

Otherwise,

1. Yes, this is a good idea, you can cheaply rule out certain intersections and avoid an expensive test. This is referred to as a bounding box.
2. Using some middleware will mean this is worked out for you.
> -1 votes

---
Tags: collision-detection, physics, collision-resolution, raycasting
---


# Question
Title: Acceleration and Deceleration During Rotation
I'm attempting to have a sprite rotate in a way where its rotation speed increases until it has reached the halfway point in its rotation, to which it starts to slow down. I'm currently calculating the halfway point by calculating the amount of time it should take to rotate the sprite, and then checking if a current time variable is larger.

The code works rather well except for the fact that I can't figure out how current time should increment each update. Currently I'm using delta time, but that doesn't work. I'm thinking it needs to be some combination of the calculated time to rotate and delta, but I haven't gotten it yet (clearly).

EDIT: Specifically, currentTime shouldn't be incremented by delta solely, but I have no idea what it should be in place of delta.

```
        if (currentTime <= timeToRotate)
        {
            rotationSpeed += 5f * delta;
            currentTime += delta;
        }

        else
        {
            if (rotationSpeed > 5f)
                rotationSpeed -= 5f * delta;

            else
                rotationSpeed = 5f;

            currentTime += delta;
        }

```

# Answer
> 2 votes
Correct me if I am wrong, but from what I understand, you want to achieve the following:

If so, this can be achieved using trigonometry:

```
float easing = 0.075f;

float direction = Math.atan2(target.y - sprite.y, target.x - sprite.x) / Math.PI * 180;

if (direction < sprite.rotation - 180) {
    direction += 360;
}

if (direction > sprite.rotation + 180) {
    direction -= 360;
}

sprite.rotation += (direction - sprite.rotation) * easing;

```

# Answer
> 0 votes
This seems like a real nice fit for using something like bias and gain.

Using those functions, you do a simple linear interpolation, but before using your "percent" value in the lerp, you pass it through a function to make the percent value non linear.

This makes it so it still takes the same amount of time to do, but you can make it faster in the beginning and slower in the end or make it slow near the ends and fast in the middle - or other behaviors as well.

Check this out for more info: http://blog.demofox.org/2012/09/24/bias-and-gain-are-your-friend/

---
Tags: sprites, rotation
---


# Question
Title: How do you add turbulence to a particle system using noise?
I have implemented a basic particle system using transform feedback in openGL, hoping to replicate a dust cloud.

I have looked at methods of adding turbulence, such as vortices found here.

But they do not give the desired effect. The guide discusses the idea of using perlin or simplex noise to add turbulence.

But I don't understand how this is done?

Would you use a pre-generated noise texture and take sample data from it?

Or calculate data at run time in the shader?

What is the basic idea behind implementing noise turbulence?

Edit: My main question would be, how do you get a turbulent velocity from noise values?

# Answer
> 1 votes
If you want 3D I gues one easy way of getting a velocity for a particle would be to input it's location into a noise function trice with a different seed for each one and then use the output numbers an x, y and z velocities.

Another and better way would be to generate two random numbers with the method I mentioned before: `rand1` and `rand2` that will be between 0 and 1 and use them to get a random uniformly ditributed poin point on a sphere witch can be used as a dirrection vector and scaled as needed. Like so:

```
    theta = 2 * PI * rand1;
    phi = acos(2 * rand2 - 1.0);
    velX[i] = cos(theta) * sin(phi) * scale;
    velY[i] = sin(theta) * sin(phi) * scale;
    velZ[i] = cos(phi) * scale;

```

A good way of doing this is to use 4D perlin noise, with the first three dimentions being position and the fourth being the seed. To increase performene you can make an array of the velocities and the velocitie closest to a particle will effect it. You can also add variations to the flow by adding time to the seed but it won't be as efecient because you'll have to recompute the values.

---
Tags: shaders, noise
---


title: Is DirectX free for commercial use?

text:
# Question
Title: Is DirectX free for commercial use?
*This question isn't gamedev per se but it is definitely relevant. Still, if it's off-topic, please direct me to the proper SE page.*

This question has probably already come up many times but I'd like to take a complete approach here and also up-to-date (whatever I may find online might be from 1/5/10 years ago and so isn't of much value to me).

So - is DirectX free for commercial use? What do I mean by that? Is it free to download DirectX SDK (or whatever it's called nowadays) and develop my game? Are there any fees involved in publishing and selling my game if it uses DirectX? And in the spirit of covering it all - using DirectX implies using Windows (which isn't free) and maybe Visual Studio? To that last one - is it absolutely necessary to use VS? Also, is it practical to use any other IDE? And are there any other (implied) costs like that "using Windows" one?

**Update:**

My friend sent me this EULA snippet saying that it's only free if I'm the only user of the software I develop so this must mean I have to pay for DX for commercial use.

> SOFTWARE PRODUCT. You may install and use the SOFTWARE PRODUCT on an unlimited number of computers, including workstations, terminals or other digital electronic devices ("COMPUTERS") to design, develop, and test software application products for use with Microsoft operating system products including Windows NT Workstation 4.0, Windows NT Server 4.0, Windows 95 and subsequent releases thereto ("Application"). You may install copies of the SOFTWARE PRODUCT on up to ten (10) COMPUTERS provided that you are the only individual using the SOFTWARE PRODUCT on each such COMPUTER.

# Answer
> 5 votes
It's definetly free, but it runs only on windows, which is not. Visual studio is optional, but it is the preferred editor by many developers, especially in professional game development studios. You will also find most samples for it as a Visual studio solution.

---
Tags: directx, licensing, pricing
---


title: Finding coordinate in radius

text:
# Question
Title: Finding coordinate in radius
Hello i have two points (Vector3) `A` and `B`. And have a radius `r`

How can i find a coords of point `P` in a circle by angle?

# Answer
> 2 votes
Solution for 2D vectors:

```
Vector2 AB = B - A;  // Vector from A to B

Vector2 A0 = r * AB.normalized;  // Vector from A to 0°
Vector2 A90 = new Vector2(A0.y, -A0.x);  // Vector from A to 90°

Vector2 P = A + Sin(alpha) * A90 + Cos(alpha) * A0;  // Coordinate of arbitrary point on a circle

```

For arbitrary 3D vectors A and B in 3D space you need coordinates of at least one more point on the same plane (but not located on the A-B line).

---
Tags: mathematics, vector, linear-algebra
---


# Question
Title: How to render tile maps in modern opengl?
I'm trying to use SDL2 and Modern OpenGL to make a 2D rpg. The problem is, I have no idea how to render a tile map. I'm using the Tiled map editor to create maps. I have a vague idea of how to parse the maps using this (https://github.com/andrewrk/tmxparser) tmx parser. I try to parse the maps using said parser, but then I run into the problem of how to actually get the tile maps to appear on screen, when using a spritebatch class. How would I go about rendering these maps using modern OpenGL?

# Answer
You'd draw a tile map in OpenGL the same way you'd draw a sprite that has multiple frames in a single texture; by adjusting the texture coordinates such that you only drew a portion of the texture onto the quad that represents the tile.

A rough way to do it would be to create a mesh of quads/triangles that represents your tile map; each tile's world coordinates would be equal to the tile's X,Y index in the grid * the size of the tile (make sure to use orthographic projection!);

Then, each tile's UV coordinates into the master tiles texture would be something like;

(1 / tiles across) * textureXindex

So if your texture had four tiles across (same thing in an ortho projection) and you wanted tile #2;

textureWidth = 1 / 4;

textureWidth * 2 = 0.5 (left texture U coordinate)

the above value (0.5) + textureWidth (right texture U coordinate)

Same for the Y/V coordinate. You could also calculate the tile width by dividing the total width of the tile texture in pixels by the width of a tile in pixels, which will give you the same decimal value as the 1/4 calculation above.

In order to convert a single-number tile index into an X, Y value within the tile map, divide it by the number of columns to get the Y, then mod (%) it by the number of columns to get the X.

So if your tile map is 4x4, and your index is 13;

```
13 / 4 = 3
13 % 4 = 1

```

So your tile coordinates are 1, 3.
> 2 votes

# Answer
Here is an example with a very simple tile/sprite sheet. Each tile is 32x32 and the red line marks the left and the upper corner of each tile.

You always want to use sheets like this when rendering tiles. Switching textures is much more expensive than drawing a bunch of vertices.

You can either index it either by using a 2D vector or just a number. To index it via a vector you would get the minimum position (assuming the origin is in the top left of the image) and maximum position as such (this is some kind of pseudocode):

```
sheetPrediv = (1 / sheetWidth, 1 / sheetHeight);
minPos = (x * spriteWidth, y * spriteHeight) * sheetPrediv;
maxPos = (x * spriteWidth + spriteWidth, y * spriteHeight + spriteHeight) * sheetPrediv;

```

sheetPrediv could be contained in some class that also contains your OpenGL texture handle, since it only needs to be calculated when the texture is loaded and can then be stored.

Another way to index the sheet is by a number. Imagine that each cell has a number; the top-left cell is 0, the top-middle cell is 1 and so on, when it gets to the last cell on the current line it keeps going on the next line.

Now you can get the minimum and maximum position of the tile (once again, assuming the origin is in the top-left) in a different way:

```
sheetPrediv = (1 / sheetWidth, 1 / sheetHeight);
minPos = ((index % sheetColumns) * spriteWidth, floor(index / sheetColumns) * spriteHeight) * sheetPrediv;
maxPos = minPos + (spriteWidth, spriteHeight) * sheetPrediv;

```

There are tons of other ways to get the index, doing it the way I've don it here are just two examples. If your origin is somewhere else (like in the bottom-left) you'll have to modify these formulas a bit. I'll leave that as an exercise.

So, now you have the texels for drawing. So bind the texture and send the texels to your shader. Alternatively you send the index to your shader and to do all the calculations there.

Remember to mark an answer for your question
> 2 votes

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


# Question
Title: Should I initialize a Box2D World per Level?
I'm using a LevelManager to load Tiled maps in my libGDX game, which stores:

**Static:**

* final `Size` of map in Tiles
* final `Size` of map in Pixels
* final `Size` of an individual tile
* `TiledMap ACTIVE_MAP`
* `World WORLD`

When the map is loaded, it creates a new World and stores it in the static `WORLD`, later populating it with static bodies based on objects found in the map's Collision layer.

My reasoning for using static is down to the fact that logically, only one map will be playable at any one time, however I've got it in my head that only constants and singletons should be static, so this feels strange for me. Is there a better, more efficient way of handling this?

**Should I have one World per Level, or a global World independent of what TiledMap is active?**

In other words, should I initialize `WORLD` once and leave it as is, making it final, or continue what I am doing and initialize it as a new World whenever a new TiledMap is loaded?

**How do I correctly dispose of all bodies within the World, essentially clearing it?**

I'm going to have to do this every time I load a new map, regardless of whether or not `WORLD` is global.

# Answer
> 1 votes
I took some time to think about the issue and realized that logically, there is no purpose for disposing the World or re-initializing it whenever a new Level is loaded it seems a lot better to dispose and reinitialize the world when a new Level is loaded - thanks to @Shiro for helping me see this. I won't have to manually clear all of the World's bodies, forces, etc.

I created a WorldManager class which contains the World and a method to "clear" it:

```
public final class WorldManager {

    public static World world;

    private WorldManager() {}

    public static void clearWorld() {
        if (world != null) {
            world.dispose();
        }

        world = new World(new Vector2(0, 0), true);
    }
}

```

In my LevelManager class, before loading a specified level, I make a call to `WorldManager.clearWorld()`

---
Tags: libgdx, box2d
---


# Question
Title: Box2D Issues determining the side of collision
I'm trying to determine which side of my object a collision is happening. In all of my searching, I have found 2 different proposed solutions, but each one has a major issue. I'm hoping that someone here can explain what steps I am missing.

**Attempt 1 : Sensors**

The first solution I tried was using Sensors on the sides of a Dynamic body. Like this :

The issue with this solution is that multiple sensors can easily collide with a single obstacle, like this :

**Attempt 2 : Determine side of contact using the World Normal**

My second solution was to get the Normal from the b2WorldManifold that is provided by the contact in BeginContact(). This works perfectly, but only for detecting the side when a collision begins, not when it ends. EndContact() doesn't have the ability to provide a World Normal. You can get the manifold, but the components of the Normal are undefined. The issue with this is that I have no way of knowing which collision just ended.

Hopefully someone knows enough about Box2D to see something simple that I am obviously missing. Thanks in advance for any input.

# Answer
> 1 votes
There exists a manifold from the time BeginContact is called just up until EndContact is called. When EndContact is called the manifold is no longer valid.

This means you can store the b2Contact pointer once BeginContact is called. For every game loop that EndContact is not called you can access the b2Contact pointer and query the manifold. This way you can update your world normal. Once EndContact is called you can just look at what your collision normal was last game loop.

# Answer
> 0 votes
* Keep the point in the middle of the object before the movement;
* Create a Vector with start in this point and end in the point in the middle of the rectangle result of the collision;
* Check what side is in contact with that vector;

# Answer
> 0 votes
If you want to check which of your body sides collided with obstacles, you can create your box-shaped body consisting of four b2EdgeShape sides having independent fixtures instead of single b2PolygonShape (in case you are using b2PolygonShape). In this way, while your are checking for contacts, can easily determine which fixture of my body is currently in contact with. I hope it helps you out.

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


# Question
Title: How not to show ads to paid customers when I decided to make it free?
I am planning to publish a paid game built with Unity. After a while I will update the game as free and will start showing ads. But I do not want my first paid customers to see the ads after installing update? How can I manage this?

Game will be both on App Store and Google Play.

Thanks

# Answer
> 1 votes
The simplest solution: you can store the initial version number of the game at installation in PlayerPrefs. Then when you add the ads, you can have a check of the minimum version number versus the initial version number. Or you can record in PlayerPrefs whether it is a paid version or not on the initial launch again.

That leaves some problems: what if someone uninstall the paid version and reinstalls the free version? You might need a way to grant them the "no-ads" flags remotely. I use in-game gift codes for that, but it requires a backend of some sort (using parse.com).

It is also susceptible to hacking of the local data, but if someone is willing to go to that length, it doesn't matter what you do - so don't worry about that.

---
Tags: unity, game-mechanics
---


# Question
Title: Capturing small details in textures without making a huge map
Ex. Nuts and bolts on a cabinet. Said items are tiny relative to the cabinet, and on a texture map looks like an indistinguishable dot. Is it worth it to separate these tiny details into a mesh of their own? Obvious cons are increasing poly count and draw calls, disregarding how much of an increase that would be. Is there a generally accepted way of going about this?

# Answer
> 0 votes
Since it sounds like you're using a human sized perspective, you can either increase your texture or your polygon budget. Usually, you would bake fine geometry into something like a normal map, but if it's that small then it probably isn't worth it unless that's a vital part of gameplay. If it is, then go ahead and use a model for it. Just be careful that you aren't blowing all your resources on things the player isn't going to look twice at.

A game with multiple size perspectives (if the player can grow or shrink to that size) could use variable level of detail - to increase the detail of now large objects - and depth of field - to hide distant objects consuming unnecessary draw cycles - for these things, but that implies a lot more engineering than it's worth if they aren't going to be spending much time there.

# Answer
> 0 votes
If you find that geometry is too heavy weight, bump mapping can be a great way of getting the appearance of geometric detail without paying the geometry costs.

# Answer
> 0 votes
Using decals and even meshes of highly varying scale for additional detail is completely fine and has been done for quite some time already (I'd say at least 20 years or so, since the dawn of somewhat realistic 3D).

Yes, it's definitely worth it. And no, there's nothing wrong about making something as long as it looks right and meets all performance requirements.

For example, The Last of Us still did things like that: http://goingsony.com/system/file\_uploads/uploads/000/002/792/original/60fps3.jpg \- if you look closely, it can be seen that level of texture detail isn't exactly matching for all foliage.

Though of course, before you make detail like that, you should probably make sure that someone will actually be able to see that detail. Not much point investing in polishing for rarely visited or distant areas.

P.S.

> into a mesh of their own

For meshes that support multiple materials, that should not be necessary. The detail can be added into the same mesh. Unless you need many meshes of the same kind together, in which case it might be easier to just export all variations separately, if you use a visual editor of any kind.

---
Tags: textures
---


title: a shader type class in c

text:
# Question
Title: a shader type class in c
Is it possible to setup something sort of like a class in C++ but in c in the simplest terms? I want to avoid using c++ but I would like to create a simple struct that has glsl shader program.

for example

```
struct shader_program
{
     GLuint shader;
     void (*create_shader)(const char* vss, const char* fss);
     void (*enableShader)(void);
     GLuint (*getUniformLoc(struct shader_program* sp, char* name);
     void (*disableShader)(void);

}

sample usage.

struct shader_program simple_shader = create_shader(.., ..);
struct shader_program advanced_shader = create_shader(.., ..);

draaw()
{
 simple_shader->enableShader();
 //...bind vai, draw, etc..
 simple_shader->disableShader();

 advanced_shader->enableShader();
 //draw
 advanced_shader->disableShader();

}

```

the main question is how would i set this up in a header and source file so that I can use a struct like this to do my rendering?

# Answer
> 0 votes
If you want to aim for a real class, I would recommend C++ if that's how you want to organize your project. However C is still totally appropriate for OpenGL. If I'm not mistaken a totally appropriate C way of doing something class-like would be:

```
// Shader.h
struct Shader{
    GLuint id;
}

Shader* createShader(char* vertexSource, char* pixelSource);
void bindShader(Shader* shader);
void unbindShader();

//Shader.c
Shader* createShader(char* vertexSource, char* pixelSource{
    //Load shader or whatever
    return new Shader(shaderID);
}

void bindShader(Shader* shader){
    glBindShader(shader->id);
}
void unbindShader(){
    glBindShader(0);
}

//Application.c
void init(){
    shader = createShader("vert source", "pixel source);
}

void draw(){
    bindShader(shader);
}

```

---
Tags: data-structure, c, architecture, struct
---


title: Screen tearing in emulator

text:
# Question
Title: Screen tearing in emulator
I'm trying to make a game boy emulator, and I'm using Windows for the graphics (`StretchDIBits`). I'm getting screen tearing like this. I tried enabling vsync in graphic settings but nothing changed.

This is how I'm doing my timing in the end of my main loop.

```
if (cpu.T >= CLOCKSPEED / 40)
{
    if (MSpassed < 25)
        Sleep(25 - (int)MSpassed);
    MSpassed = 0;
    cpu.T -= CLOCKSPEED/40;
}

```

`CLOCKSPEED` is the number of emulated CPU cycles per second. `cpu.T` is how many cpu cycles passed until now. `MSpassed` is in milliseconds. I'm measuring it with QueryPerformanceCounter.

Is the problem in the timing, the way I'm doing my graphics, or somewhere in the GB specific code?

# Answer
> 3 votes
The issue you're describing is due to a lack of Vertical Sync (v-sync). Your drawing is not in sync with your monitor's refresh rate. From my research there is no way in the Windows API by default to force VSync in anything but a DirectX application.

https://stackoverflow.com/questions/2448831/how-to-eliminate-tearing-from-animation

You have two options as I see it.

You could write your own v-sync system. Detect the refresh rate of the monitor and match your drawing to that rate. This should be totally possible from within the Windows API.

Or you could just switch to DirectX or OpenGL for drawing. It would require a lot of work to re-build your application but the payoff would be pretty significant. Hardware accelerated drawing is just faster. Not only that but you can let the hardware manage your v-sync for you.

You can test the first solution by looking up the refresh rate of your monitor in your Windows settings and then setting your emulation to run at that framerate.

---
Tags: c++, graphics, windows, emulation
---


# Question
Title: Implementing a 2D Collision method that can tell direction of collision (boxes)
Been searching for quite a while now and really struggling to find an easy way, or a good tutorial on how to create a collision detection system which can indicate what side on a box a collision has occurred.

I should specify that I am using SFML2 and their sprites class, this is what I currently use and it just picks up 2 sprites intersecting

```
//check rectangles for collision without taking into account where the collision is
bool Game::isRectCollision(sf::Sprite &sprite1, sf::Sprite &sprite2){

    sf::FloatRect r1=sprite1.getGlobalBounds();
    sf::FloatRect r2=sprite2.getGlobalBounds();
    return r1.intersects(r2);

}

```

# Answer
The Separating Axis Theorem might be what you're looking for.
Writing collision detection using SAT is easier than it seems and allows you to calculate handy things like where exactly they collided as well as the minimum translation vector. Highly recommended for shape collision detection.
> 1 votes

---
Tags: collision-detection, sfml
---


# Question
Title: blender imported sphere with mesh collider not collided
here is the scene

i imported a sphere (the blue sphere) from blender (with a hole at back), i added a mesh collider on it but it has no effect, and there is an error message Cooking::cookConvexMesh: user-provided hull must have less than 256 vertices!.

any ideas?

(update the collider work fine after i retry and retry, but the error message still stay)

# Answer
> 2 votes
The error message tells you that the (convex) Mesh collider you want to use has way too much vertices. I can think of two solutions:

1. Just use a sphere collider...
2. Create a low-poly sphere (with no more than 256 verts) mesh in blender, and use it just for collision.

---
Tags: unity
---


title: How to choose a SKSpriteNode randomly?

text:
# Question
Title: How to choose a SKSpriteNode randomly?
I want to choose from 4 enemies using random and present it on scene. For that purpose I've made this:

```
func enemyPicker() -> SKSpriteNode {
var enemyArray = [mouse, robot, drone, block, bird]
var countArray = UInt32(enemyArray.count)
var pickOneEneny = arc4random_uniform(countArray)
var randomElement = Int(pickOneEnemy)

return enemyArray.randomElement
}

```

But Xcode says to me that `SKSpriteNode does not have a member named randomElement`. And it surely doesn't, but how would I say to my function that I need it to pick and assign that random Int to an actual enemy from array?

My SpriteNodes are declared like this. Example:

```
var mouse = SKSpriteNode()
let mouseAtlas = SKTextureAtlas(named: "mouse")
var mouseArray = [SKTexture]()
mouseArray.append(mouseAtlas.textureNamed("mouse_0"));
mouseArray.append(mouseAtlas.textureNamed("mouse_1"));
mouseArray.append(mouseAtlas.textureNamed("mouse_2"));

mouse = SKSpriteNode(texture: mouseArray[0]);
self.mouse.position = CGPointMake(CGRectGetMaxX(self.frame), CGRectGetMidY(self.frame) - 138)
self.mouse.size = CGSizeMake(self.mouse.size.width, self.mouse.size.height + mouse.size.height / 2)

self.mouse.name = "mouse"
self.addChild(mouse)

```

I also tried to change `-> SKSpriteNode` to `SKTexture`, `String` and "\< T \>" and had not any luck with it.

# Answer
Your problem is in line `return enemyArray.randomElement`. This sentence tries to access a property called `randomElement` that your `enemyArray` has, but you want to get the object inside `enemyArray` that has the `randomElement` position, right? Try with this:

```
return enemyArray[randomElement]

```

More information about arrays in swift can be found here.
> 2 votes

---
Tags: ios, spritekit, swift
---


# Question
Title: current value of x for vector2 game object
I just need to push my game object in y direction not in of its x position,I need to assign it a new position but unable to access its current x position value so that can make it fix on its x position... please help

I tried this:

> ```
> Vector2 curScreenPoint = new Vector2 (need the current x position of game object , Input.mousePosition.y);
>
> ```

```
Vector2 curScreenPoint = new Vector2 (0, Input.mousePosition.y);
     Vector2 curPosition = Camera.main.ScreenToWorldPoint (curScreenPoint);
    transform.position = curPosition;

```

---

# Answer
Not entirely sure what you are trying to accomplish based on your code. Possibly you are not familiar with the MonoBehaviour object type.

Have you tried something like this:

```
Vector2 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
transform.position = new Vector2(transform.position.x, mousePos.y);

```
> 0 votes

---
Tags: unity, 2d
---


title: Unity sprites and layouts

text:
# Question
Title: Unity sprites and layouts
I am trying to learn Unity for a simple board game. The question is, is it possible to use grid layout group (or any layout component) with sprites? The goal is to fit a board into my view regardless of the aspect ratio of the device.

The following grid should contain 7 by 7 sprites and it should scale up and down (no more then lets say 100 px) and have an aspect ratio of 1. I've tried adding a canvas and a panel that has a grid layout group component but it seems like sprites are not affected when added to the panel.

Also it seems like when I try to work with a panel or a canvas they have a fixed sizes in units. Having fix sizes feels a little bit off.

Is there a way to use layout components so sprites can have relative distances between them.

So far I am stuck and lost in tutorials and feeling like the answer should not be this complicated.

Any push to the right direction is welcome.

# Answer
There are a few different approaches that you can take to get your game to work on all ratios. I will explain to you what I found works best for me, in Unity. It may be a viable option for you as well.

The concept is to set a "Viewable Area", where the camera will zoom and clamp to, regardless of the screen ratio or size.

Take a look at the following example picture:

The darker rectangle in the center is the "Viewable Area" that will always be visible. You want to put all your important game objects inside of this area, to ensure it will draw in game.

The background is left purposely larger than the Viewable area. This is important, as different ratios will cut off at different places depending on your Viewable rectangle proportions. You need to get a little clever to fill in the blank areas, the large repeating background is a great way to fill this space.

Simply create a GameObject to define your Viewable Area, and set its Position, Width and Height. You can add a spriteRenderer (1 unit sprite, for the size to be correct) like I did to visually see it in your scene. Then, attach the below script to your Camera, and drag this object to the "Area" property to link the script to the Viewable Area. The code should do the rest for you.

Comment if you have any questions about this implementation.

```
using UnityEngine;
using System.Collections;

public class CameraZoom : MonoBehaviour
{
    public Transform Area;

    public void Update()
    {
        float height = Area.localScale.y * 100;
        float width = Area.localScale.x * 100;

        float w = Screen.width / width;
        float h = Screen.height / height;

        float ratio = w / h;

        float size = (height / 2) / 100f;

        if (w < h)
            size /= ratio;

        Camera.main.orthographicSize = size;

        Vector2 position = Area.transform.position;

        Vector3 camPosition = position;
        Vector3 point = Camera.main.WorldToViewportPoint(camPosition);
        Vector3 delta = camPosition - Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z));
        Vector3 destination = transform.position + delta;

        transform.position = destination;
    }

}

```

To optimize, move this code to its own function and manually call it when your scene moves around, instead of calling it on every Update() cycle.
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: Why is addressing an array of vectors more efficient than addressing an array of matrices in Cg?
According to Nvidia's Cg tutorial (in the note section right under 6.5.2), addressing an array of vectors seems to be more efficient than addressing an array of matrices. The reason it mentions is because the index is floating point value instead of integer.

Could anyone explain this a little bit?

Here is the quote:

> For performance reasons, the program treats `boneMatrix` as an array of `float4` vectors rather than an array of `float3x4 matrices. The`matrixIndex\` array contains floating-point values instead of integers, and so the addressing of a single array of vectors is more efficient than accessing an array of matrices. The implication of this is that the indices in the matrixIndex vector should be three times the actual matrix index. So, the program assumes 0 is the first matrix in the array, 3 is the second matrix, and so on. The indices are fixed for each vertex, so you improve performance by moving this "multiply by 3" outside the vertex program.

And here is the Cg program it's referring to:

```
// Example 6-5. The C6E5v_skin4m Vertex Program
void C6E5v_skin4m(float3   position    : POSITION,
                  float3   normal      : NORMAL,
                  float2   texCoord    : TEXCOORD0,
                  float4   weight      : TEXCOORD1,
                  float4   matrixIndex : TEXCOORD2,
              out float4   oPosition   : POSITION,
              out float2   oTexCoord   : TEXCOORD0,
              out float4   color       : COLOR,
          uniform Light    light,
          uniform float4   boneMatrix[72], // 24 matrices
          uniform float4x4 modelViewProj)
{
  float3 netPosition = 0, netNormal = 0;

  for (int i = 0; i < 4; i++) {
    float index = matrixIndex[i];
    float3x4 model = float3x4(boneMatrix[index + 0],
                              boneMatrix[index + 1],
                              boneMatrix[index + 2]);

    float3 bonePosition = mul(model, float4(position, 1));
    // Assume no scaling in matrix, just rotate & translate
    float3x3 rotate = float3x3(model[0].xyz,
                               model[1].xyz,
                               model[2].xyz);

    float3 boneNormal = mul(rotate, normal);
    netPosition += weight[i] * bonePosition;
    netNormal   += weight[i] * boneNormal;
  }

  netNormal = normalize(netNormal);
  oPosition = mul(modelViewProj, float4(netPosition, 1));
  oTexCoord = texCoord;
  color = computeLighting(light, netPosition, netNormal);
}

```

# Answer
> For performance reasons, the program treats boneMatrix as an array of float4 vectors rather than an array of float3x4 matrices. The matrixIndex array contains floating-point values instead of integers, and so the addressing of a single array of vectors is more efficient than accessing an array of matrices.

There is definitely a performance implication for using an array matrices, personally I can see two reasons for this. ***Memory layout*** and ***index calculations***.

Generally speaking contiguous memory layout is much faster to access than non-contiguous memory layout. It's a common practice to flatten 2D arrays into 1D arrays. As noted the implication is that it leaks the implementation so you have to handle this fact by changing the indexing.

But I can be wrong, I suspect that the matrix implementation in Cg language actually a 1D array. So this brings us to the second point, if the implementation in Cg of a matrix is actually a 1D array the only different between using an array of matrices or array of vectors (flattened matrix) is actually the index calculation, given in the article they are using floating point to calculate the index and a single precision floating point multiply, add, and multiply-add take 4 clock cycles per warp. The arrays of vectors only needs one index the array of matrices need two, this leads to less instructions per lookup, and remember in shaders every instruction matters.

Update regarding your question in the comments:

> But according to the code, they actually convert the vectors back to matrices in the for loop. Isn't that be more efficient to do something like using an array of matrices and index it directly to get the model matrix? It will be only one indexing instead of three when constructing the model matrix.

What you said makes sense, what I speculate is that the compiler will notice that boneMatrix doesn't change. So the compiler won't allocate a new matrix and just reference the old values, so it's not actually constructing a new matrix just aliasing the vectors to be able to use matrix operations. But how can we be sure? someone need to check the generated code..

Update: this has been confirmed by @EternalWind (check the comments) the compiler doesn't construct a new matrix but actually reference the vectors, moreover it was able to vectorize the operation using dot product.
> 1 votes

---
Tags: shaders, cg
---


title: AssetManager proper usage in libgdx

text:
# Question
Title: AssetManager proper usage in libgdx
I am a beginner in libgdx and I am coding a simple game. This game is like a word puzzle where each letter is a texture. Before loading the first level I need to load into memory 26 textures, one for each alphabet letter, and also an English dictionary stored in memory as a `.txt` file. The problem is that my dictionary needs to be processed and loaded into memory (complexity Big-O is O(n) where n is around 200k). Where should I process it? Inside the asset manager class or in the class where it will actually be used?

Also, different levels may use the exact same textures so it would be great to load them in memory only once rather than disposing them every time a level ends. Is storing them in a static variable in the Assetmanager class a nice solution to this problem?

# Answer
About textures loading, yes i suggest you to make them static in the AssetManager class and then declaring them in the "level" class with `Texture letterA = AssetManager.letterA` and so on.

Same goes for the dictionary (i never had to process a .txt file so i don't know if you're going to declare it as a String or else..).

I usually make `static` every asset that is not going to be modified, and use it in other classes like i wrote.
> 1 votes

---
Tags: java, android, libgdx, resource-management
---