# Question
Title: Problem Rendering a Wireframe Cube and Grid with DirectX 11
I am trying to draw a 3D Wireframe (just the lines that connect each vertex) Cube and a 10x10 grid with D3D11. So far, this is my code

```
//************************************************************
//************ INCLUDES & DEFINES ****************************
//************************************************************

#include <iostream>
#include <ctime>
#include "XTime.h"

using namespace std;

#include <d3d11.h>
#include <d3dx11.h>
#include <d3d10.h>
#include <DirectXMath.h>
#include <DirectXColors.h>
#include <DirectXCollision.h>
#include <DirectXPackedVector.h>
#include <D3dx9math.h>
#include "Trivial_VS.csh"
#include "Trivial_PS.csh"

#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dx11.lib")
#pragma comment(lib, "d3d10.lib")

using namespace DirectX::Colors;
using namespace DirectX::Internal;
using namespace DirectX::PackedVector;
using namespace DirectX::TriangleTests;

#define BACKBUFFER_WIDTH    500
#define BACKBUFFER_HEIGHT   500

//************************************************************
//************ SIMPLE WINDOWS APP CLASS **********************
//************************************************************

class DEMO_APP
{
    HINSTANCE                       application;
    WNDPROC                         appWndProc;
    HWND                            window;
    ID3D11Device *device = 0;
    ID3D11DeviceContext *deviceContext = 0;
    ID3D11RenderTargetView *RTV = 0;
    IDXGISwapChain *swapChain = 0;
    ID3D11View *view = 0;
    ID3D11Debug *debugger = 0;
    ID3D11Texture2D *swapChainBuffer = 0;
    D3D11_VIEWPORT viewport;
    ID3D11InputLayout* inputLayout;
    XTime timer;
    int XDir = 1;
    int YDir = 1;

    ID3D11Buffer *cubeBuffer;
    unsigned int numCubeVertices = 24;

    ID3D11Buffer *gridBufferC;
    unsigned int numGridVertices = 44;

    ID3D11VertexShader *vertexShader;
    ID3D11PixelShader *pixelShader;

    ID3D11Buffer * constantViewBuffer;

    struct SEND_TO_VRAM
    {
        DirectX::XMVECTORF32 constantColor;
        DirectX::XMFLOAT2 constantOffset;
        DirectX::XMFLOAT2 padding;
        DirectX::XMMATRIX worldMatrix;
        DirectX::XMMATRIX viewMatrix;
        DirectX::XMMATRIX projectionMatrix;
    };

    SEND_TO_VRAM toShaderCube;

    SEND_TO_VRAM toShaderGridC;

public:
    struct SIMPLE_VERTEX
    {
        DirectX::XMFLOAT2 position2D;
    };

    struct ROBUST_VERTEX
    {
        DirectX::XMFLOAT4 position;
    };

    DEMO_APP(HINSTANCE hinst, WNDPROC proc);
    bool Run();
    bool ShutDown();
};

//************************************************************
//************ CREATION OF OBJECTS & RESOURCES ***************
//************************************************************

DEMO_APP::DEMO_APP(HINSTANCE hinst, WNDPROC proc)
{
    application = hinst;
    appWndProc = proc;

    WNDCLASSEX  wndClass;
    ZeroMemory( &wndClass, sizeof( wndClass ) );
    wndClass.cbSize         = sizeof( WNDCLASSEX );
    wndClass.lpfnWndProc    = appWndProc;
    wndClass.lpszClassName  = L"DirectXApplication";
    wndClass.hInstance      = application;
    wndClass.hCursor        = LoadCursor( NULL, IDC_ARROW );
    wndClass.hbrBackground  = ( HBRUSH )( COLOR_WINDOWFRAME );
    RegisterClassEx( &wndClass );

    RECT window_size = { 0, 0, BACKBUFFER_WIDTH, BACKBUFFER_HEIGHT };
    AdjustWindowRect(&window_size, WS_OVERLAPPEDWINDOW, false);

    window = CreateWindow(  L"DirectXApplication", L"CGS Hardware Project", WS_OVERLAPPEDWINDOW & ~(WS_THICKFRAME|WS_MAXIMIZEBOX),
                            CW_USEDEFAULT, CW_USEDEFAULT, window_size.right-window_size.left, window_size.bottom-window_size.top,
                            NULL, NULL, application, this );

    ShowWindow( window, SW_SHOW );

    DXGI_SWAP_CHAIN_DESC swapChainDesc;

    ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));

    swapChainDesc.BufferCount = 1;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDesc.BufferDesc.Height = BACKBUFFER_HEIGHT;
    swapChainDesc.BufferDesc.Width = BACKBUFFER_WIDTH;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.OutputWindow = window;
    swapChainDesc.SampleDesc.Count = 4;
    swapChainDesc.Windowed = true;

    UINT flags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;

    if (_DEBUG)
    {
        flags |= D3D11_CREATE_DEVICE_DEBUG;
    }

    HRESULT hr = D3D11CreateDeviceAndSwapChain(NULL,
        D3D_DRIVER_TYPE_HARDWARE,
        NULL,
        flags,
        NULL,
        NULL,
        D3D11_SDK_VERSION,
        &swapChainDesc,
        &swapChain,
        &device,
        NULL,
        &deviceContext);

    hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&swapChainBuffer);

    hr = device->CreateRenderTargetView(swapChainBuffer, NULL, &RTV);

    hr = device->QueryInterface(__uuidof(ID3D11Debug), (void**)&debugger);

    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = swapChainDesc.BufferDesc.Width;
    viewport.Height = swapChainDesc.BufferDesc.Height;
    viewport.MinDepth = 0;
    viewport.MaxDepth = 1;

    ROBUST_VERTEX cube[24];

    //Cube Init
    {
    for (unsigned int i = 0; i < numCubeVertices; ++i)
    {
        cube[i].position.w = 1;
    }
    //TOPLEFT
    cube[0].position.x = -0.25f;
    cube[0].position.y = 0.25f;
    cube[0].position.z = -0.25f;
    cube[1].position.x = -0.25f;
    cube[1].position.y = 0.25f;
    cube[1].position.z = 0.25f;

    //TOPBACK
    cube[2].position.x = -0.25f;
    cube[2].position.y = 0.25f;
    cube[2].position.z = 0.25f;
    cube[3].position.x = 0.25f;
    cube[3].position.y = 0.25f;
    cube[3].position.z = 0.25f;

    //TOPRIGHT
    cube[4].position.x = 0.25f;
    cube[4].position.y = 0.25f;
    cube[4].position.z = 0.25f;
    cube[5].position.x = 0.25f;
    cube[5].position.y = 0.25f;
    cube[5].position.z = -0.25f;

    //TOPFRONT
    cube[6].position.x = 0.25f;
    cube[6].position.y = 0.25f;
    cube[6].position.z = -0.25f;
    cube[7].position.x = -0.25f;
    cube[7].position.y = 0.25f;
    cube[7].position.z = -0.25f;

    //BOTTOMLEFT
    cube[8].position.x = -0.25f;
    cube[8].position.y = -0.25f;
    cube[8].position.z = -0.25f;
    cube[9].position.x = -0.25f;
    cube[9].position.y = -0.25f;
    cube[9].position.z = 0.25f;

    //BOTTOMBACK
    cube[10].position.x = -0.25f;
    cube[10].position.y = -0.25f;
    cube[10].position.z = 0.25f;
    cube[11].position.x = 0.25f;
    cube[11].position.y = -0.25f;
    cube[11].position.z = 0.25f;

    //BOTTOMRIGHT
    cube[12].position.x = 0.25f;
    cube[12].position.y = -0.25f;
    cube[12].position.z = 0.25f;
    cube[13].position.x = 0.25f;
    cube[13].position.y = -0.25f;
    cube[13].position.z = -0.25f;

    //BOTTOMFRONT
    cube[14].position.x = 0.25f;
    cube[14].position.y = -0.25f;
    cube[14].position.z = -0.25f;
    cube[15].position.x = -0.25f;
    cube[15].position.y = -0.25f;
    cube[15].position.z = -0.25f;

    //CORNER FRONTLEFT
    cube[16].position.x = -0.25f;
    cube[16].position.y = 0.25f;
    cube[16].position.z = -0.25f;
    cube[17].position.x = -0.25f;
    cube[17].position.y = -0.25f;
    cube[17].position.z = -0.25f;

    //CORNER BACKLEFT
    cube[18].position.x = -0.25f;
    cube[18].position.y = 0.25f;
    cube[18].position.z = 0.25f;
    cube[19].position.x = -0.25f;
    cube[19].position.y = -0.25f;
    cube[19].position.z = 0.25f;

    //CORNER BACKRIGHT
    cube[20].position.x = 0.25f;
    cube[20].position.y = 0.25f;
    cube[20].position.z = 0.25f;
    cube[21].position.x = 0.25f;
    cube[21].position.y = -0.25f;
    cube[21].position.z = 0.25f;

    //CORNER FRONTRIGHT
    cube[22].position.x = 0.25f;
    cube[22].position.y = 0.25f;
    cube[22].position.z = -0.25f;
    cube[23].position.x = 0.25f;
    cube[23].position.y = -0.25f;
    cube[23].position.z = -0.25f;
}

    ROBUST_VERTEX gridC[44];

    //Grid Init
    {
    for (unsigned int i = 0; i < numGridVertices; ++i)
    {
        gridC[i].position.y = 0;
        gridC[i].position.w = 1;
    }

    //Borders
    {
        gridC[0].position.x = -0.5;
        gridC[0].position.z = -0.5;
        gridC[1].position.x = -0.5;
        gridC[1].position.z = 0.5;

        gridC[2].position.x = -0.5;
        gridC[2].position.z = 0.5;
        gridC[3].position.x = 0.5;
        gridC[3].position.z = 0.5;

        gridC[4].position.x = 0.5;
        gridC[4].position.z = 0.5;
        gridC[5].position.x = 0.5;
        gridC[5].position.z = -0.5;

        gridC[6].position.x = 0.5;
        gridC[6].position.z = -0.5;
        gridC[7].position.x = -0.5;
        gridC[7].position.z = -0.5;
    }

        //CrossSections
    {
        float counter = -0.4;
        for (unsigned int i = 8; i < 26;)
        {
            gridC[i].position.x = -0.5;
            gridC[i].position.z = counter;
            ++i;
            gridC[i].position.x = 0.5;
            gridC[i].position.z = counter;
            ++i;
            if (counter >= -0.15 && counter <= -0.05)
            {
                counter = 0;
            }
            else
            {
                counter += 0.1;
            }
        }

        counter = -0.4;
        for (unsigned int i = 26; i < 44;)
        {
            gridC[i].position.z = -0.5;
            gridC[i].position.x = counter;
            ++i;
            gridC[i].position.z = 0.5;
            gridC[i].position.x = counter;
            ++i;
            if (counter >=-0.15 && counter<=-0.05)
            {
                counter = 0;
            }
            else
            {
                counter += 0.1;
            }
        }

    }

}

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

    cubeBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    cubeBufferDesc.ByteWidth = sizeof(ROBUST_VERTEX)*numCubeVertices;
    cubeBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    cubeBufferDesc.MiscFlags = 0;
    cubeBufferDesc.StructureByteStride = 0;

    D3D11_SUBRESOURCE_DATA subResDataCube;
    ZeroMemory(&subResDataCube, sizeof(D3D11_SUBRESOURCE_DATA));
    subResDataCube.pSysMem = cube;
    subResDataCube.SysMemPitch = 0;
    subResDataCube.SysMemSlicePitch = 0;

    device->CreateBuffer(&cubeBufferDesc, &subResDataCube, &cubeBuffer);

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

    gridBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    gridBufferDesc.ByteWidth = sizeof(ROBUST_VERTEX)*numGridVertices;
    gridBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    gridBufferDesc.MiscFlags = 0;
    gridBufferDesc.StructureByteStride = 0;

    D3D11_SUBRESOURCE_DATA subResDataGrid;
    ZeroMemory(&subResDataGrid, sizeof(D3D11_SUBRESOURCE_DATA));
    subResDataGrid.pSysMem = gridC;
    subResDataGrid.SysMemPitch = 0;
    subResDataGrid.SysMemSlicePitch = 0;

    device->CreateBuffer(&gridBufferDesc, &subResDataGrid, &gridBufferC);

    device->CreateVertexShader(Trivial_VS, sizeof(Trivial_VS), NULL, &vertexShader);
    device->CreatePixelShader(Trivial_PS, sizeof(Trivial_PS), NULL, &pixelShader);

    D3D11_INPUT_ELEMENT_DESC inputElementDesc[] =
    {
        {"POSITION",0,DXGI_FORMAT_R32G32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0}
    };

    device->CreateInputLayout(inputElementDesc, 1, &Trivial_VS, sizeof(Trivial_VS), &inputLayout);

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

    constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    constantBufferDesc.ByteWidth = sizeof(SEND_TO_VRAM);
    constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    constantBufferDesc.MiscFlags = 0;
    constantBufferDesc.StructureByteStride = 0;

    device->CreateBuffer(&constantBufferDesc, NULL, &constantViewBuffer);

    toShaderCube.constantOffset.x = 0;
    toShaderCube.constantOffset.y = 0;
    toShaderCube.constantColor = DirectX::Colors::Green;
    toShaderCube.worldMatrix = DirectX::XMMatrixIdentity();

    toShaderGridC.constantOffset.x = 0;
    toShaderGridC.constantOffset.y = 0;
    toShaderGridC.constantColor = DirectX::Colors::White;
    toShaderGridC.worldMatrix = DirectX::XMMatrixIdentity();

}

//************************************************************
//************ EXECUTION *************************************
//************************************************************

bool DEMO_APP::Run()
{

    float Yscale = 1.0f / (tan(DirectX::XMConvertToRadians(0.5*60)));
    float aspectRatio = viewport.Width / viewport.Height;
    float Xscale = Yscale*aspectRatio;
    float zNear = 0.1f;
    float zFar = 10.0f;

    DirectX::XMMATRIX viewMatrix;
    DirectX::XMMATRIX projectionMatrix(Xscale, 0, 0, 0,
        0, Yscale, 0, 0,
        0, 0, (zFar / (zFar - zNear)), 1,
        0, 0, -1.0f*(zFar*zNear) / (zFar - zNear), 0);

    projectionMatrix = DirectX::XMMatrixTranspose(projectionMatrix);

    toShaderCube.projectionMatrix = projectionMatrix;
    toShaderGridC.projectionMatrix = projectionMatrix;

    float cameraAngle = DirectX::XMConvertToRadians(18);
    viewMatrix = DirectX::XMMatrixRotationX(cameraAngle);
    viewMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixTranslation(0, 0, -1.5), viewMatrix);
    viewMatrix = DirectX::XMMatrixInverse(NULL,viewMatrix);
    viewMatrix = DirectX::XMMatrixTranspose(viewMatrix);

    toShaderCube.viewMatrix = viewMatrix;
    toShaderGridC.viewMatrix = viewMatrix;

    //timer.TotalTime() just returns the amount of time since the program started
    toShaderCube.worldMatrix = DirectX::XMMatrixIdentity();
    toShaderCube.worldMatrix = DirectX::XMMatrixTranslation(0, 0.25, 0);
    toShaderCube.worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationY(DirectX::XMConvertToRadians(timer.TotalTime()*50)),
                            toShaderCube.worldMatrix);
    toShaderCube.worldMatrix = DirectX::XMMatrixTranspose(toShaderCube.worldMatrix);

    deviceContext->OMSetRenderTargets(1, &RTV, 0);
    deviceContext->RSSetViewports(1, &viewport);
    deviceContext->ClearRenderTargetView(RTV, DirectX::Colors::Black);

    D3D11_MAPPED_SUBRESOURCE mappedSubRes;
    ZeroMemory(&mappedSubRes, sizeof(mappedSubRes));
    deviceContext->Map(constantViewBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &mappedSubRes);
    memcpy(mappedSubRes.pData, &toShaderGridC, sizeof(SEND_TO_VRAM));
    deviceContext->Unmap(constantViewBuffer, NULL);

    deviceContext->VSSetConstantBuffers(0, 1, &constantViewBuffer);

    UINT stride = sizeof(ROBUST_VERTEX);
    UINT offset = 0;
    deviceContext->IASetVertexBuffers(0, 1, &gridBufferC, &stride, &offset);

    deviceContext->IASetInputLayout(inputLayout);
    deviceContext->VSSetShader(vertexShader, 0, 0);
    deviceContext->PSSetShader(pixelShader, 0, 0);

    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);

    deviceContext->Draw(numGridVertices, 0);

    ZeroMemory(&mappedSubRes, sizeof(mappedSubRes));
    deviceContext->Map(constantViewBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &mappedSubRes);
    memcpy(mappedSubRes.pData, &toShaderCube, sizeof(SEND_TO_VRAM));
    deviceContext->Unmap(constantViewBuffer, NULL);

    stride = sizeof(ROBUST_VERTEX);
    offset = 0;
    deviceContext->IASetVertexBuffers(0, 1, &cubeBuffer, &stride, &offset);
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);

    deviceContext->Draw(numCubeVertices, 0);

    swapChain->Present(0, 0);
    return true;
}

//************************************************************
//************ DESTRUCTION ***********************************
//************************************************************

bool DEMO_APP::ShutDown()
{
    deviceContext->ClearState();

    deviceContext->Release();
    deviceContext = NULL;
    swapChain->Release();
    swapChain = NULL;
    device->Release();
    device = NULL;
    RTV->Release();
    RTV = NULL;
    debugger->Release();
    debugger = NULL;
    swapChainBuffer->Release();
    swapChainBuffer = NULL;
    inputLayout->Release();
    inputLayout = NULL;
    cubeBuffer->Release();
    cubeBuffer = NULL;
    gridBufferC->Release();
    gridBufferC = NULL;
    vertexShader->Release();
    vertexShader = NULL;
    pixelShader->Release();
    pixelShader = NULL;
    constantViewBuffer->Release();
    constantViewBuffer = NULL;
    //view->Release();
    //view = NULL;

    UnregisterClass( L"DirectXApplication", application );
    return true;
}

//************************************************************
//************ WINDOWS RELATED *******************************
//************************************************************

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow );
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE, LPTSTR, int )
{
    srand(unsigned int(time(0)));
    DEMO_APP myApp(hInstance,(WNDPROC)WndProc);
    MSG msg; ZeroMemory( &msg, sizeof( msg ) );
    while ( msg.message != WM_QUIT && myApp.Run() )
    {
        if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }
    myApp.ShutDown();
    return 0;
}
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    if(GetAsyncKeyState(VK_ESCAPE))
        message = WM_DESTROY;
    switch ( message )
    {
        case ( WM_DESTROY ): { PostQuitMessage( 0 ); }
        break;
    }
    return DefWindowProc( hWnd, message, wParam, lParam );
}

```

