# Question
Title: Fragment Shader Code returns weird values
i've implemented a shader that produces a simple Radar Ping given a uniform time input. ShaderToy Proof of concept

Now i implemented this into my real Opengl GLFW GLAD C++ Core4.5Profile NVIDIA GTX960 environment and recieve only weird ouput when i use my own function call.

Why do i recieve such a weird output if i use a function call in opengl glsl?

PS: I have a feeling this has something to do with the precision and the call by value standards of glsl.

Thank you very much for any response, or even a hint where to look for help.

EDIT: The problem was as Kevin van der Velden described.

Result Images:

This is my shader Code:

```
    #version 330 core

    in vec2 v_TexCoord;
    out vec4 FragColor;

    uniform float u_time;

    // Generates a BnW Ping on normalized 2d coordinate system
    float RadarPing(in vec2 uv, in vec2 center,in  float innerTail,
                   in float frontierBorder, in float timeResetSeconds,
                   in float radarPingSpeed, in float fadeDistance,
                   in float currentTime)
    {
        vec2 diff = center-uv;
        float r = length(diff);
        float timeMod = mod(currentTime, timeResetSeconds) * radarPingSpeed;

        float circle;
        circle += smoothstep(timeMod - innerTail, timeMod, r) * smoothstep(timeMod + frontierBorder,timeMod, r);
        return circle;
    }

    void main()
    {
        //normalize coordinates
        vec2 uv = v_TexCoord; //move coordinates to 0..1
        uv = uv*2.; // translate to the center
        uv += vec2(-1.0, -1.0);
        //uv.x *= iResolution.x/iResolution.y; //correct the aspect ratio

        float color;
        // generate some radar pings
        float fadeDistance = 1.0;
        float resetTimeSec = 5.0;
        float radarPingSpeed = 0.3;
        vec2 greenPing = vec2(0.0, -1.0);

        //WITHOUT FUNCTION CALL
        //vec2 diff = greenPing-uv;
        //float r = length(diff);
        //float moduloTime = mod(u_time, resetTimeSec);
        //color = smoothstep(moduloTime - 0.25, moduloTime, r) * moduloTime + 0.025, moduloTime, r);

        //WITH FUNCTION CALL
        color += RadarPing(uv, greenPing, 0.25, 0.025,  radarPingSpeed, fadeDistance, u_time);

        //OUTPUT
        FragColor = vec4(color, color, color,1.0);
    }

```

# Answer
You're invoke (what C++ would call) undefined behaviour, in these lines:

```
    float color;
    color += RadarPing(uv, greenPing, 0.25, 0.025,  radarPingSpeed, fadeDistance, u_time);

```

You're not setting `color` to a value, so depending on the drivers it will just use any old value. Then you're adding a value to it.

Notice that in your code without function call you're using `color = smoothstep(...`, which means you're ignoring whatever was stored in the variable completely, causing it to work as expected.
> 1 votes

---
Tags: opengl, glsl, fragment-shader
---


# Question
Title: Difference between Gdx.graphics.getWidth() and camera.viewportWidth
I am a newbie in game development and I am developing an android game using Libgdx on `intelliJ` IDE. I want to understand the difference between `Gdx.graphics.getWidth()` and `camera.viewportWidth` . As I want the size of everything (example buttons) in my game to be by percentage of width and height of the screen, so what should I use for that `Gdx.graphics.getWidth()` or `camera.viewportWidth` ?

# Answer
> 1 votes
`Gdx.graphics.getWidth()` gives you the width in pixels of the either the window (in desktop mode) or the screen (for IOS or Android).

`viewportWidth` on the `Camera` is the span in *world-units* that the camera can see.

If you set every size up to be a percentage of the screen size then you can use any of the two.

Based on a guess of what you're trying to achieve I think a `ScreenViewport` would work well for you, but note that you might run into issues with aspect ratio as not all devices have screens in the same aspect ratio.

There's good documentation about viewports available at the **libGDX** wiki.

---
Tags: android, libgdx
---


# Question
Title: Why would a game developer choose Direct3D instead of something with more cross-platform support?
Why would a game developer choose to use Direct3D (D3D), instead of using something with more cross-platform support, like the Vulkan or OpenGL APIs?

I know the hardware is actually rendering.

# Answer
> 9 votes
OpenGL is available on many platforms, but that doesn't magically make it a effort-free cross-platform option. There are still many platform variances and platform-specific hitches that somebody using OpenGL has to account for when building a project that will be deployed to many platforms. Initial setup, hardware capability, and driver bugs or implementation details are chief among these concerns.

Certainly using something like OpenGL will reduce the burden of porting to many platforms, but it doesn't completely eliminate it.

With that in mind there are often several reasons that go into a decision to use D3D over OpenGL:

* The developer just likes the API better and would prefer to use it when possible.
* The developer doesn't *actually care* about current or future portability concerns.
    + Or the developer may not *know* OpenGL and doesn't have the time or desire to learn.
    + Or the developer might not think it's worth porting to other platforms due to market share.
    + Or the developer might not have access to any hardware other than a Windows PC.
* The developer wants to use the "best" (most performant, most well-supported, whatever) API on every available platform and the cost of maintaining both a D3D and OpenGL (and Metal... et cetera) renderer is worth it to that developer.
    + Also related to this is the idea that the developer may be porting to something that neither OpenGL or D3D run on, such as a console; at that point they have to pay the cost of building or using an abstraction anyway.
* The developer might be using existing frameworks that make the decision for them.

# Answer
> 4 votes
This is a rather broad question & the specific answer will vary from one situation to the next. Here are some general reasons:

* It takes less time, money & expertise to develop & support a more restricted platform than a broader one.
* You might be using a specific engine, tool or library that's tied to a given platform / API.
* Your development team might not have experience with Vulkan or OpenGL.
* You might personally prefer one API / platform over another.
* Your publisher might have restrictions on platforms they're willing to support.

Ultimately, if you have the luxury of having enough time & or money, you can work around any of the above problems, use whatever tool you want & release on as many platforms as you'd like. In practice, you probably have some constraints that affect your choices.

# Answer
> 4 votes
The answers in this thread all make good points that play into this decision, but a few more things to consider:

* Windows comes with DirectX built-in and the driver certification includes Direct3D support. OpenGL support built-in is limited to software OpenGL 1.5, so anything beyond that requires 3rd party installers & drivers. *These are widely installed by OEMs, but that doesn't mean OpenGL 2.0 or 4.0 will 'work out of the box' the same as DirectX*. So, the edge for supportability on Windows systems goes to DirectX.
* OpenGL includes a very wide ranging amount of functionality including a lot of legacy functionality. Direct3D tends to trim out this older functionality over time. For example, Direct3D 10 or better doesn't include the old fixed-function hardware transform & lighting and texture blend cascade functionality, and just supports programmable shaders. As such, it can be challenging to know exactly which parts of OpenGL to optimize the most and this is a shifting target. Video driver writers tend to focus on a few key OpenGL games and applications, and if you're usage pattern doesn't match it you may well hit bugs or performance cliffs. For a while in the 1990s, your OpenGL game had to do exactly what DOOM did on Windows to work well. It's better these days, but the edge for compatibility on Windows systems goes to DirectX.
* Finally OpenGL tends to be very 'vendor-specific' in the implementation details. A lot of effort from Microsoft goes into making DirectX work well across all vendor's devices, so it tends to be more 'hardware neutral' than the equivalent OpenGL which usually has to use a lot of specific extensions. This is the natural result of the fact that hardware vendors want product differentiation, while software developers want abstraction and consistency.

Ultimately for successful games and engines, the question is not which one to support but which one to do first because successfully popular IP will be shipped on many platforms including those that only support DirectX, and those that only support OpenGL or OpenGL ES.

# Answer
> 3 votes
**Because this is not actually as important as you seem to think it is**

OpenGL (or Vulkan) is not a magic bullet for cross-platform support; in fact supporting multiple rendering APIs on different platforms is a solved problem, and has been for many years. Look at any game that's released for both XBox and Playstation: that game has already solved the problem; it supports two APIs. Does it also have a Windows version? If so then it has support for three APIs.

What's far more interesting than different *software* platforms is different *hardware* platforms, i.e. different GPU vendors, or even different hardware revisions from the same GPU vendor. This is where Direct3D has a number of distinct advantages over OpenGL, including (but not necessarily limited to):

* Developers code to a common runtime so differences between hardware vendors are better abstracted.
* OpenGL typically evolves by means of vendor-specific extensions, meaning that (until the spec settles down) you may have to write multiple different code paths that do the same thing.
* Direct3D tends to give you a better indication of what is actually supported by hardware, whereas OpenGL is allowed fall back to software emulation, which can be too slow to be practically useful (anybody who tried to use non-power-of-two textures on the first available OpenGL 2.0 hardware has bitter experience of this).
* There is typically a good match between Direct3D versions and hardware generations; this was particularly the case for the DirectX 8/9/10 and GL 1.5/2.0/3.0 generations, where Direct3D actually had significant features (such as buffer objects and shaders) in a cross-vendor form before OpenGL did.
* Direct3D driver quality and tools tend to be better.

# Answer
> 0 votes
It is a mix of target market and developer convenience:

* According to Steam Hardware & Software survey as of March 2017, **95.96%** of Steam users are running windows which supports DirectX.
* All generations of XBox also support DirectX exclusively.
* Other consoles use proprietary APIs (Some have partial OpenGL API support with drawbacks.)
* Many GPU drivers on Windows have major bugs in their OpenGL implementations.
* OpenGL documentation and API is often ambiguous and difficult to understand.
* There are API wrappers that use OpenGL and provide a DirectX interface to (relatively) easily port DirectX games to OpenGL platforms.
* OpenGL does not standardize the display initialization, just the rendering.

The biggest advantage of OpenGL is if your target market are Unix workstations (OSX, Linux, BSD, etc) or mobile devices using OpenGL ES and want it to also run on PCs during development.

---
Tags: directx
---


# Question
Title: How does Windows GDI work compared to DirectX/OpenGL?
OpenGL and DirectX, if we are talking about graphics, are somehow built into a graphics card and you can access them using appropriate environment and draw some graphics.

After reading wiki, I came to a thought that even though GDI doesn't use hardware directly as DirectX/OpenGL, it still get its access to a graphics card after some manipulations.

What is GDI and how does it work in compare to these two?

# Answer
GDI is a software rendering API; all the work it does to accomplish the drawing of lines, shapes, fonts, and images is done in *software*. This is because GDI needs to provide a very high level abstraction over target hardware, which is useful for the context in which GDI is intended to be used (drawing application graphics on the huge variety of hardware Windows supports).

This differs from D3D and OpenGL, which ultimately result in a large portion of the heavy lifting to transform and rasterize 3D geometry being executed on the specialized hardware of the GPU.