Here's the Trivial\_VS hlsl shader file. The trivial\_Ps doesn't do anything currently

```
struct INPUT_VERTEX
{
    float2 coordinate : POSITION;
};

struct OUTPUT_VERTEX
{
    float4 colorOut : COLOR;
    float4 projectedCoordinate : SV_POSITION;
};

cbuffer THIS_IS_VRAM : register( b0 )
{
    float4 constantColor;
    float2 constantOffset;
    float2 padding;
    float4x4 worldMatrix;
    float4x4 viewMatrix;
    float4x4 projectionMatrix;
};

OUTPUT_VERTEX main( INPUT_VERTEX fromVertexBuffer )
{
    OUTPUT_VERTEX sendToRasterizer = (OUTPUT_VERTEX)0;
    sendToRasterizer.projectedCoordinate.w = 1;

    sendToRasterizer.projectedCoordinate.xy = fromVertexBuffer.coordinate.xy;

    sendToRasterizer.projectedCoordinate.xy += constantOffset;

    sendToRasterizer.projectedCoordinate = mul(sendToRasterizer.projectedCoordinate, worldMatrix);
    sendToRasterizer.projectedCoordinate = mul(sendToRasterizer.projectedCoordinate, viewMatrix);
    sendToRasterizer.projectedCoordinate = mul(sendToRasterizer.projectedCoordinate, projectionMatrix);

    sendToRasterizer.projectedCoordinate.x /= sendToRasterizer.projectedCoordinate.w;
    sendToRasterizer.projectedCoordinate.y /= sendToRasterizer.projectedCoordinate.w;
    sendToRasterizer.projectedCoordinate.z /= sendToRasterizer.projectedCoordinate.w;

    sendToRasterizer.colorOut = constantColor;

    return sendToRasterizer;
}

```

Right now, the only thing that is being drawn is a green square that rotates the way the cube should and a white line where the grid should be.

Ideally, I'd like to have the 10x10 white grid and the 3D Wireframe cube sitting on top of the grid and rotating. I don't want to fill in any of the faces with a texture and I don't want to have two triangles representing each face with a diagonal cutting through the face. I feel like I'm missing some aspect of working specifically in 3D.

Also, if you know how to debug what the values in the shader are changing to as I multiply them by each matrix, that would definitely be a help as well but really I just want to get my objects drawn.

Thanks for anything you can help out with!

# Answer
```
D3D11_INPUT_ELEMENT_DESC inputElementDesc[] =
{
    {"POSITION",0,DXGI_FORMAT_R32G32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0}
};

```

You need to change the format to DXGI\_FORMAT\_R32G32B32A32 or you won't be able to send the z and w information of the vertex to the vertex shader.
> 2 votes

---
Tags: 3d, directx, rendering, directx11, matrix
---


# Question
Title: Why are microtransactions more or less universally hated?
In many games nowadays we see micro-transactions in the form of in-game purchases. The benefits of these purchases can be anything from disabling ads, cosmetic unlocks, or in-game currency. Here's an example:

That is of course an extreme example of pricey micro-transactions. But it seems that even more "reasonable" in-game purchases are more or less despised by the community as a whole, even though they are there to help monetize the game and without them the game wouldn't exist.

So why are micro-transactions so despised?

# Answer
> 90 votes
This is my own personal opinon on the subject, and some other people may dislike microtransactions for other reasons, but hopefully this will give you a first element of answer.

I personally dislike microtransactions because they are not honest and up front with the customer.

They are often associated with psychological tricks to make you spend money. One basic example of these tricks is create a fake currency (like the gems in your example) which act as a layer to detach the customer from the money which is actually spent. Another example would be to tease the player by giving him one free item, which will later on only be available through microtransactions. Much more devious methods exist.

There's also the issue that you don't know beforehand what will be locked up behind microtransactions when you buy the game. Of course you can make your researchs, but there's a difference between buying a game without microtransactions and knowing you can explore it fully without any constraints, and buying a game to later on realize some of the content is not available.

And of course, there's the slightly different issue of competitive games where microtransactions can give you an edge. It's hard to not feel cheated in this case.

# Answer
> 54 votes
Back in the day when apps were $1-$2 (or the occasional $5 or so for something above and beyond or very specialized) I bought quite a lot of apps. Buying an app and then having full control over the game play is terrific.

Now that apps have gone to free download + microtransactions, I have stopped paying for anything completely.

**Why pay to play is terrible:**

* You have no idea what the true cost of the game is. It is generally hidden, and you only find out after passing a few levels that you need to pay $10 for a "package" to get your further. But what next? Many times the prices keep going up, or the credits required in the game escalate so you are required to buy substantially more credits to make progress.
* For multiplayer games, the enjoyment of competition and skill is overshadowed by who is willing to spend more. When you find other players are beating you because they are spending more money on the game, and there is basically no limit to the amount you can spend, most people will stop playing. I believe it's a very small percentage of people who can't control their spending who make the most money for game publishers. Check out the reviews for Mobile Strike and you will see people who claim to have spent thousands of dollars on the game. Ridiculous! You can see people get hooked and keep pumping money in because of the sunk cost fallacy (aka Escalation of commitment).
* The feeling that the game is constantly tricking you, cheating you, or is generally stacked against you. **"This game cheats!"** is so commonly yelled at games because players want an even play field, and any unfair advantage the computer has against the player is not received well. When the whole point of the game is to put up arbitrary unfair obstacles in your way that can only be removed by paying, players feel scammed.
* The prices are ridiculous. $100 for a package of gems that will last you a week, for a simple phone app? I can buy several high end games for my PC that will give me much more enjoyment for the same price. Who pays these prices?

I'd love to pay a fair price for a game, but the current model seems aimed at people who make poor financial decisions.

# Answer
> 43 votes
People hate **scams and price increases**, and have been taught to associate micro-transactions with both.

In some cases, especially most of the early cases, micro-transactions were used for illegal scams. There was a time when Apple and Google ignored the password requirement for payments, under some conditions, which was used to prey on children and (other) addicts.

In far too many other cases, micro-transaction are legal scams. Pay to win, pay to avoid grinding, etc.

In many of the remaining cases, micro-transactions end up being either a real or a perceived price increase over past pricing, or unethically milk gambling habits while circumventing gambling laws (loot boxes/crates).

In those cases that are none of the above, there are significantly fewer complaints about micro-transactions. IIRC, one example of those was the first version of Heroes of the Storm - but the current version offers random loot crates for money.

# Answer
> 26 votes
I would go a bit further than what Eldy said (+1) and quote this additional bit from a Rolling Stone article on the matter:

> A free-to-play game does not sell its in-game currency or items; it doesn’t sell anything, in fact. It holds hostage the one thing that is obviously more valuable than money. They hold hostage your time in this world \[...\] You still lose in the end, because you’ve traded money for time. You haven’t purchased a game. You haven’t incentivized quality through the dissemination of your money, which is the only real power an individual holds in a free market. You have been sold back time in your life to do something, anything, else. All the confusion created by multiple in-game currencies, endlessly adjusted pay scales for items, manufactured fluctuations in a game’s self-contained market, and so on, is an endless loop meant to divide your spending from the game’s true value proposition: time, or, your actual life away from the game.

The above does assume that the game (eventually) offers all its contents just through grinding and that microtransactions only speed up that aspect. That isn't always the case though; there are certainly games where some items with gameplay value can only be purchased with real money. But then it's probably improper to call it free-to-play anymore, maybe just free-to-play-some-portion.

As for buying in-game advantages over other players (even if just cosmetic), there's a UC Berkeley paper that says, in its abstract:

> In one survey and two experimental scenario-studies with active gamers as participants (total N = 532), we found evidence supporting the idea that a player using microtransactions will be judged more negatively. More specifically, we find that gamers dislike it more when microtransactions allow the buying of functional benefits (that provide an in-game advantage) than when they are merely ornamental, and players who buy these functional benefits are respected less. In Studies 2 and 3 we found that players who use microtransactions are perceived as having a lower skill and status. This happens both when the microtransaction-using player is an enemy who bought a competitive advantage, as well as in games where one cooperates with the microtransaction-using player and the advantage is thus effectively shared.

# Answer
> 26 votes
Because it’s nickle-‘n-diming, nothing else.

Just imagine you go to Disney, and pay 20$ to get in the park, and while you walk along, every some yards there is a turnstyle, where you need to pay another 4.99$ to pass. You have no idea how many more are coming, and either you pay them all, or you turn around and wasted all the money you already paid. Would you like that park?

# Answer
> 18 votes
Players don't care about the economics of game production cost. I spent all my Saturdays and some Sundays for 6 months to make one of my games. A friend, when presented with having to pay $3 for it, said that I owed him a beer for buying it. No, he got a game that I worked hard to make.

Players don't want to pay for a game, no matter how cheap. Many, many excellent iPhone games were $1 or $2 before the advent of common microtransactions in games.

The best way to get people to pay for microtransactions is to link them to player performance (known as "Pay to Win"), since most players want to perform better. So one reason people hate these things is because it means that people willing to spend more money than them will be able to beat them regardless of skill.

The other reason people don't like these transactions is because ultimately it means that games are more expensive. Since they're not willing to pay more than $60 for AAA games, which have been that price for decades while cost of production has gone up, the big studios are going to look for ways to pay these huge budgets. So now we have the phenomenon of buying a game like Overwatch, but still being asked to buy loot crates.

I work in the games industry, and have been on mobile projects for many years now. I see what goes on behind the curtain; I see how hard it is to get people to keep playing and more importantly pay. Budgets for even what seem like small mobile games are in the millions of dollars. The support infrastructure for customer support, content delivery, patch delivery, content production and many other facets of game development are very expensive to maintain.

We work hard to give players the best game we can, but we can't continue to do that if we can't pay our mortgages and eat. So we will adapt to the market, and find whatever way we can to pay the bills. At this moment in time, that means microtransactions. Perhaps, I hope, this will change.

# Answer
> 14 votes
**The cost is not entirely known up-front**

Let's compare against two other monetization models;

Players are all too happy to shell out $60 for a triple-A title that has decent reviews - because they understand the cost that it will incur to them. They feel like they can appropriately weigh the cost against the reviews (and their preferences) to decide if they want to invest their time in the game.

Players are also quite happy to buy into subscription-based services - most MMO's use this format, and are quite successful because of it. This subscription is not generally tied to your ingame actions, and you pay regardless of if you play. But, again, this is a well-understood cost to the player. There is no surprise here, they understand what they're getting.

But microtransactions are more uncertain. Players don't know if they'll end up spending $3 or $30 over the course of a week or month of gameplay. There's no upper limit to the amount they *might* need to spend in order to play the game the way they want.

**It frequently reminds the players that they are losing real money**

If you ask a player for a lump sum at the outset, or silently bill them every month, they forget about the money. But if you constantly harangue them to buy more skins or loot crates, they are viscerally aware that they are constantly spending money in the game. This is bad, because even if you only ask for a dollar or two at a time, doing so a dozen times *feels* like you're asking for more than if you just asked for $30 up-front.

Most mammals act like this; our reward centers are focused on getting rewards *more often*, not necessarily in larger amounts. Similarly, we feel costs more strongly if we incur them more often. A pet cat who is fed multiple times per day is much happier than if the exact same amount of food was given to them all at once.

**The cost is usually not associated with things that actually incur development cost**

Let's say you're playing a non-pay-to-win game, and you buy some hats or skins. The assumption is that because the *game* was free, but the *skins* cost money, that it must be costly to produce skins. But this is ludicrous, skins and hats are the easiest things in the game to produce! Players know this, and so when you demand $1 for a fancy hat, the cost is associated with *the hat*, and players feel a bit cheated because they know that the hat couldn't have taken more than a dozen or so man-hours to slap together, and it seems ludicrous to demand so much money for something like that.

***TL;DR***

Microtransactions are hated because they activate all of our uncertainties and biases about money.

# Answer
> 14 votes
As a hobby game designer, I have an especially deep hatred for microtransaction for a reason that I think many players also understand instinctively:

If your game has microtransactions as its business model, it most likely means that your game design has been mutilated to maximize the profit. That means progress will be artificially slowed so that people buy things that speed up progress. It means there will be soft or hard barriers that are best overcome by spending money and that have no other place in the gameplay.

In a movie analogy, it means your movie is not only interrupted by advertisement, it has been scripted and edited to maximize the opportunities for ad interruptions.

That means the game is not as good as it could be, and not even as good as you could have made it. It has been intentionally crippled and downgraded to maximize profit. This is the **opposite** of what I expect from an honest transaction. I want to give you money and in return you should try to entertain me in the best way possible. But with microtransactions, I am no longer a valued customer, I am a mark to be fleeced.

# Answer
> 12 votes
It's not the microtransactions *per se* that are hated.

It's the hate-able game designs and the way the sale items are designed, which happen to use microtransactions.

For example:

* Microtransactions for advantages, creating pay-to-win games where players are essentially in an endless bidding war with each other, and/or free players are at a huge disadvantage to paying players.
* Never-ending microtransactions on addictive games that can add up to much more than a game is worth.
* Games that are made annoying unless you pay microtransactions.
* Games that get you to invest time in them until you can even tell how much you're going to need to pay to enjoy keeping playing them at all.
* Games that are barely games, where the design is mainly about getting people addicted and willing to pay money for imaginary things.
* Games designed to have players be attached to their character, virtual pet/farm/kingdom/etc, or their involvement with other players (q.v. so-called "social" games or games with clans) and that involve microtransactions to keep their pet alive, their country from being invaded, or their clan-mates from being "let down". (Thanks for the comment, @H.idden.)
* And other hate-worthy schemes.

It would be possible to make non-awful games that use microtransactions, which would hopefully not be hated by association. For example, some games are actually interesting games but happen to offer some microtransaction sales of things that don't materially mess up the game, and aren't excessively priced.

# Answer
> 9 votes
**Microtransactions are not universally hated**

Having a game or aspects of an otherwise fun game altered invasively simply to sell more microtransactions is what is universally hated.

I think a list of games and give a short evaluation of each on how I personally feel about microtransactions in each would help show which games to them well and which do not and why.

**TL;DR** If the microtransactions don't affect game balance, add fun cosmetic content to the game, and are non-intrusive, I don't think anybody hates their inclusion in any game.

* EA Battlefront 2 - Hated. This is a competitive premium shooter where additional gameplay advantages can be bought, thus creating a conflict of interest for the developers, and dividing the community into haves/have-nots after an already $60 or more purchase.
* Overwatch - Great! The microtransactions add fun skins and are non-intrusive. Loot are frequently given out for free, and there are NO mechanical microtransactions, ensuring competitive balance. All new gameplay-related content distributed for free, thus ensuring community unity in matchmaking.
* Rocket League - See Overwatch
* CS:GO - See Overwatch, 3rd party gambling sites non-withstanding.
* Leage of Legends - They're ethical because LoL is free, but affect gameplay balance to a non-negligible degree... and additional cosmetics are sold anyway. The community does not seem to mind, but it is why I stopped playing and never bought anything.
* TF2 - See League of Legends.
* Warframe - Ethical, but for me, too expensive for what the core game provides; a simple grindy corridor shooter (plains of the Eidolons non-withstanding)
* Tribes Ascend - Ethical, but had a very negative affect on the games balance. Gun and side grades were very pollutive on what otherwise was a fun core experience.
* DotA - See Overwatch.
* Shadow of War - The developers purposefully introduced grind to their game to incentivise additional purchases. This is a slimy tactic, especially given the game is single player (no continued server maintenance) and already has a high price point.
* Dungeon Keeper - Microtransactions are ethical here (as the game is free), but is the game worth it? No. Not by a long shot.

# Answer
> 9 votes
I think fundimentally it is because it is a business model which no longer emphasises making the best possible game (or even the best game with the limited available budget). Look at these businesses models:

Paid up front: Further revenue is driven by reviews and positive recommendations, providing a very good game drives this

Paid by advertising: The longer a player plays the more revenue is generated, providing a very good game drives this

Paid by microtransactions: The game as delivered must not be too fun, parts of the game must be intentionally disabled in order to rent them back. As much of the revenue is generated by the small percentage of players who pay vast amounts, and they need something to buy, the game must be compromised even for players paying moderate amounts (to incentivise the players who pay vast amounts).

Ref: http://www.escapistmagazine.com/forums/read/7.843665-Most-Freemium-Revenue-Comes-From-Less-Than-1-of-Gamers

All in all its a great business model but doesn't lead to very good games

# Answer
> 4 votes
The biggest problem with micro-transactions is that they are, in general but also in some very prominent examples (which people remember well), deceptive, fraudulent, abusive, and explicitly designed to take advantage of the weak. Insofar, they are also massively unethical. That, and they're not "micro" at all.

*How are they deceptive and fraudulent?* The game is usually advertized as "free" or "play free", but it is not free in any way, on the contrary. Usually, what you can do for free is so much limited (purposely, of course) that you cannot really claim it's useable if you are being honest.
In fact, if you look at the screenshot that you posted yourself, it is not only not-free, it is outrageous. The smallest thingie costs $5.49 and while I don't know that particular game, you can bet that the 500 stuffs you get for that are worth next to nothing game-wise. Prices go up to well beyond 100 dollars. That's *a lot* of money for something that's free.

Add to that the fact that usually you have to pay very real amounts of real money and have no way of getting refunded, but whether or not (and for how long) you actually get back some "value" is uncertain. In-game items may be taken away, the entire game may be discontinued on short notice, and the price tags on in-game items may change every day. Things you bought for real money may suddenly become free for all as an advertising campaign, too (all that has happened with some real games).

*How are they abusive and designed to take advantage of the weak?* Microtransactions make it easy to spend money, or money-equivalent (which you will promptly refill using money) when you would normally not do so. They are designed to make it exceptionally hard to tell exactly how much money you have spent.
They make it **especially** easy for kids to spend greater amounts of money, and deliberately so. They take advantage of lacking impulse control of mostly (but not necessarily) young humans, and their inability to realize what amount of money they're spending in a very short time.

# Answer
> 4 votes
We have to differentiate between micro-transactions which buy content, from those which buy consumables.

In the beginning, micro-transactions were not only cheap (around $1 or not much more), but they bought **content**. New levels, new characters, new missions, new hats. Even if it was just decorative, if you bought it, you kept it. It was yours.

Now, most micro-transactions are buying you **consumables**. In-game currency you spend, and it's gone. Time-skips, extra lives, you spend them, they are gone.

If you want to understand how players feel about it, imagine the following: take a very famous, well-beloved old game. Like DOOM. I assume you know it, if not, then you can get it almost for nothing, or you can try out the shareware version or a number of its free ports.

Now imagine that the developers added in the possibility to buy ammunition for real world money. Yeah, right, who needs that? But as you play, ammo crates in the game start becoming more and more rare, up to a point when they are almost completely gone, and the only way to proceed is to buy ammunition for real money. And as you fire that ammunition, it's gone. You have to buy more, for even more money. And then monsters suddenly start getting ten times as strong, and the only way to survive them is to buy that exclusive armor only available for real money. And then, if you want to save or load the game, you are greeted by a screen which says you have to either wait two hours, or pay real money. Ok, you go do some household chores instead of paying, but on the next occasion, the waiting time is for hours. And after that, eight hours. And once you got used to paying just another dollar instead of waiting for days, one day you open the game, and see a message saying that monsters are about to steal your backpack, and if you don't buy a protective charm for real money, they take away all your equipment (equipment you spent so much time gathering, and some of it you bought for real money).

Would you think all this improved the game, or would you hate it instead?

# Answer
> 2 votes
I can offer two reasons. One is that old style gamers such as myself just prefer to play the game without having to pay extra to get the content. I would prefer to unlock content by player.

The second is worse, its the game companies that appeal to children and constantly try to sell items to them that have zero value , sometimes for reletively large amounts each time (even 50p per time is a lot if they are going to buy 4-5 things per day at age 10).

Your question of course requires an opinion as an answer. And this is just my opinion. Many people love to buy skins and other useless in-game items and dont care about the odd £1-£10 they spend on them.

Dont even get me started on the full grown men I know who work all week and will spend minimum of £30 per week on FUT and other things lol

# Answer
> 1 votes
### There is one point for hating micro transactions that I didn't see made here.

tl;dr players feel like people who pay get an unfair advantage.

Players in games often feel like people who pay have an unfair advantage. In clash of clans and clash Royale there exists the slang term "gemmer" which has a negative connotation, referring to people who pay the micro transactions for the in game premium currency, gems.

The (majority of) game developers do their best to make winning based on skill (hard), but the company does need money to improve their game.

I personally like that others are paying for the game for me, but it seems most others don't look at micro transactions that way. I wouldn't call it an unfair advantage, I'd call it a fair advantage.

# Answer
> 0 votes
They can be used benignly, but when that happens, they don't make the news. And even when they are used just on cosmetic aspects, they still threaten to partition your users into "haves" & "have nots", which creates its own complications.

As the question observed, sometimes they represent the only way to finance development. But end users rarely see that side of development & even when they do, most consumers don't care.

They do have the capacity to present designers & developers with choices that ultimately amount to the promise near term financial rewards at the expense of user experience. As such, they can incentivise poor design & development choices.

So from the user perspective, the negatives are more visible than positives, thus making them unpopular.

# Answer
> 0 votes
In my not-so-humble-opinion, micro-transactions are a manifestation brought to life by gamers themselves.

For the sake of a simplistic and well known example; how popular did it used to be or still is to buy currency in World of Warcraft using real money?

Blizzard uses everything in their power to stop such activity but people keep on doing it. However they too eventually figured out that if you can't beat 'em, exploit 'em.

As for why micro-transactions are so hated, I think the answer boils down to the conditioned expectations of gamers based on past experiences and the harsh truth of the current reality.

Additionally, the continued deterioration of people's patience is nothing more that a self-sustaining business plan for those who can afford to cash in on that impatience.

# Answer
> 0 votes
Microtransactions themselves are not a bad concept, in my opinion. The problem is what they encourage. Instead of the game developer creating a reasonable timeline to get some cool unlock, it encourages for them to make the timeline... less reasonable, so that it encourages people to use the microtransaction path to unlock it. This is put to the extreme in the latest EA scandal where a very desired unlock takes ~40 hours to unlock, but can be unlocked very easily by simply giving EA some money.

It was not always like this too. When microtransactions were first introduced, they were actually praised by quite a few people. For instance, I paid $5 in either Battlefield 3 or 4 (can't recall) to unlock some weapons. I could've unlocked them by putting 5 hours into a game mode I couldn't care less about, but $5 is cheap enough to justify saving 5 hours of uninteresting grind time. However, the equivalent design today would be more like put 30 hours into a game mode OR the "get lucky" approach. In the get lucky approach, there is no outright guaranteed timeline. This has become increasingly popular with the advent of lootboxes. This is used in recent Call of Duty's. Now, you have the choice of buying an unlock, or you can wait... for some unknown amount of time until you happen to get some amount of lootboxes and unlock 8 different items (usually 2 very rare, with the others more common).

This kind of gambling aspect that was introduced is what makes it all seem very unfair. Microtransactions are no longer a short-cut. They've become a way to unlock something that most people will never put in enough time to unlock.

# Answer
> -2 votes
Imagine if, in real life, you went to a shoe store in order to buy new shoes, but then you discovered you don't have enough money to buy them. What do you do?

You use a Microtransaction to buy the shoes anyway.

Wait. What? How did you do that? Where did you get the money to buy the shoes from?

**Microtransactions break the story,** in the exact same way cheat codes do. And while cheat codes can simply not be used, mechanics accompanied by microtransactions are there by default and can rarely be disabled.

---
Tags: monetization, in-app-purchase, microtransactions
---


title: Network jitter, client input to server

text:
# Question
Title: Network jitter, client input to server
I am working on a authoritative client/server game, looking to both Valve and Gaffer to understand the concept.

Currently, the server simulates at 20 ticks a second. The inputs received from the client is buffered and only processed during one of these ticks. However, if a client sends input at a faster rate, say 60 times a second, that client will move about 3x faster than regular clients.

A solution to this would be to have the server combine/unify the inputs in the buffer and process this input once, instead of processing the buffered inputs individually.

Now, given the latter solution, a client with a send rate of 20 could be subject to network jitter, which could cause the server to receive 2 or more inputs at the same time. This would cause the server to combine/unify the inputs, when they should actually be processed individually.

So my question is, how should the server handle inputs to prevent more inputs from being processed than necessary, while not skipping inputs that arrive at the same time?

I hope I make sense, if not just tell me to elaborate :)