On modern machines, the renderings produced by GDI are ultimately handed off to the GPU for final output to the screen. You can envision this *conceptually* as handing D3D a series of textured quads, where each texture is some GDI image (in practice, it's more involved). The key point is that GDI is still doing all its work CPU-side.

> OpenGL and DirectX, if we are talking about graphics, are somehow built into a graphics card and you can access them using appropriate environment and draw some graphics.

This isn't strictly correct; OpenGL and D3D are *not* built in to the graphics card. OpenGL and D3D are primarily implemented by *drivers* for the card. The drivers are software, not hardware, although each hardware vendor writes their own according to the internal, often-proprietary specifications of the cards themselves.
> 6 votes

# Answer
if you would have graphics card with 'hardware windows acceleration' then you can try to compare it by performance.I'd see once one had mentioned in 90's.Despite not cost-effective maybe it may accupy some share.But gdi has no even basic 2d stuff like alfa channel or swap buffers(despite its 'doublebuffer' in window class).
> -1 votes

---
Tags: opengl, directx, graphics, rendering
---


# Question
Title: View "distortion" or "stretching" when looking up/down? (Software renderer)
I'm not sure distortion is the right way to describe this. I've uploaded a video to show you guys. Apologies if it's long, but I wanted to show the code as well as posting it here. https://youtu.be/NfcGHjXZJpo Look at the cube carefully when I look down on it from the side.

Basically, when I rotate up or down when I'm close to a polygon, it just seems like it's stretching up or down. It doesn't feel natural to me. I'm not sure what it is or what's causing it. I thought it had to do with either world to camera or camera to perspective transforms, but they all seem right. Aspect ratios are fine too.

My setup:

* I have a low res and high res framebuffers. Both have the same aspect ratio. I render the game to the low res buffer, and render font for example to the high res. When it's time to blit, I "stretch-blit" the low-res buffer to the high-res, and "bit-blit" the high res buffer directly to the screen. (I was stretch-blitting it for testing in the video, but it's a bit-blit)
* I don't use any matrices. All my transformations are functions. For sake of simplicity and ease of 3D education, will add matrices later after I'm comfortable with things without them.
* Camera uses quaternions for it's rotation. The effect still happens if I used a simpler euler angles camera.

Here's what I think is some relevant codes (note that `fix` or `fixed` is just a `typedef` for `float` I was using fixed points initially but switched to floating points for debugging purposes):

Camera:

```
struct camera
{
    vec Position;
    fix FOV, Tan;
    fix ScaleX, ScaleY;
    fix NearZ, FarZ;
    quat Rotation;

    INLINE vec Forward()
    {
        vec Result;

        Result = (Rotation*vec_Forward).Normalized();

        return(Result);
    }

    INLINE vec Right()
    {
        vec Result;

        vec F  = Forward();
        Result = vec_Up.Cross(F).Normalized();

        return(Result);
    }

    INLINE vec Up()
    {
        vec Result;

        var F  = Forward();
        vec R  = Right();
        Result = F.Cross(R).Normalized();

        return(Result);
    }
};

void CameraInit(camera *Camera, vec WorldP, fixed Aspect, fixed FOV)
{
    Camera->Position = WorldP;
    Camera->FOV = FOV;

    // tan fov/2
    Camera->Tan = Math_Tan(Camera->FOV / 2);

    // distance to the projection plane (which is of size 2*ar x 2).
    Camera->ScaleY = 1 / Camera->Tan;

    // we divide x by ar because we want to normalize things on the x too
    // otherwise we'd still be left in the range [-ar, +ar]
    Camera->ScaleX = Camera->ScaleY / Aspect;

    // near/far clipping planes
    Camera->NearZ = (fixed)0.01f;
    Camera->FarZ = (fixed)100.0f;
}

```

Input:

```
fix Horizontal = 0;
fix Vertical = 0;

if (Keys['W'] == Key_Held)
{
    Camera->Position += Camera->Forward() * CamMovSpeed * DeltaTime;
}
if (Keys['S'] == Key_Held)
{
    Camera->Position -= Camera->Forward() * CamMovSpeed * DeltaTime;
}
if (Keys['A'] == Key_Held)
{
    Camera->Position -= Camera->Right() * CamMovSpeed * DeltaTime;
}
if (Keys['D'] == Key_Held)
{
    Camera->Position += Camera->Right() * CamMovSpeed * DeltaTime;
}
if (Keys['E'] == Key_Held)
{
    Camera->Position += vec_Up * CamMovSpeed * DeltaTime;
}
if (Keys['F'] == Key_Held)
{
    Camera->Position -= vec_Up * CamMovSpeed * DeltaTime;
}
if (Keys['J'] == Key_Held)
{
    Horizontal += -CamRotSpeed * DeltaTime;
}
if (Keys['L'] == Key_Held)
{
    Horizontal += CamRotSpeed * DeltaTime;
}
if (Keys['I'] == Key_Held)
{
    Vertical += CamRotSpeed * DeltaTime;
}
if (Keys['K'] == Key_Held)
{
    Vertical += -CamRotSpeed * DeltaTime;
}

// mouse
int dx = Mouse->x - Mouse->LastX; Mouse->LastX = Mouse->x;
int dy = Mouse->LastY - Mouse->y; Mouse->LastY = Mouse->y;
if (Mouse->MMB == Key_Held) // pan
{
    Camera->Position -= (Camera->Up()*dy + Camera->Right()*dx) * SpeedMul/2 * DeltaTime;
}
if (Mouse->RMB == Key_Held) // orbit
{
    Horizontal += dx * SpeedMul*10 * DeltaTime;
    Vertical += dy * SpeedMul*10 * DeltaTime;
}
if (Mouse->Wheel) // zoom
{
    Camera->Position += Camera->Forward() * Mouse->Wheel * SpeedMul*10 * DeltaTime;
}

if (Horizontal != 0 || Vertical != 0)
{
    quat QVertical(vec_Right, -Vertical);
    quat QHorizontal(vec_Up, Horizontal);
    Camera->Rotation = QHorizontal * Camera->Rotation * QVertical;
    Camera->Rotation.Normalize();
}

```

Transforms:

```
INLINE vec ModelToWorld(vec ModelP, vec WorldP, quat Rotation, fix Scale)
{
    vec Result;

    Result = ModelP * Scale;
    Result = Rotation * Result;
    Result += WorldP;

    return(Result);
}

INLINE vec WorldToCamera(vec WorldP, camera *Camera)
{
    vec Result;

    vec Diff = WorldP - Camera->Position;
    Result = Camera->Rotation.Inverse() * Diff;

    // similar effect: project to camera basis (same as multiplying with a rotation matrix)
    //var R = Camera->Right();
    //var U = Camera->Up();
    //var F = Camera->Forward();
    //Result.x = Diff.Dot(R);
    //Result.y = Diff.Dot(U);
    //Result.z = Diff.Dot(F);

    return(Result);
}

INLINE vec CameraToPerspective(vec CameraP, camera *Camera)
{
    vec Result;

    Result = CameraP;
    fix ZInv = 1/Result.z;
    Result.x = (Result.x * Camera->ScaleX) * ZInv;
    Result.y = (Result.y * Camera->ScaleY) * ZInv;

    return(Result);
}

```

Quaternion (taken from MFGD)

```
struct quat
{
    fix w;
    vec v;

    INLINE quat()
    {
        w = 1;
        v = vec_Zero;
    }

    // Building a quaternion from an axis-angle rotation.
    // http://youtu.be/SCbpxiCN0U0
    INLINE quat(vec Axis, fix Angle)
    {
        fix HalfAngle = Angle/2;
        w = Math_Cos(HalfAngle);
        v = Axis * Math_Sin(HalfAngle);
    }

    // http://youtu.be/A6A0rpV9ElA
    INLINE quat Inverse()
    {
        quat Result;
        Result.w = -w;
        Result.v = v;
        return(Result);
    }

    // Multiplying two quaternions together combines the rotations.
    // http://youtu.be/CRiR2eY5R_s
    quat operator*(quat B)
    {
        quat C;

        C.w = w*B.w - v.Dot(B.v);
        C.v = v*B.w + B.v*w + v.Cross(B.v);

        //C.v.x = v.x*B.w + B.v.x*w + v.y*B.v.z - v.z*B.v.y;
        //C.v.y = v.y*B.w + B.v.y*w - v.x*B.v.z + v.z*B.v.x;
        //C.v.z = v.z*B.w + B.v.z*w + v.x*B.v.y - v.y*B.v.x;
        //C.w = w*B.w - v.x*B.v.x - v.y*B.v.y - v.z*B.v.z;

        return(C);
    }

    INLINE quat operator*=(quat Q)
    {
        return *this = *this * Q;
    }

    // Rotate a vector with this quaternion.
    // http://youtu.be/Ne3RNhEVSIE
    // The basic equation is qpq* (the * means inverse) but we use a simplified version of that equation.
    vec operator*(vec Vector)
    {
        vec Result;

        quat Q;
        Q.w = 0;
        Q.v = Vector;

        // Could do it this way:
        //const Quaternion& q = (*this);
        //return (q * p * q.Inverted()).v;

        // But let's optimize it a bit instead.
        Result = this->v.Cross(Vector);
        Result = Vector + Result*(2*w) + this->v.Cross(Result)*2;

        return(Result);
    }

    INLINE fix Length()
    {
        return sqrt(v.x*v.x + v.y*v.y + v.z*v.z + w*w);
    }

    INLINE quat Normalized()
    {
        quat Result;
        // TODO: handle L=0
        fix L = Length();
        Result.v = this->v/L;
        Result.w = this->w/L;
        return(Result);
    }

    INLINE void Normalize()
    {
        *this = this->Normalized();
    }
};

```

Any ideas what's causing that stretch? or am I just seeing things.

**\[EDIT\]** Rasterizer code (Note I have a flag to switch between z-buffering and z-sorting. Should have two different rasterize functions instead of the if-statement):