# Answer
> 2 votes
A simple solution i found, is to keep track of how many server ticks have gone without processing input from the client. This amount is then decremented for each subsequently processed input.

This allows for multiple inputs to be processed at each server-tick, but no more than the tick-rate.

Im still open for other ideas, but for now, this is what i'll stick with.

# Answer
> 0 votes
I'm not sure why so many people seem to have so much trouble with this. The server simulates 20 ticks per second. End of story.

Clients are expected to roughly send inputs at about that rate, probably slower (since you do not normally generate 20 events every second). But, whatever... the server *still* simulates 20 ticks.

That means none more and none less than if your client sends 60 inputs per second (or 240 inputs?), they will queue up and when the server processes its next tick, it will ignore all but the last commands received (you can as well only process the first few received, but it usually is more desirable to ignore old commands rather than new ones).

The server will process exactly the number of commands per tick per client that you allow. Not one more.

If a client continuously sends high volumes of updates, not just as a matter of a short burst (this may actually happen sporadically), the server may simply disconnect the client and flag the user as possible cheater...

---
Tags: networking, online, latency
---


# Question
Title: How can I blend grass decals in a transparent alpha channel in 3D? LibGDX
I'm new to 3D and trying to create grass simulation using decals in libGDX.

I'm following the logic outlined here.

Atm my grass decal is a billboard of grass stems with a transparent background. I've placed 3 decals together in the form of a triangle.

When I pan the camera around at times the decals blend together but most of the time you can see the outline of the decal and you can distinguish between the pngs.

Can someone please help me understand a way to blend my decals better?

The decal: http://www.reinerstilesets.de/3dtextures/billboardgrass0002.png

The code:

```
public class Grass implements Screen {
    private FirstPersonCameraController camera_control;
    private PerspectiveCamera camera;

    private Mesh floor_mesh;
    private Vector<Texture> grass;

    private Vector<Decal> decals;
    private DecalBatch decalBatch;
    private Vector<TextureRegion> grass_regions;

    private ShaderProgram shaderProgram;
    private Stage stage;

    @Override
    public void show() {
        stage = new Stage();
        decals = new Vector<Decal>();
        grass = new Vector<Texture>();
        grass_regions = new Vector<TextureRegion>();

        //camera
        camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.near = 0.01f;
        camera.far = 10f;
        camera.position.set(1, 2, 5);
        camera.update();
        camera_control = new FirstPersonCameraController(camera);
        camera_control.setVelocity(3);
        camera_control.setDegreesPerPixel(.25f);
        Gdx.input.setInputProcessor(camera_control);

        //grass
        grass.add(new Texture("billboardgrass0002.png"));

        for(Texture t : grass){
            grass_regions.add(new TextureRegion(t));
        }

        decalBatch = new DecalBatch(new CameraGroupStrategy(camera));
        for(int i = 0; i < 3; i++){
            decals.add(Decal.newDecal(0.75f, 1.25f, grass_regions.get(0), true));
        }

        //set grass
        decals.get(0).setPosition(1f, 0, 1f);
        decals.get(1).setPosition(1.1f, 0, 1.1f);
        decals.get(1).setRotationY(45);
        decals.get(2).setPosition(.8f, 0, 1.1f);
        decals.get(2).setRotationY(-45);
    }

    @Override
    public void render(float delta) {
        //gl
        Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        //Gdx.gl20.glClearColor(1, 1, 1, 1);
        Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
        Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);
        Gdx.gl20.glEnable(GL20.GL_TEXTURE_2D);
        Gdx.gl20.glEnable(GL20.GL_BLEND);
        Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl20.glCullFace(GL20.GL_NONE);

        //camera
        camera_control.update();

        //disable depth writing
        Gdx.gl20.glDepthMask(false);

        //draw grass decals
        for(Decal d : decals){
            decalBatch.add(d);
        }
        decalBatch.flush();

        //stage
        stage.getViewport().update(1280, 720, true);
        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {}

    @Override
    public void hide() {}

    @Override
    public void pause() {}

    @Override
    public void resume() {}

    @Override
    public void dispose() {
        shaderProgram.dispose();
        decalBatch.dispose();
        decals.clear();

        for(Texture t : grass){
            t.dispose();
        }

        grass.clear();
        floor_mesh.dispose();
    }
}

```

**Edit:** disabled depth buffer writing before drawing decals, now looks better:

# Answer
> 3 votes
The transparent pixels can still hide objects behind them. You need to disable depth write when rendering anything transparent:

```
Gdx.gl20.glDepthMask(false);

```

---
Tags: opengl, libgdx, 3d
---


title: Smooth Rotate Object While Orbiting

text:
# Question
Title: Smooth Rotate Object While Orbiting
I am working on a 3D game where you can control an object that orbits a sphere with an on-screen virtual joystick. So far I have that part working, but the object follows the joystick angle perfectly and "snaps" into the angle, rather than smoothly interpolating to the new angle of the joystick.

I would like to redo this and have it interpolate the values. I have it very close using the following code:

```
angle = Mathf.Atan2(joystickY, joystickX) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, currentAngle);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, TURNING_SPEED * Time.deltaTime);

```

This works great on one side of the sphere, but as soon as I move the object halfway around the sphere, the rotation is now mirrored and the object rotates 180 degrees until it reaches the other side again. What am I missing here?

I am basically trying to calculate the joystick angle, then apply that to the object as it orbits, but do this smoothly using slerp.

Let me know if you need any further information. Thanks!

# Answer
> 1 votes
For anyone running into a similar issue, the solution (for me at least) was to just change it to rotating around the local z-axis rather than the world z-axis:

```
joystickAngle = (Mathf.Atan2(-joystickY, -joystickX) * Mathf.Rad2Deg) + 90;
Quaternion targetRotation = Quaternion.Euler(0f, 0f, joystickAngle);
var blend = 1f - Mathf.Pow(1f - 0.1f, Time.deltaTime * 60f);
thisTransform.localRotation = Quaternion.Lerp(thisTransform.localRotation, targetRotation, blend);

```

---
Tags: unity, rotation, quaternion, interpolation, joystick
---


# Question
Title: How can I process extra mouse buttons using Monogame?
I use Monogame for game development. For processing mouse input, I can use the `Mouse` class to query basic information like left click state, right click state, and screen position. That works fine for a generic three-button mouse (left, right, and scroll wheel), but falls short for more complex gaming mice with side buttons. My question is, **how can I query those extra side buttons?**

Since `Mouse` doesn't include that functionality, are there additional C# libraries I can use? How do I account for the fact that mice can have any number of extra buttons and wheels? Is there some standard for representing those additional buttons programatically?

**Edit:** This question originally also asked about complex keyboards with extra buttons or wheels. Now, I'm asking only about processing extra mouse buttons (ideally any number of extra buttons).

# Answer
> 1 votes
The 4-th and 5th buttons are known as XButton1 and XButton2 in Monogame and are available as properties on `MouseState`, either through `Mouse.GetState` or `Window.MouseState`

Old XNA documentation links and since I can't find any Monogame docs, a link to the source:

https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.mousestate.xbutton1.aspx

https://github.com/MonoGame/MonoGame/blob/47a47c9f0157d24cc9a581454cca1f11aa0adf51/MonoGame.Framework/Input/MouseState.cs#L30

---
Tags: monogame, input, mouse, keyboard, control
---


title: SDL Mixer Strange Error Message

text:
# Question
Title: SDL Mixer Strange Error Message
I have a Visual Studio C++ project. I've just started out with SDL, and I've already rendered images, text, and now I'm trying to play audio. This will be done with the SDL\_Mixer extension library.

However, I'm having the following issue. When I run my code with the SDL\_Mixer library included, I get the following popup error message:

```
The procedure entry point SDL_AudioStreamFlush could not be located in the dynamic link library...

```

What the heck does this mean? Did I do something wrong with the installation? I got SDL mixer from here: https://www.libsdl.org/projects/SDL\_mixer/

Any help would be greatly appreciated!

# Answer
> 2 votes
I solved the issue! Basically, I didn't have the latest form of SDL2. (I think I had 2.0.5 or something)

By going to the SDL2 download page, I was able to get and install SDL-2.0.7, replacing the old version. Once I completed the update, I was relieved to hear my music playing!

---
Tags: c++, sdl, audio
---


# Question
Title: How to achieve this sprite/mesh tile splitting like in Peggle?
Everyone knows `Peggle`. Here's a simple screenshot from one of their 'shapes':

On the first look, it looks so simple. It's a circle made of identical tiles:

It's easy to make a circle like this, even programatically.

But then I realised that I can't make bigger/smaller circles with this single tile. For instance, the shape above has 17 tiles. If I want to make a circle with 9 tiles, I need to make a tile more curved, so it can close the entire shape with 9 elements.

Here's a sample of a shape which cannot be constructed using the above tile:

As you can see, it's probably made dynamically. Each tile has different size and it's warped differently and I don't think so that they've used 30000 types of tiles with multiple angles. They did actually, in the first version of the game coded in Lua, but there were 3-5 types of tiles. In their latest game, they've created more exotic shapes, and that would be so inefficient, especially for mobiles.

Are there any algorithms for filling an oval or circle with irregular tiles like this?

I assume I'd need to split some meshes dynamically for that, or at least sprites.

I'll be thankful for pointing me a right direction!

# Answer
> 3 votes
This can be done in general using a shape where you can get the normals at any point. It's particularly easy if the shape is a circle or an ellipse, because we can just use the parametric equation for the ellipse to give the position and normal.

One of the problems now is that to cut up the curve into segments, you should know the arc-length of each segment. This can be a bit tricky when you are dividing the curve up in "parameter space" instead of "real space" you can see it in the picture in the question, where they are squished around where the curvature is higher. This will happen when you divide up into equal angle segments and you might need to adjust for that.