```
void Rasterize(vec v0, vec v1, vec v2, vec uv0, vec uv1, vec uv2, texture *Texture,
               framebuffer *LowBuffer, depthbuffer *DepthBuffer)
{
    assert(Texture);

    // set raster points
    BeginSample("Points&Box&Clip");
    raster_point p0 = { v0.x, v0.y };
    raster_point p1 = { v1.x, v1.y };
    raster_point p2 = { v2.x, v2.y };

    // get triangle bounding box
    i32 MinX = Math_Min3(p0.x, p1.x, p2.x);
    i32 MaxX = Math_Max3(p0.x, p1.x, p2.x);
    i32 MinY = Math_Min3(p0.y, p1.y, p2.y);
    i32 MaxY = Math_Max3(p0.y, p1.y, p2.y);

    // clip against screen
    MinX = Math_Max(MinX, 0);
    MinY = Math_Max(MinY, 0);
    MaxX = Math_Min(MaxX, LowBuffer->Width - 1);
    MaxY = Math_Min(MaxY, LowBuffer->Height - 1);
    EndSample();

    // calculate barycentric increments
    BeginSample("Bary Setup");
    i32 IncrementX_01 = (p0.y - p1.y), IncrementY_01 = (p1.x - p0.x);
    i32 IncrementX_12 = (p1.y - p2.y), IncrementY_12 = (p2.x - p1.x);
    i32 IncrementX_20 = (p2.y - p0.y), IncrementY_20 = (p0.x - p2.x);
    EndSample();

    // calculate initial edge values and areas
    BeginSample("Initial Edge");
    raster_point Point = { MinX, MinY };
    i32 E01_Row = EdgeFunction(p0, p1, Point);
    i32 E12_Row = EdgeFunction(p1, p2, Point);
    i32 E20_Row = EdgeFunction(p2, p0, Point);
    i32 Area = EdgeFunction(p0, p1, p2); //technically area x 2
    fix OneOverArea = 1.0f / Area;
    EndSample();

    // fill pixels
    BeginSample("Blending & Fill");
    for (i32 y = MinY; y <= MaxY; y++)
    {
        // cache row edge function values
        // so we can increment them in the
        // inner loop. we should NOT be
        // incrementing the original row
        // values in there!
        i32 E01 = E01_Row;
        i32 E12 = E12_Row;
        i32 E20 = E20_Row;

        for (i32 x = MinX; x <= MaxX; x++)
        {
            if ((E01 | E12 | E20) >= 0)
            {
                fixed W0 = E12*OneOverArea;
                fixed W1 = E20*OneOverArea;
                fixed W2 = E01*OneOverArea;

                if ((W0 < 0 || W0 > 1) ||
                    (W0 < 0 || W0 > 1) ||
                    (W0 < 0 || W0 > 1))
                    continue;

                fixed InterpolatedZ = v0.z*W0 + v1.z*W1 + v2.z*W2;

                #if defined(PERSPECTIVE_CORRECT)
                fixed Z = 1.0f / InterpolatedZ;
                #else
                fixed Z = InterpolatedZ;
                #endif

                i32 Offset;

                if (UseZBuffer)
                {
                    Offset = (y*DepthBuffer->Width + x);
                    fixed DepthValue = DepthBuffer->Memory[Offset];
                    if (Z < DepthValue)
                    {
                        DepthBuffer->Memory[Offset] = Z;

                        Offset = (y*LowBuffer->Width + x)*LowBuffer->BytesPerPixel;
                        i32 *Pixel = (i32 *)(LowBuffer->Memory + Offset);

                        vec UV = uv0*W0 + uv1*W1 + uv2*W2;

                        #if defined(PERSPECTIVE_CORRECT)
                        UV *= Z;
                        #endif

                        UV.x = Math_Clamp(UV.x, (fix)0, (fix)1);
                        UV.y = Math_Clamp(UV.y, (fix)0, (fix)1);

                        i32 tx = (i32)((UV.u * (Texture->Width - 1)) + 0.5f);
                        i32 ty = (i32)((UV.v * (Texture->Height - 1)) + 0.5f);
                        byte *Color = (byte *)Texture->Memory + (Texture->Width*ty + tx)*Texture->BytesPerTexel;
                        *Pixel = Color[3]<<24 | Color[0]<<16 | Color[1]<<8 | Color[2];
                    }
                }
                else
                {
                    Offset = (y*LowBuffer->Width + x)*LowBuffer->BytesPerPixel;
                    i32 *Pixel = (i32 *)(LowBuffer->Memory + Offset);

                    vec UV = uv0*W0 + uv1*W1 + uv2*W2;

                    #if defined(PERSPECTIVE_CORRECT)
                    UV *= Z;
                    #endif

                    UV.x = Math_Clamp(UV.x, (fix)0, (fix)1);
                    UV.y = Math_Clamp(UV.y, (fix)0, (fix)1);

                    // Windows: ABGR
                    // Texture: RGBA
                    i32 tx = (i32)((UV.u * (Texture->Width - 1)) + 0.5f);
                    i32 ty = (i32)((UV.v * (Texture->Height - 1)) + 0.5f);
                    byte *Color = (byte *)Texture->Memory + (Texture->Width*ty + tx)*Texture->BytesPerTexel;
                    *Pixel = Color[3]<<24 | Color[0]<<16 | Color[1]<<8 | Color[2];
                }
            }

            // increment one to the right
            E01 += IncrementX_01;
            E12 += IncrementX_12;
            E20 += IncrementX_20;
        }

        // increment one row down
        E01_Row += IncrementY_01;
        E12_Row += IncrementY_12;
        E20_Row += IncrementY_20;
    }

    EndSample();
}

```

Here's how I set values for perspective correct stuff:

```
// perspective & screen transforms
    {
        ForI(RenderList->PolyCount)
        {
            var It = &RenderList->PolyStorage[i];
            if ((It->Flags & Polygon_Culled) == 0)
            {
                // camera to perspective
                {
                    It->Vertices[0] = CameraToPerspective(It->Vertices[0], &Camera);
                    It->Vertices[1] = CameraToPerspective(It->Vertices[1], &Camera);
                    It->Vertices[2] = CameraToPerspective(It->Vertices[2], &Camera);
                }

                // perspective to screen
                // X: [-1, 1] -> [0, Width]
                // Y: [1, -1] -> [0, Height]
                {
                    It->Vertices[0] = PerspectiveToScreen(It->Vertices[0], HalfWidth, HalfHeight);
                    It->Vertices[1] = PerspectiveToScreen(It->Vertices[1], HalfWidth, HalfHeight);
                    It->Vertices[2] = PerspectiveToScreen(It->Vertices[2], HalfWidth, HalfHeight);
                }

                #if defined(PERSPECTIVE_CORRECT)
                It->Vertices[0].z = 1.0f / It->Vertices[0].z;
                It->Vertices[1].z = 1.0f / It->Vertices[1].z;
                It->Vertices[2].z = 1.0f / It->Vertices[2].z;
                It->UVs[0] = It->UVs[0] * It->Vertices[0].z;
                It->UVs[1] = It->UVs[1] * It->Vertices[1].z;
                It->UVs[2] = It->UVs[2] * It->Vertices[2].z;
                #endif
            }
        }
    }

```

# Answer
That's normal. It's the effect of perspective projection, the renderer tries to shove a spherical area into a flat area.

Try this: Take a balloon, draw a rectangle (and something in it if you want to have a better visual cue) on it and pop it. Then try cutting out the rectangle and flattening it. You probably won't succeed or if you do, you get a very distorted scene.

If the player'd see everything around himself/herself, he'd have a spherical viewport, but because you limit the view to a specific angle, the player's viewport is only a part of it. Here you get the same problem that cartographers are trying to solve for centuries now.

You can make the effect less apparent by reducing the field of view. In my experiences, a field of view of around 60° vertically makes the best area-distortion ratio, but it depends on the game.
> 0 votes

---
Tags: camera, rotation, perspective, software-rendering, win32
---


# Question
Title: Why I can't change from one scene to another by using SceneManager.LoadScene()?
I made a game with two scenes and everytime I call the function `SceneManager.LoadScene()`, no matter the value, type(`string` or `int`) or mode(`single` or `additive`) of the parameters, the scene with build index 0 is always getting loaded.

# Answer
You're trying to load `"Level 2"` but the scene name in the build settings is `Level2` (no space)
> 0 votes

---
Tags: unity, scenemanager
---


title: How can I generate Sudoku puzzles?

text:
# Question
Title: How can I generate Sudoku puzzles?
I'm trying to make a Sudoku puzzle generator. It's a lot harder than I expected and the more I get into it, the harder it gets!

My current approach is to split the problem into 2 steps:

1. Generate a complete (solved) Sudoku puzzle.
2. Remove numbers until it's solveable and has only 1 solution.

In step 1, since I'm using a brute force methods, I'm facing some run time issues. Is there an optimal way of filling in a complete Sudoku puzzle?

In step 2, what kind of algorithm should I use to "puzzlize" a solved sudoku?

# Answer
I have a top selling Sudoku game on the iOS app store. Here's how I generated puzzles.

First I do have a puzzle generator application. But it's not part of the game's code. It' is a stand alone app that I use to make puzzles. It's highly modified so I can set it to create different pattern types, difficulty ratings, number of givens, etc. Generating puzzles and getting a consistent difficulty level is hard to do on the fly and takes more time than a player would want to wait. So, I generate what I call "seed puzzles" and that is what is used by the game's code to generate the puzzles that people play.

I'm not answering how to code a generator here. You can google and find tons of puzzle generator code online. Start there. But to make a good game you need to make a good game. My game does not generate puzzles on the fly.

The way my puzzle generator app works is that it generates thousands of puzzles per minute, but they're not all good and they don't all match a specific difficulty rating. The generator creates a puzzle, then solves it and figures out a difficulty rating, and scores the puzzle based on the techniques needed to solve the puzzle, and determines if guessing is required to solve it (which is usually bad). It tosses out any puzzles that don't match a criteria. For hard but not impossible puzzles, on a fast machine, it can take an hour to generate 100 puzzles that match my exact specifications. This is why I don't do this in the app. Generating puzzles on the fly with those tough specifications wouldn't work for the quality of puzzles that I have in my app. So I run that app in 10 windows at a time all night to get the number of puzzles I need.

The puzzles are strings, 162 characters long, 81 characters with numbers and dashes or dots where the blanks are going to be, then another 81 with the solution. Then columns for each of the stats, like how many singles, doubles, etc.

My output from all the generation sessions are comma delimited lines with the stats as columns. I'll take maybe 10,000 puzzles, bring them in to excel, and sort them by difficulty. Then bring them into an app to see them on the game board. I also look at them for visual appeal and the visible patterns to the puzzle. Then I hand pick from those.

I call them seed puzzles and here's what I mean. The numbers in a sudoku game are really just tokens. Instead of being the numbers 1-9 they could be colors or symbols or letters. So my seed puzzles are not numbers they are the letters a-i. Each seed puzzle gets changed on the fly to make a playable puzzle:

1. Randomize the numbers/tokens. When I turn the letters a-i back to into the numbers 1-9 the lookup table is randomized. Meaning that a isn't always 1. That alone creates about 300,000 variations on each puzzle.
2. Rotate the puzzle by 90, 180 or 270 degrees. That adds 4 more variations.
3. Flop the puzzle horizontally, vertically, or both. That adds 4 more variations.

Each seed puzzle therefore can create 5,806,080 variations. I've tested this in the field with real players. People do not know they're essentially playing the same puzzle. It's impossible actually. Only if they were to notice that the pattern the givens are in are the same each time. But with even 100 different seeds no one will notice. A million users of my game haven't. I've also tested it with solver apps. A solver app won't solve a puzzle the same way when it's rotated or flopped. It will even sometimes analyze it as a different difficulty rating even though it's technically the same puzzle.