So let's say we have divided our curve into segments, equal or otherwise, then we can create custom geometry from the position and normal. Choose point **a** to be one point and **b** is the next point.

We build a custom geometry as a quad using the four points

`a + a_normal`

`a - a_normal`

`b - b_normal`

`b + b_normal`

This image is showing two adjacent points on the curve and their normals. Four more points are generated from them.

Interactive example. This was made in javascript but should translate into Unity.

---
Tags: unity, procedural-generation, geometry, mesh
---


# Question
Title: "error CS0246: The type or namespace "NAMESPACE" could not be found" while declaring that namespace usage
I have two scripts, one is located at:

> Assets / Scriptable Objects / ...

while the other one is located at:

> Assets / Scripts / ...

I have the first script encapsulated on a namespace.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using VoidlessNodes.LevelFlowNodes;

namespace VoidlessUtilities
{
[CreateAssetMenu]
public class LevelFlowData : BaseNodeEditorData<BaseLevelNode, LevelFlowEditorAttributes>
{
    private const string MENU_ITEM_PATH = "Create / ScriptableObjects / LevelFlowData";
    private const string NEW_ASSET_PATH = "ScriptableObjects / Level Flow Data";

    [SerializeField] private string _name;
    private RootLevelNode _root;

    /// <summary>Gets and Sets name property.</summary>
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }

    /// <summary>Gets and Sets root property.</summary>
    public RootLevelNode root
    {
        get { return _root; }
        set { _root = value; }
    }

    [MenuItem(MENU_ITEM_PATH)]
    public static void CreateAsset()
    {
        LevelFlowData scriptableObject = ScriptableObject.CreateInstance<LevelFlowData>() as LevelFlowData;
        AssetDatabase.CreateAsset(scriptableObject, AssetDatabase.GenerateUniqueAssetPath(NEW_ASSET_PATH));
    }

    public BaseLevelFlowNode GetLevelFlow()
    {
        BaseLevelFlowNode rootLevelFlow = null;

        if(root != null)
        {
            rootLevelFlow = root.GetNode();
        }
        else
        {
            Debug.LogError("[LevelFlowData] Data has no RootLevelFlowNode saved");
        }

        return rootLevelFlow as RootLevelFlowNode;
    }
}
}

```

And the other one is using the same namespace, which is a namespace I use for my custom scripts, but the only difference is that LevelFlowData's location is not under **Scripts**.

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VoidlessUtilities;

public class TestLevelController : Singleton<TestLevelController>
{
    [SerializeField] private LevelFlowData _levelFlowData;
    [SerializeField] private List<GameObject> _testViews;

    /// <summary>Gets and Sets levelFlowData property.</summary>
    public LevelFlowData levelFlowData
    {
        get { return _levelFlowData; }
        protected set { _levelFlowData = value; }
    }

    /// <summary>Gets and Sets testViews property.</summary>
    public List<GameObject> testViews
    {
        get { return _testViews; }
        set { _testViews = value; }
    }

#region UnityMethods:
    void OnEnable()
    {
        BaseInteractable.onTriggeredEvent += (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }

    void OnDisable()
    {
        BaseInteractable.onTriggeredEvent -= (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }

    /// <summary>TestLevelController's' instance initialization.</summary>
    void Awake()
    {

    }

    /// <summary>TestLevelController's starting actions before 1st Update frame.</summary>
    void Start ()
    {

    }

    /// <summary>TestLevelController's tick at each frame.</summary>
    void Update ()
    {

    }
#endregion

#region PublicMethods:
    public void EnableView(int _index)
    {
        testViews.SetAllActive(false);
        testViews[_index].SetActive(true);
    }
#endregion

#region PrivateMethods:

#endregion
}

```

Do I need to move LevelFlowData to Scripts, and make platform independet compilation (e.g., **#if UNITY\_EDITOR**) encapsulation for UnityEditor namespace usage? Or is there another point I am missing?

This is the specific error log:

> **Assets/Scripts/Scene Controllers/TestLevelController.cs(10,27): error CS0246: The type or namespace name \`LevelFlowData' could not be found. Are you missing an assembly reference?**

Thanks in advance.

# Answer
So, the reason why the namespaces are not detected is due to the order of compilation of scripts that makes non-Editor scripts have no reference of Editor scripts..

So, to solve it, I just had to modify the non-Editor script, to now receive a Scriptable object, instead of a LevelFlowData (since that ScriptableObject had dependencies on Editor scripts).

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VoidlessUtilities;
using VoidlessNodes.LevelFlowNodes;
//using VoidlessEditorWindow;
//using VoidlessUtilities.VoidlessNodeEditor;

public class TestLevelController : Singleton<TestLevelController>
{
    [SerializeField] private ScriptableObject _levelFlowData;
    [SerializeField] private List<GameObject> _testViews;
    [SerializeField] private BaseLevelFlowNode _levelFlowRoot;

    /// <summary>Gets and Sets levelFlowData property.</summary>
    public ScriptableObject levelFlowData
    {
        get { return _levelFlowData; }
        protected set { _levelFlowData = value; }
    }

    /// <summary>Gets and Sets testViews property.</summary>
    public List<GameObject> testViews
    {
        get { return _testViews; }
        set { _testViews = value; }
    }

    /// <summary>Gets and Sets levelFlowRoot property.</summary>
    public BaseLevelFlowNode levelFlowRoot
    {
        get { return _levelFlowRoot; }
        set { _levelFlowRoot = value; }
    }

#region UnityMethods:
    void OnEnable()
    {
        BaseInteractable.onTriggeredEvent += (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }

    void OnDisable()
    {
        BaseInteractable.onTriggeredEvent -= (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }
}

```

And then use the Inspector script I made for that class as a layer to deal with some Editor utilities, casting the ScriptableObject to LevelFlowData to still have the functionalities I expected.

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

[CustomEditor(typeof(TestLevelController))]
public class TestLevelControllerInspector : Editor
{
    private const string REPLACE_VIEW_TAG = "View_";
    private const string OPEN_LEVEL_EDITOR = "Open Level Flow Editor";
    private const string UPDATE_LEVELFLOW = "Update Level Flow Data";
    private TestLevelController testLevelController;

    /// <summary>Sets target property.</summary>
    void OnEnable()
    {
        testLevelController = target as TestLevelController;
    }

    /// <summary>OnInspectorGUI override.</summary>
    public override void OnInspectorGUI()
    {
        /// Do your stuff here:

        DrawDefaultInspector();

        if(testLevelController.testViews.Count > 0)
        {
            for(int i = 0; i < testLevelController.testViews.Count; i++)
            {
                if(testLevelController.testViews[i] != null)
                {
                    if(GUILayout.Button(testLevelController.testViews[i].name.Replace(REPLACE_VIEW_TAG, " ")))
                    {
                        testLevelController.EnableView(i);
                    }
                }
            }
        }

        if(testLevelController.levelFlowData != null)
        {
            if(GUILayout.Button(OPEN_LEVEL_EDITOR))
            {
                if((testLevelController.levelFlowData is LevelFlowData))
                {
                    LevelFlowEditor.OpenNodeEditorWindowWithData(testLevelController.levelFlowData as LevelFlowData);
                }
                else
                Debug.LogError("[TestLevelControllerInspector] ScriptableObject provided is not of type LevelFlowData");
            }
            if(GUILayout.Button(UPDATE_LEVELFLOW))
            {
                if((testLevelController.levelFlowData is LevelFlowData))
                {
                    LevelFlowData data = testLevelController.levelFlowData as LevelFlowData;
                    testLevelController.levelFlowRoot = data.GetLevelFlow();

                    testLevelController.levelFlowRoot.Tick();
                }
                else
                Debug.LogError("[TestLevelControllerInspector] ScriptableObject provided is not of type LevelFlowData");
            }
        }
    }
}

```

Hope it solves similar issues to other users.
> 1 votes

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


title: How To Scale Canvas In Android

text:
# Question
Title: How To Scale Canvas In Android
I am writing a android game using Canvas as the way to draw everything, the problem is that when i run it on different android phones the canvas dosn't change size i tried using canvas.scale() but that didn't make a i difference. The code i use for drawing is ...

```
public void draw( Canvas c, int score )
{
    Obstical2[] obstmp = Queue.toArray(this.o);
    Coin[] cointmp = QueueC.toArray(this.c);

    for( int i = 0; i < obstmp.length; i++ )
    {
        obstmp[i].draw(c);
    }

    for( int i = 0; i < cointmp.length; i++ )
    {
        cointmp[i].draw(c);
    }
    c.drawText(String.format("%d", score ), 20, 50, textPaint);

    if( isWon && isStarted ) c.drawText("YOU WON", 20, 400, resPaint);
    else if( isLost && isStarted ) c.drawText("YOU LOST", 20, 400, resPaint);
}

```

The function above calls the draw functions for the entity's on the screen, theses function are as follows

Draw Function For Obstical :

```
public void draw( Canvas c )
{
    Log.i("D", "COIN");
    coin.draw(c);
}

```

Draw Function For Coin :

```
public void draw( Canvas c )
{
     obstical.draw(c);
}

```

The on create function is :

```
protected void onCreate(Bundle savedInstanceState)
{
    player = new Player(this);
    //map = new Map(this, );
    WindowManager w = this.getWindowManager();
    Display d = w.getDefaultDisplay();

    float sy = d.getHeight()/800;
    float sx = d.getWidth()/480;

    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    String type = intent.getStringExtra(CUBEMenuActivity.EXTRA_MESSAGE);

    Log.i("MENU", type);

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    //mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

       // Remove the title bar from the window.
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Make the windows into full screen mode.
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    map = new Map( this, type, sy, sx );

    canvasView = new CanvasSurfaceView(this, map, player, sx, sy );
    setContentView(canvasView);

    Log.i("C", "Canvas View Set");

}

```

i am using a canvasSurfaceView instead of an XML layout, the canvasSurfaceView constructor method is

```
public CanvasSurfaceView(Context context, Map map, Player player, float sx, float sy)
{
    super(context);
    holder = getHolder();

    gestures = new GestureDetector(new GestureListener(this));

    this.map = map;
    this.player = player;
    this.background = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.background1), 480, 10000, false);
    this.sx = sx;
    this.sy = sy;
}

```

when the game is running the run() method is called repeatedly this is where the canvas class is initialized

```
public void run()
{
    while( run == true )
    {
        if( !holder.getSurface().isValid() )
        {
            continue;
        }

        Canvas c = holder.lockCanvas();

        if( ( map.isWon || map.isLost ) && map.isStarted ) setCompleated();
        //c.scale(sx, sy);

        if( notCompleated == false )
        {

            if( map.map.bottomOfLevel != 800 ) by += player.terminalVelosity / 2;
            update();
        }
        c.drawBitmap(background, 0, by, null);
        map.draw(c, player.score);
        player.draw(c);

        holder.unlockCanvasAndPost(c);
    }
}