However, Big Bad Sudoku Book has 10's of 1000's of seed puzzles in 5 difficulty levels, and multiple puzzle patterns types. This means that there are billions of puzzles in my game. With every 10,000 seed puzzles there are 58,060,800,000 different puzzles.

In Sudoku Book version 4 (due out 2016) I figured out a way to be able to specify an exact puzzle out of those 58 billion and get the same puzzle on each player's device.
> 50 votes

# Answer
> In step (1) Generate a complete (solved) Sudoku puzzle, since I'm using a brute force method, I'm facing some run time issues. Is there an optimal way of filling in a complete Sudoku puzzle?

There is an easy way to fill in a complete Sudoku puzzle - group filling and circular shift.

1. Fill the first row with nine different numbers.
2. Fill the second row which is a shift of the first line by three slots.
3. Fill the third row which is a shift of the second line by three slots.
4. Fill the fourth row which is a shift of the third by one slot.

```
line 1: 8 9 3  2 7 6  4 5 1
line 2: 2 7 6  4 5 1  8 9 3 (shift 3)
line 3: 4 5 1  8 9 3  2 7 6 (shift 3)

line 4: 5 1 8  9 3 2  7 6 4 (shift 1)
line 5: 9 3 2  7 6 4  5 1 8 (shift 3)
line 6: 7 6 4  5 1 8  9 3 2 (shift 3)

line 7: 6 4 5  1 8 9  3 2 7 (shift 1)
line 8: 1 8 9  3 2 7  6 4 5 (shift 3)
line 9: 3 2 7  6 4 5  1 8 9 (shift 3)

```

To prevent the user from noticing the obvious pattern, it might be a good idea to randomize the order of the rows and the columns so that there no longer is any pattern. So long as all 9 numbers in each row/column move together as one atomic unit, the Sudoku board will always remain valid.

You get a complete filled Sudoku puzzle. For more details, you can search "make Sudoku".
> 10 votes

# Answer
It's not too difficult, provided that you have a sudoku solver.

*Making sudoku solvers is a hard / interesting problem, so it's best to save it for a different question. Or you can just read this and see how you go.*

1. To generate a solved puzzle, simply run the solver on an empty board. The only caveat is you should randomise the "guesses" that the solver uses, otherwise you might end up with the same puzzle every time. That is, at some point the solver will try a number for a cell; it might try it in this order: `1, 2, 3, 4, ...` and pick the first one that works. You need to shuffle that order so that it tries, say, `4, 7, 2, 9, ...`. This process should be as fast as your solver.
2. To remove numbers, use this algorithm:
    * Pick a random number you haven't tried removing before
    * Remove the number, run your solver with the added condition that it cannot use the removed number here
    * If the solver finds a solution, you can't remove the number
    * Repeat, until you have removed enough numbers (or you can't remove any more)

This is a very simple (and naive) method, so there's no guarantee that you'll get puzzles of a certain difficulty - aside from the number of missing numbers that is - or if you can even remove the amount of numbers you want. Hope this helps anyway.
> 4 votes

# Answer
I just think its interesting to point out this webpage, since it helped me a lot for our proyect development. Making a sudoku with an unique solution is far away from a simple task. In the link you can find how the author (he really did a great job, its no me eh!), found several different strategies. You can have an idea to generate your own Sudoku solver.

Now, going with the topic, there is also a way to generate similar sudokus, just by

1. The permutation of the rows.
2. Other simple solution, is to start with a fill out sudoku of minimun 17 digits fill in (its the proven minimun to find a unique solution), and fill in following diferent strategies (e.g. in the previous link the strategies are divided on difficulties, you can do something similar), till you reach the unique solution.
3. There was a list of a mathematician trying to find a 16 starting digit unique solution sudoku, with a HUGEEEEEE list of 17 digits sudokus. I cant remember if he has any kind of copy write, but Im pretty sure, if you can offer him other 17 unique solution sudoku will be more than glad to let you use his data.

Cheers and good luck with the algorithm :D
> 0 votes

# Answer
My solver is using brute force, and can find solution within 20 milliseconds. By using the deletion method, described above, my generator produces a puzzle within 200 milliseconds.

It usually generates a puzzle with around 24-34 digits left, and I still don't know how in the world they manage to produce 17-digits puzzle.
> 0 votes

---
Tags: algorithm, puzzle, content-generation
---


# Question
Title: Scene2D set table cell size in percentage of tables ´s size
Is it somehow possible to set Scene2D table cell´s size in percentage of the table?

I would like to have orientation independent menu, with buttons filling let´s say 75% percent of the screen, and also to respond on window resizing (desktop version). I have tried several methods, for example using `Value`

```
table.add(button).width(Value.percentWidth(.75F));

```

but when `value.get(actor)` is called inside cell, it is supplied with inner button actor not its container (table).

I have also tried to set it in fixed fashion

```
table.add(button).width(Value.percentWidth(.75F).get(table));

```

This works fine, but since I set pixel value insted of Value object it is not recalculated upon resizing.

Is there any way to achieve this?

# Answer
You can change the `Actor` that the `Value` acts on by supplying the actor (in your case your `table`) in the constructor like so:

```
table.add(button).width(Value.percentWidth(.75F, table));

```

This will make `Value` use that actor for the `Value#get(actor)` method instead of the default parent actor.
> 4 votes

---
Tags: libgdx, scene2d
---


# Question
Title: Third Person - Highlight "Usable" Objects
I'm trying to figure out a good solution in a third-person RPG to determine if the character is facing and close enough to an object for it to highlight and be shown as a usable item - a door, or a chest, or any other usable object in the scene.

I imagine the best approach is ray-casting, but I've yet to figure out how this would actually work. I plan to have a `usable` script on all usable objects that defines what happens during use (a door or chest opens, a coin goes into your inventory, etc), but I need to know whether the player can use the item, highlight it, and also determine which object is the "best choice" based on facing direction and distance if multiple items are in range.

# Answer
You can figure out how much the player faces an object by taking the normalized vector pointing from the player to the object and the player's directional vector and using dot product on them. If the player faces the object exactly, then it'll return 1, if the player's looking in the other direction, then -1.
> 1 votes

# Answer
A simple BoxCast(NonAlloc) used to create a box at a reasonable distance in front of the character will do the job. If you can afford using a `LayerMask` (let's say all your interactive objects are tagged as interactive) only the right objects will be returned. Then you can apply your logic to determine the most relevant one.
> 1 votes

# Answer
**I think the simplest way to solve this is using a collider.**

1. Create a collider originating at the player's camera.
2. Extend this collider in front of the player to simulate the player's field of view.
3. Mark the collider as trigger.
4. On the `OnTriggerEnter` method, check if the other object has for example a script component named *UsableObject*
5. Call a *Highlight* method that you defined on that class
6. On the `OnTriggerExit` method, call another method on that class that turns off the highlight.

As for the collider's shape - it is best if you create a frustrum shape or a cone/pyramid. However these cannot be natively created in Unity and you'll have to import a model from Blender or similar. If you need more help with that let me know.
> -2 votes

---
Tags: unity, raycasting
---


# Question
Title: When should I use instancing versus a constant buffer?
I've heard something about instancing and understood it's useful for drawing the same object many times with slight changes. It's faster because you call the draw function once per frame and update the buffer (in this case the instance buffer) once per frame too while with constant buffers, for example, if you need a world matrix you have to update your constant buffer once per object.

But if I have only one object, would instancing be faster (or at least as fast as) using a constant buffer? With instancing, you have to call only an update buffer function (for the vertex-instance buffer) while with CB you need two calls: one for the vertex buffer and one for the constant buffer.

Another question about instancing:

Since I have to update the instance buffer once per frame, I need to create it with `DYNAMIC_USAGE` and with a byte width representing the maximum number of objects I can draw with one call. For example, if I want to pass a matrix, I need `insBufferdesc.bwitdh= sizeof(matrixtype)*maxNumObjs`. Is this right? Given that `maxNumObjs` is 20 and I want to render only 10 objs, I've should just update the first 10 matrices of the buffer and call `drawInstanced(..., 10)`. Will I get some error if I don't use all of the buffer?

# Answer
> 1 votes
First question: You are wrong where you state that with instancing you have to update one buffer while with constatnt buffers two buffers. There is no vertex-instance buffer but a vertex buffer and an instance buffer (which is also created with the D3D11\_BIND\_VERTEX\_BUFFER flag). So either way you have to update the vertex buffer and instance (or constant) buffer - If they need to be updated.
You second question is correct, you have to create a buffer with maximum size which could be used and only write the visible objects to the beginning of the buffer. Then call draw with the appropriate number of vertices for example: `drawinstanced(...,10*object.vertices.count());`

# Answer
> 1 votes
You don't need a second vertex buffer (passing 2 vertex buffers) It's more easy to use one vertex buffer en still call the `DrawIndexedInstanced(triangleIndicesCount, instanceCount, 0, 0, 0)`. Your vertex shader will be called for all instances, but you need to add another symantic to your `vertex_in` struct.

```
struct VertexIn
{
    float3 PosL : POSITION;
    float3 Normal : NORMAL;
    float2 Tex : TEXCOORD;
    unsigned int InstanceId : SV_InstanceID;   // <-- this one will be filled with the instance index.
};

```

For the instances *(world matrix, colors, etc)*, you can use a `StructuredBuffer` or a `ConstantBuffer`. Structured buffers can be larger than 64k, Constant buffers are faster *(but need to be aligned on 128bit)*.

Using a constant/structured buffer over a second vertex buffer is way more maintainable, because you don't need to specify the combined InputLayout for both the vertex and the instance etc. The Vertex format for single draw/multi instanced draw is the same.

---

Another optimize you could think of *(instead of directly choosing hardware instancing)* is combining meshes into a single geometry. For example, instead of rendering 10k blades of grass, you could combine multiple blades in one geometry and rendering them through eachother, which will look as all blades are moving separately.

Rendering one mesh with many vertices VS rendering multiple times the same meshes, the one mesh is way more parallel. The one mesh vertices are calculated completely parallel. Hardware instancing doesn't render the geometries parallel(the are rendered in serial, so the vertices aren't calculated parallel across multiple instances), but it only eliminates the `DrawIndexed()` call and updating multiple matrices instead of a single one for each draw.

---
Tags: c++, rendering, directx11, instancing
---


title: How to Clamp rotation of a turret

text:
# Question
Title: How to Clamp rotation of a turret
I'm going mad to clamp rotation of an object.

I've tested using Inspector that correctly rotation range is Z\>-15 and Z\<30.

I've written this code but it isn't working properly !

```
if (rb.transform.rotation.eulerAngles.z > 30)
    rb.transform.Rotate (-Vector3.forward * speedTurretMovement  , Space.Self);
if (rb.transform.rotation.eulerAngles.z < -15 )
    rb.transform.Rotate (Vector3.forward * speedTurretMovement , Space.Self);

```

Thanks

# Answer
> 3 votes
```
using UnityEngine;

public class Body : MonoBehaviour
{
    public GameObject head; //ref the head / turret via inspector
    public int angle = 0;
    public int min = -15;
    public int max =  30;

    void Update ()
    {
        angle += Input.GetKey(KeyCode.LeftArrow) ? 1 : 0;
        angle += Input.GetKey(KeyCode.RightArrow) ? -1 : 0;
        angle = Mathf.Clamp(angle, min, max);
        head.transform.eulerAngles = new Vector3(0, angle, 0);
    }
}

```

Create a **new**, clean scene. Create a cube `GameObject` called `Body` and drop this script on it. Create another cube called `Head` and drop it inside the `Body`. Drag inspector connection for `Head` onto the `Body` script. Make sure they are both at world origin. Use arrow keys to control. Have fun.

P.S. Nothing stops you from calling this script `Head` and dropping it on `Head` instead. I just like the idea of the `Head` controlling the `Body`, and providing angular constraints.

# Answer
> 0 votes
just use `Mathf.Clamp(value,min,max);`

# Answer
> 0 votes
```
rb.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Clamp(transform.eulerAngles.z + rotationAmount * Time.deltaTime, -15, 30)));

```

If you don't want to use `Quaternion`.

```
direction = -1 or 1
rb.transform.Rotate(new Vector3(0, 0, Mathf.Clamp(speedTurretMovement * direction, -15 - rb.transform.eulerAngles.z, 30 - rb.transform.eulerAngles.z)), Space.Self);

```

---
Tags: unity, rotation
---


# Question
Title: What functional abstraction to use for multi-agent simulation?
this is quite a broad question, touching a few different fields, so let me know if there's a way to narrow it down.

What I would like to know is your opinions on what abstraction to use for my use case.

My game is a grid-based trading game (it's more complicated than that, but for now think of a Patrician on a grid) and I want to do some heavy simulation in the settlements. Heavy here means that the decisional processes and actions of every individual is simulated. I already managed to do a stress test and I know I can handle about 1 milion individuals without any slow down for the game.

The game is written in Scala in a functional style. The problem is that I achieved those performances using a naive copy of immutable states. So for every entity and settlement I compute the next state, I aggregate it in a global state and in the next iteration, I replace the old state with the new one. The issue is with the garbage collector: if the state grows too much after a while it tries a full garbage collection to free up memory and considering that with this approach I may have two whole sized states (the old one and the just computed new state), this gargabe collection may happen at every step.

What I did to solve this was to break the global state in N parts, computing and replacing parts of the state in N iterations. This works because every settlement is assumed to be in isolation and so it won't conflict with the others. This is a strong assumption though and in such an early state of development I don't want to be bound to it.

So what I need is a way to structure this simulation, settlement by settlement but that allows the agents on the map to interact with the settlements. The abstraction must be functional and match the requirements for the memory issue.

An obvious answer may be to use actors but I fear that using frameworks like Akka, the overhead may be too great for a game.

# Answer
Let's look *just* at the primary performance problem you mention, and ignore further wild assumptions.

GC issues can be eradicated by using an object pool and pre-allocating all possible objects you may need to use, at startup time (as the Marmalade framework does, for example). This way you reuse the same objects repeatedly, instead of `free`ing old and `alloc`ing new memory under the hood. That alone will give you the biggest performance boost you are likely to see for your application.

As an example of pre-allocation: Let's say I run an existing version of my app, warts and all, and determine I will never need more than a thousand towns maximum, and one million people maximum, across the entire world. I can now allocate the initial arrays of people and towns to these figures, and only use those portions of each array that I *need at a given time*. Any time one of them becomes defunct in the game, I clear its state, and pass its index (or instance *at that index*) into the object pool, thereby freeing it up for later reuse once a new person / town spawns.

As an alternative to pre-allocating *all* object instances at startup time, you could also start small but double the size of your array / collection every time you hit its size limit. This is a viable strategy for most applications, frameworks and platforms, as you will then rapidly get to a point where no further allocations are required and the application will run smoothly thereafter.

Also, GC is timed to happen at regular intervals; it will not happen every frame as you suspect. However, I imagine you could run out of available memory in the meantime while blocks that are to be flushed on the next sweep, remain in limbo. That all really depends on just how large your states are.

**Why do we not always pre-allocate, then?** Flexibility. Operating systems and desktop applications tend to handle multiple tasks and so allocate and free memory in small chunks, given that they don't know what demands the user is going to put on the system next. But for games where all your attention is focused on the game itself, until you shut it down, preallocation can work very well.

**P.S.** Once you've solved this problem, you can go back and look at other issues like data proximity for cache purposes and so on. But that will be a separate phase and perhaps even unnecessary.
> 1 votes

---
Tags: performance, simulations
---


# Question
Title: How to animate alpha channel of sprite color using Animator in code in Unity3D?
I tried Animator + AnimationClipPlayable, but failed. Sprite disappears completely after 1 second, without animation happening. If I set "1" instead of "0" for final point, then nothing happens.

Code:

```
    AnimationClip clip = new AnimationClip();
    AnimationClipPlayable playable = AnimationClipPlayable.Create(clip);

    gameObject.AddComponent<Animator>();

    AnimationCurve alpha = AnimationCurve.Linear(0, 255, 1, 0);
    clip.SetCurve("", typeof(SpriteRenderer), "m_Color.a", alpha);

    gameObject.GetComponent<Animator>().Play(playable);

```

# Answer
Color.a accepts a float value in the range from 0 to 1, not from 0 to 255. It is also a reason why you see a sudden disappearance, because it gets to 0 at the end.

The solution is simple, change "255" to "1". Code:

```
    AnimationClip clip = new AnimationClip();
    AnimationClipPlayable playable = AnimationClipPlayable.Create(clip);

    gameObject.AddComponent<Animator>();

    AnimationCurve alpha = AnimationCurve.Linear(0, 1, 1, 0);
    clip.SetCurve("", typeof(SpriteRenderer), "m_Color.a", alpha);

    gameObject.GetComponent<Animator>().Play(playable);

```
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Why are modern open world games so quiet?
When I first got Skyrim, my friends kept ranting about how great the music was. I found this odd, since I only remembered the same old music only popping up during random encounters. After awhile I just assumed that my installation was broken (for some reason the music files were corrupted or something). Then I saw my one of my friends playing their copy, and lo and behold, their game was just as quiet—with only footsteps sound effects.

Now my roommate's version of Breath of The Wild shows up, and even Legend of Zelda games are following this trend?! What happened? What happened to the obnoxious Morrowind music? The ambient musical feel of each region in Ocarina of Time? Why would game developers eliminate such a powerful tool for creating atmosphere?

# Answer
> 3 votes
Poignancy / relevance. Over the '90s-'00s, people got tired of music constantly overwhelming every aspect of their play. The same thing has happened over the course of my life in TV and movies. I think many people prefer having long periods of just being exposed to the natural sounds of the world in question, or straight dialogue, and then occasionally having the music pop up when appropriate, making the experience more meaningful. This, along with the large number of tracks in Skyrim, reduces the chances that you'll get utterly sick of one track or another, thereby improving enjoyment at key moments. I would also say that gaming has matured as a large portion of gamers from the 70s-90s have grown into middle-aged folk. A good example of "less music" in TV is True Detective.

Anecdotally, I enjoy the nature ambience of Skyrim these days, often more than the tracks themselves. It's low key, and requires less mental energy to parse / process when your mind is on other things.

# Answer
> 3 votes
The problem is that such open world games are often played for a very long time. Even the best and longest soundtrack becomes repetitive over time. Whatever emotional impact it had when heard for the first time gets diminished to obnoxious background noise sooner or later.

That might in fact be the reason why many people remember the music in Skyrim so fondly: Because it only appears in situations where it has the maximum atmospheric impact. The epic Skyrim theme song, for example, is only ever heard in the actual game when the player is fighting a dragon. These fights are very rare if compared to the rest of the playtime, but are among the most epic moments of the game. The rare music makes these fights even more epic. If intense music like that would play all the time, then it wouldn't add any more to these scenes.

Also, background music tends to drown out other sounds from the surrounding or even worse might contain parts which can get mistaken for gameplay-relevant sounds. This can be especially troublesome in games where listening to the environment is part of the game mechanics. That can be enemy chatter and footsteps during a stealth part or random phrases spoken by NPCs while exploring a city which might contain interesting exposition.

That's why some game designers developed the tendency to only use background music in those moments which warrant some additional emotional impact.

---
Tags: art, music
---


# Question
Title: How do you define walkable and unwalkable areas in Tiled?
Hi I want created map in Tiled program. How can I generator that 2D array with 0 - unwalkable 1 - walkable 2 - damageble

I suppose I must set it somehow, can someone tell me how to give me link so some tutorial ?

# Answer
A common method is to have one special "Collison" layer. This is a layer which you don't draw in the game but which you use to place special tiles which say which parts of the map are walkable.

Another option is to use tile properties to set the walkability for each type of tile. This has the advantage that you can just map in a what-you-see-is-what-you-get style and don't have to bother with creating the collision map by hand. But unfortunately you now no longer *can* modify the collision map manually, so if you have some rare occasion where a usually blocking tile is supposed to be walkable or a usually walkable tile is supposed to be blocking, you can no longer do that.
> 1 votes

---
Tags: javascript, tiled
---


title: 2d game with 3d js. game engine

text:
# Question
Title: 2d game with 3d js. game engine
I'm trying to understand if it's possible to create a game where the player can switch between 2d (strategic/bird view) and 3d (actual gameplay) using only the 3d supported JS/HTML5 game engine, like three.js or babylon.js?

I'm aware that there are few 2d/3d game engines like Godot, Turbulenz and Blend4Web, but still curious if i can do it same good only with a 3d game engine.

Thanks in advance.

# Answer
2d rendering is easily possible with 3d rendering engines, even when there is no explicit support for it.

How it would work: Just put your two-dimensional geometry parallel to the xy-plane (or any other plane) and set your camera's viewing direction orthogonal to this plane. I would suggest using a orthogonal projection matrix, which allows you to make use of different depth-levels easily (which may look odd if you're using a 3-dimensional perspective projection).

I you just want to show your normal scene from above you don't even need to set up manual 2d-geometry. Just Put your camera above your scene (usually in +y direction) and switch to orthogonal projection.
> 2 votes

---
Tags: html5, webgl, browser-based-games, three.js, godot
---


# Question
Title: XMMATRIX XMMatrixRotationY wants the angle in radians or degrees? DirectX
The documentation is totally unclear about it. And also what does" Angles are measured clockwise when looking along the rotation axis toward the origin" mean? Are they measured clockwise looking from where? Documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx\_sdk.matrix.xmmatrixrotationy(v=vs.85).aspx

# Answer
It's actually right there in the documentation you linked (emphasis mine):

> Angle of rotation around the y-axis, **in radians**. Angles are measured clockwise when looking along the rotation axis toward the origin.

The "measured clockwise when looking along..." bit is intended to clarify the semantics of the rotation. Imagine a pencil which represents your axis of rotation (the Y axis in this case). Imagine the tip of the pencil, the bit you write with, is the origin. If you are somewhere on that axis looking *away* from the origin, a clockwise rotation goes one way relative to the world. If you are somewhere on that axis looking *towards* the origin, the clockwise rotation goes the opposite way relative to the world.

The convention of `XMMatrixRotationY` is the latter.
> 2 votes

---
Tags: directx11, c++
---


# Question
Title: How much is atomicAdd slower than an atomic counter?
I am considering replacing an atomic counter in my shader code with a SSBO an `atomicAdd` operation. What I need to know is the difference in performance of these two. I know the atomic counter executes in roughly 3 clock cycles on my Geforce 840m. The reason behind this is that I would like to add an arbitrary number to the counter rather than just increment by 1.

# Answer
According to https://software.intel.com/en-us/articles/opengl-performance-tips-atomic-counter-buffers-versus-shader-storage-buffer-objects there is no difference in performance between the two on Intel's integrated GPUs. I suspect that the argument that they are implemented with the same instruction under the hood is valid on other vendor GPUs as well, so the performance difference between them, if it ever exited, should decrease with time.
> 1 votes

---
Tags: opengl, glsl, gpu
---


title: Gun Rotation Unity

text:
# Question
Title: Gun Rotation Unity
https://www.youtube.com/watch?v=m-J5sCRipA0 \- this tutorial by brackeys shows how rotate your 2d gun using your mouse. How can I edit this script to add an auto rotating system. Where the gun keeps rotating and when you press a certain button(i.e. space) it stops and shoots.

This is the code for rotating your 2d gun using your mouse;

```
void Update(){
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; // subtracting the position of the player from the mouse mous position
difference.Normalize(); // normalizing the vector. meaning that all the sum of the vector will be equal to 1
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; //find the angle in degrees
transform.rotation = Quaternion.Euler(0f, 0f, rotZ );

 }

```

Edit: I solved my previous question, but I want it to go anti clockwise after it reaches 0 degrees or when the gun faces right and clockwise again when it reaches 180 degrees or faces left.

this is my updated code -:

```
   void Update(){

   transform.Rotate(0, 0, -3.0f);

   }

```

# Answer
The following code is untested.

---

```
public class Turret {

[SerializeField] private float _minEulerRotation;
[SerializeField] private float _maxEulerRotation;

[SerializeField] private float _rotationAmount;

private CoolDown _coolDown;

void Start(){

    this._rotationAmount *= Time.fixedDeltaTime;

    this.StartCoroutine(this.RotationProcess());

}

private IEnumerator RotationProcess()
{
    while (true)
    {
        yield return this.StartCoroutine(this.RotateToMin());
        yield return this.StartCoroutine(this.RotateToMax());
    }
}

private IEnumerator RotateToMin()
{
    while(transform.rotation.eulerAngles."Axis you need" > this._minEulerRotation){

        transform.Rotate("Your vector3" * this._rotationAmount);

        if(this._coolDown.IsActive)
        {
            yield return this._coolDown.Delay;
        }

        yield return null;
    }

    transform.rotation = Quaternion.Euler("Your vector3" * this._minEulerRotation);
}

private IEnumerator RotateToMax()
{
    while(transform.rotation.eulerAngles."Axis you need" < this._maxEulerRotation){

        transform.Rotate("Your vector3" * this._rotationAmount);

        if(this._coolDown.IsActive)
        {
            yield return this._coolDown.Delay;
        }

        yield return null;
    }

    transform.rotation = Quaternion.Euler("Your vector3" * this._maxEulerRotation);
}

public void Shoot()
{
    ...... some cooldown stuff
    this._coolDown.StartCountdown();
}
}

```
> 1 votes

# Answer
You could do something like this:

```
private int direction = 1;

void Update(){
  if(transform.rotation.z == 0 || transform.rotation.z == 180){
    direction = -direction;
  }
  transform.Rotate(0,0,-3f*direction);
}

```

I didn't really understand what you meant when you said how you wanted the direction of rotation to switch, so you could just replace the clauses in the if-statement to fit whatever you need.
> 0 votes

---
Tags: unity
---


# Question
Title: How to play GameObject (ParticleSystem) and stop?
Have a game where you've to shoot somethings and when you hit the GameObject I've should play. I've tried with `Instantiate` but I can keep shooting even if the gameobject is destroyed. What should I do in order to fix it?

```
 public GameObject particlesystem;

 void Start () {
    particlesystem= GameObject.Find("Effect");
 }

 void Hit(){
 Destroy(gameobject)
 Instantiate(particlesystem, transform.position, transform.rotation);
 }

```

This is how I handle it now, but as I wrote earlier I can keep activating the particle system.

# Answer
> 1 votes
Particle System

Get your particle system in code and use public methods like `Play()` and `Stop()`.

Just as an example of use:

```
this._particleSystems[i].Play();
if (Time.time > 50) {
    this._particleSystems[i].Stop();
}

```

# Answer
> -1 votes
I think that the best way to do it is, instead of

```
particlesystem= GameObject.Find("Effect");

```

assign the prefab in the unity GUI (in the script field)

In addition, when you want to play the effect you should have to do it this way

```
var gO = Instantiate(particlesystem, transform.position, transform.rotation);
Destroy(gO, seconds);

```

I don't remember if var is a gameobject or an object type, but with var it should work.

Edit: if you have to destroy the game object (which are you shooting) call destroy(gameobject) too

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


# Question
Title: Coordinate transformation in voxel ray-tracing?
I am implementing voxelization. I can't understand the coordinate transformation through shader.

I have read some papers and code, the first step in the geometry shader is project the triangle along its dominant axis.

What's the difference between this method and using projection matrix?

In usual ways, we transform data from local space,world space, view space, then to projection space.

Does project the triangle means we transform from view space to projection space ?
What should we get after these process, in the end of pixel shader?

# Answer
I am just through implementing scene voxelization myself, and I am doing the dominant axis selection for a primitive like this in the geometry shader:

```
// First calculate the face normal
float3 facenormal = abs(normalize(input[0].normal + input[1].normal + input[2].normal));
// Then the dominant axis is the face normal's max component:
uint maxi = facenormal[1] > facenormal[0] ? 1 : 0;
maxi = facenormal[2] > facenormal[maxi] ? 2 : maxi;

for( uint i = 0; i < 3; ++i )
{
  // The position is in World space, transform to voxel space:
  output[i].pos = float4((input[i].pos.xyz - (float3)VoxelSceneCenterPos / (float)VoxelSceneScale, 1);

  // Projection matrix is unnecessary, just a swizzle is enough:
  if (maxi == 0)
  {
    output[i].pos.xyz = output[i].pos.zyx;
  }
  else if (maxi == 1)
  {
    output[i].pos.xyz = output[i].pos.xzy;
  }
  // And if the dominant axis is Z, then I do nothing because that is the default projection plane for me.

  // Then I just project the voxel space pos like this:
  output[i].pos.xy /= (float)VoxelSceneResolution;
  output[i].pos.zw = 1;
  // After this step, the output[i].pos is in clip space, the rasterization will take place on this value.
}

```

In my code, `input` is the three vertices from the vertex shader stage, `output` is the TriangleStream which the geometry shader emits (which is also three vertices).
`VoxelSceneCenterPos` is a uniform from a constant buffer which is the center of the voxelization (for example (0,0,0) vector).
`VoxelSceneScale` is a uniform from a constant buffer which is the size of a single voxel (default value is 1).
`VoxelSceneResolution` is a uniform from a constant buffer which is the resolution of the voxel grid (for example for a 256\*256\*256 grid this value is 256).

My main idea comes from this cool presentation by NVIDIA.

Good luck!
> 1 votes

# Answer
***Raycasting projection is fundamentally different** from regular triangle projection that is commonly used in most games today.* Forget what you know about vertex shader projection at this point.

There is no need for you to render polygons at all - meaning you typically don't have a vertex shader stage for this (it's what called *passthrough* vertex shader, i.e. it doesn't do much). That also means the vertex shader doesn't really manage any transformations via model, view and project matrices, in the usual OpenGL/DirectX sense. (See more on what the vertex shader *does* do, below.)

Each ray is oriented by the CPU or compute GPU (not the vertex shader), according to where the player is looking, with some offset such that each ray represents a pixel on the screen; "look direction" is the centremost ray/pixel of the screen, while all other rays have a slight angular offset from that:

Now we "cast" the rays through the world and find where they collide with obstacles, whereupon we read the colour and write it to the texture position assigned to this ray.

Finally, the texture containing these colours is rendered to a fullscreen, textured quad which is *the only thing* that your vertex shader will actually render - *you don't need to transform the whole world space*. Instead you have transformed every ray individually at an earlier stage in the pipeline!

So because we are using individual *rays* to read the world, we don't do the usual OpenGL thing of projection matrices to transform triangles. Instead each ray is multiplied by some matrix or modified in some other way, and is then fired into the world to retrieve the colour at its screen pixel.
> 1 votes

---
Tags: opengl, shaders, directx, voxels
---


# Question
Title: Does Microsoft prevent developers from using Vulkan?
So, I recently came across a source which stated that if you choose to use Direct3D 12 in your game, you have to sign a contract with Microsoft that prohibits you from using Vulkan in the future. It also said it prevents you from using *any other API* other than Direct3D 11 or 12.

Is this true?

# Answer
Definitely not.

There are two ways to see this assertion is false. First, consider that Direct3D 12 is part of the Windows SDK, which comes with a license agreement (it's generally located in the `License` subdirectory of the installation) that you must agree to before you can use the SDK. The Windows SDK is the *minimal* piece of Microsoft technology you need to use Direct3D 12, and the Windows SDK license says nothing about any other rendering APIs, nothing about exclusivity, and nothing about restrictions on using Vulkan. It's pretty clear that you can develop software using that SDK without encumbering yourself in any kind of restriction about rendering API choice.

Second, Windows is not a walled-garden platform. Agreement to the Windows SDK's license is the first and last legal interaction you can have with Microsoft when developing and shipping software for Windows platforms. There is no other point where they can assert legal leverage to mandate that you not use Vulkan.

So this claim is false.

---

It seems likely your "source" is either flat-out incorrect, or there is a misunderstanding between yourself and that source. It *is* theoretically possible that Microsoft, acting as a publisher for a game (and thus legally and *financially* engaged in a contract with a developer to produce that game) might mandate that a particular game use particular technology, such as D3D12, over other options... Permanently or for a period of exclusivity defined by the contract. Such deals are specific, though: they don't apply to everybody and as the publisher Microsoft would generally be *paying for* the right to make such a demand by virtue of the fact that they're funding the development of the game.
> 3 votes

# Answer
As hard as I try I can't find anything online giving this the slightest bit of credence and it just seems terribly unlikely, Microsoft does silly things all the time but they're not completly bereft of sense and I know Cryengine supports both DirectX 12 and Vulkan so at least one vendor can use both without being struck down.

This just sounds like the claim about Visual Studio Express having limitations all over again.
> 2 votes

---
Tags: directx, microsoft, vulkan
---


# Question
Title: Monitoring and storing chat logs in a 3D space
There are a lot of 3D games on the market with text chat functionality holding literally thousands of conversations happening at the same time.

Being in a 3D space is there a defacto method of monitoring and storing these?

The difficulty I can see is that not all text is visible to all participants at all times meaning a raw chat log wouldn't make any sense, with having so many conversations occurring in real time.

# Answer
> The difficulty I can see is that not all text is visible to all participants at all times meaning a raw chat log wouldn't make any sense, with having so many conversations occurring in real time.

True location-based chat, chat that only appears to users within a particular radius of some coordinate in 3D space is relatively uncommon.

Games typically have chats that are global (everybody can see them), map- or team-based, as well as private user-to-user conversations. None of these are constrained by physical location and anything that monitors or stores them just needs to know *which* map or team the entire chat stream is associated with. Similarly, user-to-user chats just need to log which participants are involved. Percentage-wise, you get more of that kind of chat than you do the true location-based stuff.

True location-scoped chat can simply store the world location with each message, if needed. It's not a lot of extra data, and there are ways one could in theory optimize the storage if it really became an issue.

Monitoring and logging that chat is then simply a matter of including an optional location query in whatever monitoring tools exist. There's no need for anything complicated.

In fact, chat forensics are usually more concerns with *what was said*, rather than *who heard it*, so in general being able to execute a query like "show me all the chat said between 9am and 11pm that could be heard at this location" is not a tool one reaches for all that often.
> 1 votes

---
Tags: community-management
---


# Question
Title: How to determine how far the background is behind a transparent object in a shader?
Is there a way to know how far away any object is behind a transparent object in a shader? Like making water fully transparent when close to shore.

# Answer
Yes, absolutely. The method is outlined in this presentation from Unity in 2011. (See the section "Soft Particles" on slide 22)

Some of the shader conventions have changed since then, but the core principles remain the same.

Add a `Sampler2D` to your shader called `_CameraDepthTexture` to read the depth buffer (if you're using deferred rendering, this is effectively free. In forward rendering, it may generate a separate depth-only pass in some situations/platforms where the depth buffer can't be directly sampled)

To sample it, work out the position of the current fragment being drawn to the screen (using VPOS is probably the simplest way if you're using Shader Model 3.0 or higher \- see this answer for an example \- otherwise you can pass your projected position from the vertex shader and divide by w in the fragment shader)... and then convert that to a uv coordinate in the range 0-1.

Then use this `screenUV` to sample your depth buffer using, eg.

```
float backgroundDepth =
         LinearEyeDepth(
           UNITY_SAMPLE_DEPTH(
             tex2D(_CameraDepthTexture, screenUV)
         ));

```

All those wrappers are Unity macros/built-in methods to help decode the depth from whatever format Unity is using on the current platform, and get it into worldspace units.

Now you can compare this to the worldspace depth of your fragment (interpolated from each vertex) to get your blending factor.
> 2 votes

# Answer
You need rendered depth buffer for this to work. First you would get the current fragment depth, and then read the depth buffer value on that fragment and then calculate the transparency value for the fragment based on the difference of the two depth values. Check documentation for the depth buffer.
> 1 votes

---
Tags: unity, shaders, depth-buffer
---


# Question
Title: How to animate a MeshRenderer color in Unity 3D?
I need to animate MeshRenderer.material.color.a, but fail.

Code:

```
    private void Method()
{
    AnimationClip clip = new AnimationClip();
    AnimationClipPlayable playable = AnimationClipPlayable.Create(clip);

    AnimationCurve alpha = AnimationCurve.Linear(0, 1, 1, 0);
    clip.SetCurve("", typeof(MeshRenderer), "Material._Color.a", alpha);

    //gameObject.GetComponent<MeshRenderer>().material.SetColor("_Color", Color.red); // Works
    gameObject.GetComponent<Animator>().Play(playable); // Doesn't work
}

```

# Answer
> 4 votes
I tried this using Unity 5.5.0f3, and the path for material alpha was the only problem. It should be "material.\_Color.a" (lower-case m). Otherwise, your code worked exactly as you wrote it.

I figured this out by creating an animation within the Unity editor, then examining the new .anim file in a text editor. I do this pretty often (read assets in a text editor) to find problems or to search for things for which Unity does not have a built-in tool. It's quite useful, and only requires that your project is set to save all assets as text.

---
Tags: unity
---


# Question
Title: How to make character respawn the position needed in Andengine?
I want to make my character respawn in the last Checkpoint he has reached. I've already stored the position of the checkpoint but I'm not very sure of how to set that position to the Sprite/Body of the character to make it appear in the position I want to. Do I have to use the Sprite or the Body? Here's how I initialize my character:

```
    mPlayerSprite = new AnimatedSprite(mapOffset, 0, playerTexture);

    final FixtureDef mPlayerFixtureDef = PhysicsFactory.createFixtureDef(0, 0f, 0f, false, CATEGORYBIT_PLAYER, MASKBITS_PLAYER, (short) 0);
    mPlayerBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, mPlayerSprite, BodyType.DynamicBody, mPlayerFixtureDef);

    mPlayerSprite.setUserData(playerName);
    mPlayerBody.setUserData(playerName);
    this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mPlayerSprite, mPlayerBody, true, false));

    mScene.attachChild(mPlayerSprite);
    mEntityList.add(mPlayerSprite);

```

Thanks in advance!

# Answer
If you use body, then 'sprite.setPosition(..)' does not work. You should 'body.setTransform()'

```
float PMR = PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
mPlayerBody.setTransform(checkPointImage.getX() / PMR, checkPointImage.getY() / PMR);

```
> 1 votes

---
Tags: andengine
---


# Question
Title: Mouse Input Unexplained Behavior Unity3D
`Input.GetMouseButtonDown(0.....6);` \- in documentation it says that you can pass, 0, 1, 2 as parameter. Input.GetMouseButtonDown. It doesn't accept negative numbers like -1 or numbers 7+. What does 3 4 5 6 do? What input are they calculating? Or can I use these numbers as default for None state? I couldn't find any information about this.

# Answer
> 2 votes
0 is the left mouse button, 1 is the right ,2 is the middle. The rest are there for mice with extra buttons. Like some gaming mice have buttons on the side. For example using this code :

```
void Update () {
        if(Input.GetMouseButton(3))
        {
            Debug.Log(true);
        }
    }

```

and pressing my 4th mouse button I get true in the console.

---
Tags: unity, input
---


# Question
Title: Float inaccuracy. libgdx only? java only? also why?
Hey all I have just come to notice that floats are not accurate even when they are explicitly set and unchanged. For example i have some basic code running and it is:

```
 if (bike.getY() < previousBikeY){
        bike.accelY = 50f;

        System.out.println("bike accel Y :" + bike.accelY);
    }

```

The result in the log is:

I/System.out: accelY: 49.770126

If I wanted 49.77 id have set 49.77, this also makes me wonder about all the other uses of float i have (such as position, speed, gravity, time, etc).

A) Does this happen in other languages such as C++ or C#? B) is this normal and something i should ignore OR do I need to take action?

# Answer
> 1 votes
IMO this is a general programming question and is therefore out of place here. However;

A.) Yes, this happens in all programming languages to varying degrees (well, at least the ones I have worked with, those being Java, and C# (not sure about lua or javascript)).

B.) This is very normal and the reason is discussed here. Whether you should take special considerations depends on what you are doing and the degree of accuracy you need to maintain. If you are getting floating point precision issues in comparisons (that is, `(50f == 49.770126)` == false) you can do the following:

```
float eps = 0.000001;
if((val - comparedTo) < eps)
    System.out.println("We have a match!");

```

Where `eps` is the decimal precision you need you comparison to check.

# Answer
> 1 votes
**To answer strictly to your question, no it does not happens on other languages.**

While it is true that floating point cannot represent all numbers, **small whole numbers should be represented correctly**. Infact if you try the following floating point converter with "50.0f" value, you will se "50".

https://www.h-schmidt.net/FloatConverter/IEEE754.html

To me it looks like that variable was not simply assigned, but underwent some additional processing (likely to be some transformation matrix or something similiar).

The quickest way to check that is to do some extra tests (also to remove the chance the bug is actually only in the visualization of the debug log).

try the following

```
bike.accelY = 50f;
if((bike.accelY +1f)  == 51f)
     System.out.println("Value was 50 and just displayed wrongly");
else
     System.out.println("Value went under further processing");

```

If the value is processed I would be surprised, because Java (as far as I know) does not have properties (like C#, or do they added properties?)

---
Tags: java, libgdx, lwjgl, floating-point
---


title: Stretch line on bow using touch

text:
# Question
Title: Stretch line on bow using touch
I have drawn a line on sprite representing the string of a bow. I want to stretch it with finger touch input, using `onTouch`. I have added a Physics body but I don't understand how to stretch the line.

It's a bow and arrow demo:

Here is the code I use:

```
protected Scene onCreateScene() {
        this.mEngine.registerUpdateHandler(new FPSLogger());
        mScene = new Scene();
        mScene.setBackground(new Background(0.3f, 0.8f, 0.9f));
        float centerX = CAMERA_WIDTH/2;
        float centerY = CAMERA_HEIGHT/2;

        Sprite sprite = new Sprite(centerX,centerY,this.regionBow, this.getVertexBufferObjectManager());
        mScene.attachChild(sprite);

        PhysicsWorld physicsWorld = new PhysicsWorld(new Vector2(0, 300), false);
        Line line = new Line(99, 10, 99, 240, 4, getVertexBufferObjectManager());
        line.setColor(0f,0f,0f);

        FixtureDef lineFixtureDef = PhysicsFactory.createFixtureDef(1, 4f, 0.5f);
        Body body = PhysicsFactory.createLineBody(physicsWorld, line, lineFixtureDef);
        mScene.getLastChild().attachChild(line);

        PhysicsConnector physicsConnector = new PhysicsConnector(sprite, body, true, true);
        physicsWorld.registerPhysicsConnector(physicsConnector);

        mScene.setOnAreaTouchListener(new IOnAreaTouchListener() {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea, float pTouchAreaLocalX, float pTouchAreaLocalY) {
                return false;
            }
        });

        return this.mScene;
    }

```

# Answer
Maybe you can not use physics. Something like this;

```
float[] bowLeftUpCornerPos =... // add Bow left-up corner positions.
float[] bowLeftDownCornerPos=... // add Bow left-down corner positions.
float[] bowLeftCenterPos=... // add Bow left center positions.

Line lineUp = new Line(bowLeftCenterPos[0], bowLeftCenterPos[1],
bowLeftUpCornerPos[0] , bowLeftUpCornerPos[1], 4, getVertexBufferObjectManager());

Line lineDown = new Line(bowLeftCenterPos[0], bowLeftCenterPos[1],
bowLeftDownCornerPos[0], bowLeftDownCornerPos[1], 4, getVertexBufferObjectManager());
.
.

@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,     ITouchArea pTouchArea, float pTouchAreaLocalX, float pTouchAreaLocalY) {

    float pX = pSceneTouchEvent.getX();
    float pY = pSceneTouchEvent.getY();

    if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) {
       lineUp.setPosition(pX,pY,bowLeftUpCornerPos[0],bowLeftUpCornerPos[1]);
       lineDown.setPosition(pX,pY,bowLeftDownCornerPos[0],bowLeftUpCornerPos[1]);
    }

    if (pSceneTouchEvent.isActionUp()) {
       lineUp.setPosition(bowLeftCenterPos[0], bowLeftCenterPos[1],bowLeftUpCornerPos[0],bowLeftUpCornerPos[1]);
       lineDown.setPosition(bowLeftCenterPos[0], bowLeftCenterPos[1],bowLeftDownCornerPos[0],bowLeftUpCornerPos[1]);
    }

return false;
}

```
> 0 votes

---
Tags: 2d, physics, sprites, andengine
---


# Question
Title: Libgdx Android app: Avoid fullscreen and show titlebar
I am developing an app using Libgdx and I don't want the app to go fullscreen and want to show the title bar but the app goes to fullscreen and hides title bar despite all efforts.

Here is my `style.xml` file

```
<style name="MyStyle" parent="android:Theme.Light"></style>

```

---

Here is `AndroidManifest.xml`

```
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyStyle" >
    <activity
        android:name="com.mygdx.game.android.AndroidLauncher1"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

```

---

Here is `AndroidLauncher` class

```
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    config.hideStatusBar=false;
    initialize(new MyGdxGame(), config);
    setContentView(R.layout.main_activity);
    tv=(TextView)findViewById(R.id.tv);
    tv1=(TextView)findViewById(R.id.tv1);
    button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Build.VERSION.SDK_INT < 19) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
            }
            else{
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
            }
        }
    });

}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            Intent act2 = new Intent(this ,AndriodLauncher2.class);
            act2.setData(selectedImageUri);
            startActivity(act2);
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

```

# Answer
> 2 votes
I know this question is old but to make this work here's what I did. Based on this link: http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=12668 provided by @weirdelfb0y

1. In your **AndroidLauncher.java** replace the "initialize(new YourGame(), config);" line with:

RelativeLayout layout = new RelativeLayout(this);

layout.addView(initializeForView(new YourGame(this), config));

setContentView(layout);
2. In your **res/values/styles.xml** make sure you have the "**android:windowFullscreen**" set to **false** and the "**android:windowNoTitle**" set to **true**.

That's it!

# Answer
> 0 votes
LibGDX might override this but try adding this to your style

```
<item name="android:windowNoTitle">false</item>
<item name="android:windowFullscreen">false</item>

```

# Answer
> 0 votes
Have you tried:

```
public class MainActivity extends AndroidApplication {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RelativeLayout layout = new RelativeLayout(this);
        layout.addView(initializeForView(new MainClass(), false));
        setContentView(layout);
    }
}

```

---
Tags: android, libgdx
---


# Question
Title: Is it legal to copy stats and abilities of characters from another game?
Is it legal to copy stats and abilities of characters from another game?.Please note that my game does have a similar gameplay to the game I am copying. My characters will look different of course.

# Answer
*I am not a lawyer* so keep in mind that *what I will write is just what I remember* from different articles I've read before.

**In short:** If you copy only the gameplay part (stat and way of playing) and nothing else, then it should be ok (I repeat double check that. I am not a lawyer)

**More details:** If I remember well, in the law point of view, video games are not considered as a whole, but as many parts (music, design, art, animation, etc.) and each part is protected by its own law. The only thing that cannot be copyrighted is the gameplay which include abilities and stats. That's why there is a lot of game being part of the same style of gameplay without problem. But keep in mind that many other details can be protected. For example I think that the name of the ability and the animation when using it can be copyrighted.

Hope it will help you but wait for the answer of someone who truly know the law because I am just repeating things I've heard.
> 2 votes

---
Tags: copyright
---


# Question
Title: How do I disable fog on specific camera/s
I'm building an FPS with fog and I want to include a dynamic minimap, showing the locations of player and enemies in real time.
This is utilized by a second camera which is orthographic and looks at the scene from above.

In the minimap, I don't want to see the fog of course. I've hidden other things from the minimap by using layers and culling masks, however the fog does not belong into any specific layer.

So, how do I disable the fog on just one (or some) camera?

# Answer
The way to solve this is by disabling the global fog just before the rendering process of the camera and re-enable it immediately afterwards.

**TL;DR - attach the following script to the camera you wish to exclude from the fog**

```
using UnityEngine;

public class NoFog : MonoBehaviour {

    bool doWeHaveFogInScene;

    private void Start() {
        doWeHaveFogInScene = RenderSettings.fog;
    }

    private void OnPreRender() {
        RenderSettings.fog = false;
    }
    private void OnPostRender() {
        RenderSettings.fog = doWeHaveFogInScene;
    }
}

```
> 4 votes

---
Tags: unity, camera, fog
---


# Question
Title: Flare (particle system) showing weird semi-transparent rectangles instead of smoke when there's fog in the scene
I'm making an FPS game with some fog in the scene.

I've added a flare particle system (from the standard assets' prefabs) but it looks like it has some weird collision with the fog.

Whenever the fog is enabled I get these weird rectangles on top of the flare like in this screenshot:

I've noticed that when I turn off the fog they disappear, also I've noticed that when I turn off the *Emission* part of the particle system the rectangles disappear, but of course, also most of the wanted effect is gone.

# Answer
> 0 votes
**It appears that the standard asset of "ParticleFlare" was causing the problems!**

Maybe the black texture around it is not 100% black or it has some transparency. I'm not sure exactly, but it's definitely the culprit.

When I changed the texture on the shader component to (mostly) anything else - the glitch was gone!

Here is where you set it:

(I chose a texture called "VignetteMask" which worked for me, just had to make the particles size a bit smaller)

And this is the result:

---
Tags: unity, rendering, particles, fog
---


title: GUI rendered into texture(s) or not?

text:
# Question
Title: GUI rendered into texture(s) or not?
I am eyeing OpenVG and cairo as rendering libraries for my pet game GUI. You can use both to render either into a texture or issue GL commands to draw directly onto the display. If I would use them directly, there are the following issues:

* they will mess with GL state, which can be a problem, if it happens every frame,
* their code will be executed every frame, if the GUI is drawn directly, but the GUI textures would be updated only when game state changes.

For this reasons I think I should be rendering the GUI into texture(s), but I'm asking here just to be sure.

# Answer
They have their benefits and drawbacks so you may want to try both to see if performance matters. I was initially going to render everything in but the performance for me on PC platform does not seem to matter.

Keep in mind there is a third option though, you can render your GUI into images within the image itself. So you would draw all the text into the GUI elements when you load up the game. That way you get the flexibility and multilanguage potential without the performance drawback.

To start out I would avoid rendering into the textures, then if you need it either do that or choose the third option.
> 1 votes

# Answer
A GUI framework should behave efficiently when nothing changes between frames. You can render-to-texture as one way to achieve this, but there are others, like state caching, or keeping the generated rendering commands from the last frame.

The concern about the GUI "messing" with GL state is not really relevant. The state must be restored correctly, no matter how often it is changed, and toggling depth writes and culling is not a performance killer. Switching shaders has some performance impact, but a GUI should use a single shader, so this should be manageable.

The case where I think render-to-texture is justified is where a GUI draw might be expected to take longer than your normal frame budget. In that case, for several frames, you switch into GL GUI state, render a pass to a texture, and switch out of GL GUI state, only showing the result to the user when the expensive draw is complete.
> 1 votes

---
Tags: opengl, opengl-es, gui
---


# Question
Title: Determining Rectangle-Circle Collision Point
I'm developing a 2D game engine currently. I stuck on determining position of a rectangle that collides with a circle when its speed is added to its position. Rectangles have only x axis speed.

On picture rectangles are same. Left sided rectangles x,y,width and height values are known. Second rectangle should be next position. Circles radius, x and y values are known also. (x and y values are top left position of an object). I need to find second position of rectangle.

Edit: I can detect collision perfectly. But I need its new position.

# Answer
Because y doesn't change and the rectangle is axis aligned we have 3 cases:

* The center of the circle is below the rectangle
* The center of the circle is aligned with the rectangle
* The center of the circle is above the rectangle.

For each case you first need to check whether the rectangle collides with the circle or not. You should create a bounding box from the last and current place of the rectangle and check if the circle collides with this rectangle to avoid fake negatives when the rectangle goes too fast. Here's an image to make it clearer:

Here ABC'D' is the bounding box.

After you're certain there's a collision, you need to check which above case it belongs to. If the bottom of the rectangle is above the center, then the first, if the top is above but the bottom is below, then it's the second case, and if the top is below the center, then it's the third.

If it's the first or the third case and the rectangle goes right (it has a positive velocity), then you need to set the center's x coordinate based on the algorithm:

```
newCenterX = circleCenterX - sqrt(r * r - pow(centerY - circleCenterY, 2)) - width / 2

```

where `r` is the radius of the circle.

If the rectangle is goes left (it has a negative x velocity), then the new center's x coordinate is

```
newCenterX = circleCenterX + sqrt(r * r - pow (centerY - circleCenterY, 2)) + width / 2

```

If it's the second case and the rectangle goes right, then the new center x is

```
newCenterX = circleCenterX - r - width / 2

```

And if it goes to left, the new x is

```
newCenterX = circleCenterX + r + width / 2

```
> 2 votes

---
Tags: collision-detection, physics, geometry
---


title: sfml drawing text c++

text:
# Question
Title: sfml drawing text c++
using visual studio 2015 and SFML . relevant code:

```
sf::Font font;
font.loadFromFile("Arial.ttf");
sf::Text text;
text.setFont(font);
text.setString("hello ");
_mainWindow.draw(text);

```

It doesn't display the text. I put a breakpoint, the font gets the correct value. but the **text's string stays empty. for the main window I get:** \+ \_mainWindow sf::RenderWindow

Can anybody help?

thanks

# Answer
> 1 votes
If your font goes out of scope, the text will not be able to display. SFML fonts need to stay for the scope of the text that uses them. (I can't tell very much because I don't have surrounding code, however).

# Answer
> -1 votes
Are you calling \_mainWindow.clear(); before \_mainWindow.draw() and \_mainWindow.display(); after it ?

---
Tags: c++, sfml, visual-studio
---