```

How could i make the canvas re-size to it would look the same on any screen ?

Cheers Daniel

# Answer
> 1 votes
To do this, change the size of your paint object. Also, scale the bitmaps. Scaling the canvas doesn't do anything.

```
paint.setTextSize(textSize);

```

and for bitmaps

```
bitmap=Bitmap.createScaledBitmap(src, dstWidth, dstHeight, filter)

```

where `filter` is whether the bilinear filtering is enabled

# Answer
> 0 votes
in run method when you want draw canvas you can use :

```
//out of run method
Rect dstRect = new Rect();
//in run method
canvas.getClipBounds(dstRect);
canvas.drawBitmap(background, null, dstRect, null);

```

it force canvas to draw & scale your final bitmap(background) for any device resolation (may strech in som device).

---
Tags: java, android, html-canvas
---


title: Make timer for game to run for 2min

text:
# Question
Title: Make timer for game to run for 2min
I'm trying to make a game using C++ (in Visual Studio 2015). I want to make the game run for X minutes and then end. I have a function `play()` that calls all other functions required and I need to make `play()` run for 2min. I've tried putting `play()` in loops that run for some time, but none of them work. I am not able to find any other question that addresses the problem I'm facing and so any help would be appreciated.

# Answer
> 2 votes
If you record the time once at the start of your game:

```
time_t startTimeSeconds = time(NULL); // must include 'ctime'

```

Every update (game loop iteration) you can check to see if the elapsed time has exceeded two minutes:

```
if (time(NULL) - startTimeSeconds >= 120) // two minutes
    stopGame();

```

# Answer
> 0 votes
Your `play()` function not necessary should not be executed in the loop. Instead, you can use this function, to loop your game. Here is some minimal example, how you can use it:

```
#include <chrono>

void play()
{
    // record the time, as soon you entered the function
    auto startTime = std::chrono::system_clock::now();

    while(!isGameOver())
    {
        // here you can paste your time consuming game logic
        //  i.e. function calls

        auto endTime = std::chrono::system_clock::now();
        // check, if two minutes are over
        if (endTime - startTime > std::chrono::minutes(2))
            gameOver(); /* in this function paste your 'end of the game'-logic */
    }
}

```

The main advantage in using `std::chrono` instead of `ctime` is that your time-checking calls are less cryptic, therefore better understandable, especially in initialization part.

Compare `auto time = std::chrono::system_clock::now()` and `time_t startTimeSeconds = time(NULL);`

---
Tags: c++, timer
---


title: Get object position on texture

text:
# Question
Title: Get object position on texture
I'm rendering a 3D object to texture (2048x1600) and show this texture on a panel (1600x285) using a RawImage (2048x1600) component as child. This texture is rendered successfully on screen.

This 3d object contains several mountpoints as empty objects. Now I want to show several sprites to visualize those mountpoints on the texture (panel) at their corresponding screen position (must not pixel perfect).

I tried several camera transforms, but could not get the correct position values:

```
  var main = camera.WorldToScreenPoint(slot.mountpoint.position);
  Debug.Log("Maincam screenpos: " + main.ToString());

  RectTransform rect = this.GetComponentInParent<RectTransform>();
  Debug.Log("Rect size delta: " + rect.sizeDelta.ToString());

  Vector2 viewPos = camera.WorldToViewportPoint(slot.mountpoint.position);
  Debug.Log("Viewport pos : " + viewPos.ToString());

  Vector2 localPos = new Vector2(viewPos.x * rect.sizeDelta.x, viewPos.y * rect.sizeDelta.y);
  Debug.Log("Viewport pos local : " + localPos.ToString());

```

How I could realize this?

# Answer
> 1 votes
I could solve this problem by using a WorldSpace-Canvas for each mountpoint. Each mountpoint sprite is rendered as billboard facing towards the camera. To render any sprite on top I've overwritten the default UI shader as described by this link.

The only thing I dislike is that I've now mixed a 2D UI with some 3D UI elements placed somewhere in the hierarchy at the objects.

---
Tags: unity, gui, image
---


# Question
Title: How to force keep the aspect ratio and specific resolution without stretching the output screen view?
I'm using Screen.SetResolution()

But when I run in Android device, it shows the output image is stretched to fill up the full screen which I don't want. I want it to keep the aspect ratio properly.

***Example 01*** : This is coincidentally match and ok because my device screen aspect is 16:9.

**But here is the incorrect one (stretched)**

***Example 02***: This is 640 x 480 in resolution but it should remain in aspect ratio of 4:3.

How could I keep it's aspect ratio and **\[make it black at the extra space outside\] or \[customize it using my own image to cover the extra space\]**? in Android.

Note: I'm not talking about the canvas but entire output view.

# Answer
For desktop games you can control the supported aspect ratios directly in

`Edit -> Project Settings -> Player -> Resolution and Presentation`

But for mobile, or situations where your aspect ratio might change during play (eg. resizing a window dynamically), or you want to use letterboxing for artistic effect, we'll need an in-game solution.

You can attach the following script to your Camera to resize its viewport to fill the biggest, centered rectangle of your target aspect ratio that will fit in your current screen/window.

Note that this won't on its own set the resolution of the frame buffer you're rendering to. If you want to render only eg. 640x480, I'd recommend setting up your camera to render to a `RenderTexture` with that resolution. Then you can present the resulting texture to the screen using a screenspace overlay canvas with a `RawImage`, or a second camera.

```
using UnityEngine;

[RequireComponent(typeof(Camera))]
public class CameraCrop : MonoBehaviour {

    // Set this to your target aspect ratio, eg. (16, 9) or (4, 3).
    public Vector2 targetAspect = new Vector2(16, 9);
    Camera _camera;

    void Start () {
        _camera = GetComponent<Camera>();
        UpdateCrop();
    }

    // Call this method if your window size or target aspect change.
    public void UpdateCrop() {
        // Determine ratios of screen/window & target, respectively.
        float screenRatio = Screen.width / (float)Screen.height;
        float targetRatio = targetAspect.x / targetAspect.y;

        if(Mathf.Approximately(screenRatio, targetRatio)) {
            // Screen or window is the target aspect ratio: use the whole area.
            _camera.rect = new Rect(0, 0, 1, 1);
        }
        else if(screenRatio > targetRatio) {
            // Screen or window is wider than the target: pillarbox.
            float normalizedWidth = targetRatio / screenRatio;
            float barThickness = (1f - normalizedWidth)/2f;
            _camera.rect = new Rect(barThickness, 0, normalizedWidth, 1);
        }
        else {
            // Screen or window is narrower than the target: letterbox.
            float normalizedHeight = screenRatio / targetRatio;
            float barThickness = (1f - normalizedHeight) / 2f;
            _camera.rect = new Rect(0, barThickness, 1, normalizedHeight);
        }
    }
}

```

Because this doesn't change your camera's FoV or Height settings, the composition of game content displayed inside the camera view will stay the same - it will just grow or shrink the whole view to fit in the new crop.

Out of the box, the letterbox / pillarbox bars will just be the default colour of the framebuffer (generally cleared to black). You can fill these areas with graphics using a screenspace overlay canvas or additional cameras.
> 11 votes

# Answer
according to **docs** you can use **Projection** and **camera view**

you apply projection and camera view by first adding a matrix member to the vertex shaders of your graphics objects. With this matrix member added, you can then generate and apply projection and camera viewing matrices to your objects.
> -1 votes

---
Tags: unity, android, resolution, screen, aspect-ratio
---


# Question
Title: How can I generate infinite boundary walls in PICO-8?
I have drawn one tile and I would like to use it in a very small shoot'em'up I am writing for fun and learning. My aim would be to build something like Xenon 2 (vertical scrolling, a spaceship proceeding for a bit, at right and left walls that are programmatically generated so the ship can "travel" for a bit and then, in the end, meets final monster and end of the level) but I cannot think of how I can obtain this result without drawing everything manually in the map.

Not only code but also a good suggestion in topics / functions to study (all PICO-8 related, if possible) will be considered as a valid answer.

Here's a small manually generated example (walls are the grey blocks)

# Answer
> 6 votes
Sounds like you want to animate the walls down the screen so that it appears as though the player's ship is moving forward.

Know that the PICO-8 Map is mainly for static backgrounds, so if you want a sprite that will be animated on the screen, it is better to draw it with code using `SPR()`.

## Walk Through:

First, you will need many wall tiles drawn on the screen, so prepare an empty table to hold the X and Y coordinates for each tile. Put this above all other code: `WALLS={}`

Second, you will want to add all of the tiles' (X,Y) coordinates to that table. Do this when the game initiates so in the `_INIT()` function.

You can use a `FOR` loop that iterates 17 times because 16 tiles will fit from top to bottom, and 1extra tile will start above the screen to fill in the gap when the walls move down.

```
FOR I=0, 16 DO

END

```

Inside that, you create a small table for each tile. For the left wall the X will be 0, and the Y will calculate 8 pixels lower, each time the `FOR` loop iterates. `TILE={ X=0 , Y=8*I-8 }`

Then add that to your `WALLS` table: `ADD(WALLS, TILE)`. Create another tile table but this time the X will be 120 for the right wall, and add that as well.

Third, you can draw, using `SPR( sprite#, x, y )`, each tile onto the game screen, using a `FOR key IN ALL(table)` loop. Do this in the `_DRAW()` function.

Fourth, you can animate the walls by changing the Y coordinate of each tile at every game update so do this in `_UPDATE` function. Use another `FOR key IN ALL(table)` loop, and inside that, simply increase Y by 1: `key.Y += 1`

Then catch any tiles that fall off the bottom of the screen and move them above the screen, making the wall appear infinite:

```
FOR TILE IN ALL(WALLS) DO
    TILE.Y += 1
    IF TILE.Y >= 128 THEN
        TILE.Y = -8
    END
END

```

Done!

## Code

```
walls={}

function _init()
 for i=0, 16 do --build walls
  tile={        --left tiles
   x=0,
   y=8*i-8
  }
  add(walls, tile)

  tile={        --right tiles
   x=120,
   y=8*i-8
  }
  add(walls, tile)
 end
end

function _draw()
 cls()
 for tile in all(walls) do --draw walls
  spr(1,tile.x,tile.y)
 end
end

function _update()
 for tile in all(walls) do --animate wall
  tile.y+=1
  if tile.y>=128 then
   tile.y=-8
  end
 end
end

```

## Run

---
Tags: tilemap, shoot-em-up, pico-8
---


title: When to scale bitmaps in android game

text:
# Question
Title: When to scale bitmaps in android game
I've just started developing my first game with android using SurfaceView. I scale my bitmaps to support different screen sizes. But I don't know it's better to do the scaling when loading the bitmaps or when drawing them to canvas using Matrix. I guess the first one would occupy more memory but it's better in performance. But I don't know how really things work here so any suggestion from experts would be appreciated.

# Answer
Scaling of textures when rendering is generally not very performance intensive - it can sometimes even be faster to render small textures that are scaled up (usually when there are lots of textures and they need to be swapped from ram to vram). Of course, using small textures comes at the cost of quality.

It is generally best to avoid doing scaling yourself during runtime. If you want better quality for the textures then create multiple sets of textures (at varying resolutions) and determine the appropriate textures to load based on device resolution.
> 1 votes

# Answer
Android has special folders for this occasion, folders like `drawable-ldpi` and `drawable-mdpi` are for screens with different densities (ldpi = low density, mdpi = medium density).

You can do the same with screen sizes: `drawable-normal` or `drawable-normal-ldpi`

The plus side using this method is that when a user installs your app, only the images that are going to be used will be installed (since screen size or density can't physically change). This saves both memory and cpu.

For more info about folder names and qualifiers: Android - Supporting Multiple Screens
> 1 votes

# Answer
be carefull:

**1.** if you scale all image according to screen size first and then draw on canvas

---\> loading these bitmaps allocate memory and cause **Grow Heap** (bigger screen size = more memory allocation)

**2.** if you load all image without scale and scale framebuffer on draw

---\> it make your **FPS** (frame per second) reduce and your game flickering (bigger screen size = more flicker)
> 0 votes

---
Tags: android
---


title: see inside but not light from outside

text:
# Question
Title: see inside but not light from outside
I have a top down view of the interior of a house. I want to put a cover on the top so light from outside can't come in and I get more realistic lighting inside but transparent so I can still see inside. No clue how to achieve this in Unity. Any help would be appreciated. Ideally I'd just be able to use Unity's built in cube to make this.

# Answer
Two methods exist for this. The easier one is to just set the object's shadow casting mode to Shadows Only. I didn't know there was a Shadows Only mode and only learned of this today too, thanks to DMGregory.

The other method is more convoluted, but it can be used for other things as well. Here's the rest of my answer:

Create a custom render layer. Quote from the Layers Manual page of Unity.

> The first step is to create a new layer, which we can then assign to a **GameObject**. To create a new layer, open the Edit menu and select **Project Settings-\>Tags and Layers**.

Put the object on top of the house, then change its render layer to the custom one.

Now, select your camera and change its rendered layers so that it doesn't render that object.

Images taken from the Layers manual page of Unity.
> 3 votes

---
Tags: unity
---


# Question
Title: An object reference is required to access non-static member
I have a code that I want to use to change levels everytime the player kills a certain amount of enemies, but it gives me this error:

> An object reference is required to access non-static member \`enemyCount.nextLevelName'

Here's my script (this is attached to an empty game object)

```
public class enemyCount : MonoBehaviour {

public static int enemiesCount;
public int targetCount;
public string nextLevelName;
void Start()
{
    enemiesCount = targetCount;
}
public static void DecreaseCount()
{
    enemiesCount--;
    print("Enemy Count is " + enemiesCount);
    if(enemiesCount <= 0)
    {
        Debug.Log("Load level: " + nextLevelName);
        Application.LoadLevel (nextLevelName);
    }
}

```

}

and this is inside the bullet script

```
if (collision.gameObject.tag == "Enemy") {
        enemyCount.DecreaseCount();
    }

```

# Answer
> 4 votes
Your `nextLevelName` member variable is not static, meaning there could be a different name set on each instance of the `enemiesCount` class, of which you could have dozens or thousands if you wanted.

The `DecreaseCount` method, on the other hand, *is* static, meaning it's shared across the whole `enemiesCount` type and not attached to any one instance.

That means when you tell it to use a non-static member variable, it doesn't know which instance it should read it from. You need to give it an instance to work from. Even if you only have one instance in your scene, this method doesn't know that unless you store that instance somewhere it can find it (for example using a Singleton pattern). Some additional patterns for referencing one object from another are described in this answer.

Another way to approach this "trigger something when all entities of this type are gone" (be they coins or enemies or something else) is described in this answer.

---
Tags: unity, scripting
---


# Question
Title: Determine facing direction mecanim 2d movement
I'm using this script to move my character in my 2d world:

```
    public float speed;   //Movementspeed

public Rigidbody2D rbody;
Animator anim;

void Start () {

    rbody = GetComponentInChildren<Rigidbody2D> ();
    anim = GetComponent<Animator> ();
}

void FixedUpdate () {

    Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (movement_vector != Vector2.zero) {
        anim.SetBool("iswalking", true);
        anim.SetFloat("input_x", movement_vector.x);
        anim.SetFloat("input_y", movement_vector.y);
    } else {
        anim.SetBool("iswalking", false);
    }

    rbody.MovePosition (rbody.position + movement_vector * speed * Time.deltaTime);

}

```

}

What I want is to somehow register where my character is facing/walking towards to be able to Instansiate a gameobject infront of it.

How do I do that?

# Answer
> 1 votes
Add a Vector2 private variable to your class. This variable will tells you at any time where your character is facing:

```
private Vector2 facingDirection = Vector2.zero;
...
void FixedUpdate () {

    Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (movement_vector != Vector2.zero) {
        anim.SetBool("iswalking", true);
        anim.SetFloat("input_x", movement_vector.x);
        anim.SetFloat("input_y", movement_vector.y);
        facingDirection= movement_vector;  // You save the direction only when the object is moving
        direction.Normalize() // Normalize it as the magnitude does not give any valuable information
    } else {
        anim.SetBool("iswalking", false);
    }

    rbody.MovePosition (rbody.position + movement_vector * speed * Time.deltaTime);

}

// Example of usage
private void createObject()
{
    GameObject newObject;
    float distance = 3; // instantiate an object 3 units in front of the character

    // Now you can access the current direction of the character anywhere in the class
    Instantiate(newObject, transform.position + facingDirection*distance, Quaternion.identity);
}

```

# Answer
> 0 votes
You could try and check if the distance between two objects is increasing or decreasing or you can use an infinite raycast and check the object it hits.

# Answer
> 0 votes
Are you just looking for Transform.forward?

---
Tags: unity, c#, 2d, movement, gameobject
---


# Question
Title: LibGDX - GameWorld Dimensions vs ViewPort Dimensions vs Camera Dimensions
Before someone mark it duplicate - I am aware that there are few questions already on this topic but the explanations are all theoretical and no graphical elaboration was provided which I think will help in understanding these concepts better.

Coming to the query in hand, I assume `LibGDX` follows `OpenGl` definitions of `GameWorld`, `Camera` and `ViewPorts` \- **please correct me if** I am wrong. Now when I am trying to understand these basic concepts of `LibGDX`, confusions are arising all around me. I am sure these concepts are not that hard to understand and I must be looking at the things in a wrong way. As per my understanding:

**GameWorld Dimensions:** This is the dimension of the `GameWorld` that I have created, perhaps a Tiled map or some background which will be showing to the player. Lets assume the `GameWorld` dimension is 4096 x 4096 px.

**Camera Dimensions:** This is the dimension of the `Camera` that I would like to show to the user at a time. It could be 800x480 px or 320x240 px or whatever I want. When set, user will only be able to see that part of the `GameWorld` at a time.

**ViewPort Dimensions:** I have absolutely no clue how this works!

**And my queries are: (Please explain with image/graphics for better clarity)**

a. How is `ViewPort` related to `Camera`?

b. Is `Camera` a part of `ViewPort` or is it vice-versa?

c. Can `Camera` dimensions be different than that of `ViewPort`? eg: Can camera be 800x480 px whereas Viewport 320x240 px or vice-versa?

d. When designing games for multiple screen densities/sizes, which is a better approach - `Camera` with standard dimensions (16/9 - 4/3 - 800x480) or `ViewPort`? If `ViewPort` then which is the best in such cases - `Stretch`/`Fill`/`Fit`/`Expanded` ?

# Answer
> 0 votes
I'm not very good at drawing but I will give you my best shot at describing the relationships using analogies. This will not include technical descriptions since that has already been described elsewhere.

## Game World

The game world is, well, the *world*. It's everything your game contains. The game world has no actual size, it is an infinite space containing whatever you put there.

Your idea of the game world is that it is like the Earth (limited size), while it is more like Space (infinite size). It just feels finite because you just use and see a small bit of it at a time.

## Camera

The camera is your looking glass into the game world from outside. You can think of the camera as your eyes if you will. The "size" of the camera comes from how far to the sides we can see (**aspect ratio**) and how far we can see (**view distance / clipping plane**). It can also move around in the world.

## Viewport

While the camera controls how much we see and what we are currently looking at the viewport is what we're looking *through*. The viewport is the only one that has an actual size. Think of the viewport as your TV-screen or computer monitor.

## Conclusion

Final shot at an analogy:

* The Game World is the real world. The part of the Game World that you see is the set of a movie with actors jumping around doing their things and interacting with objects.
* The Camera is a camera filming the real world and the actors and objects in it, moving around to film at interesting angles. You can even change the camera when you need to film a different part of the world.
* The Viewport is your TV or computer monitor. You use it to look at the movie that the Camera recorded of the Game World. By changing your TV you change how you see the movie. If you use a really wide TV there will be black bars at the edges because the movie does not occupy the entire width of the TV.

# Answer
> 0 votes
First of all, OpenGL doesn't have a definition for a camera or a game world, those are relatively high level.

A gameworld doesn't have dimensions (and even if it did, it certainly wouldn't be in pixels). It's pretty much infinite. Just because you put a 5x5 tilemap in it, it doesn't become finite.

Camera's don't have a resolution, only an aspect ratio and they technically don't even exist, the underlying APIs only render the stuff between (-1, -1, 0) and (1, 1, 1), the engine's job is to put the relevant things in this range by transforming them. They are basically a matrix projecting the coordinate in a cone shaped frustum into a box shaped one:

Camera frustum

Viewport is just a part of your screen the underlying API renders to, this is the only thing, that has a resolution from your question. It's not related to the camera in any way apart from being in the same graphics pipeline. It's usually the same aspect ratio as the camera to keep the image from stretching, but it's not required.

It's definitely a bad way to solve the different aspect ratio problem by stretching or expanding the image or by filling the remaining parts with black. You can simply set the camera to have an aspect ratio, that fits to the window.!!!

---
Tags: opengl, libgdx, camera, viewport
---