# Question
Title: DirectX 11 Compute Shader error DXGI_ERROR_DEVICE_HUNG
I am trying to use a compute shader for ray picking technology. My shader accepts:

1. vertex buffer of all models
2. index buffer of all models
3. a buffer of transformation matrices of all models
4. Offset buffer for specific models.

And returns a single buffer of the size of one element, storing two variables of type int.

With a small number of models, the shader works fine(\<500 transformation matrices), but with a large number of models (model: 3000 vertices, 10,000 indices, 1600 transformation matrices), the computational shader freezes and reports an error: *DXGI\_ERROR\_DEVICE\_HUNG*

Here is the shader code with comments:

```
struct Point
{
    float3 pos;
};

struct Word
{
    int index;
};

struct Transformation
{
    matrix pos;
    matrix rot;
    matrix sca;
};

struct Offset
{
    uint countVertexAllPred;
    uint countVertex;
    uint countIndecedsAllPred;
    uint countIndeceds;
    uint countTransformations;
};

StructuredBuffer<Point> arrayPoints: register(t0); // buffer vertex
StructuredBuffer<Word> arrayIndeceds: register(t1); // buffer index
StructuredBuffer<Transformation> arrayTransformations: register(t2); // buffer transform
StructuredBuffer<Offset> arrayOffsets: register(t3); // buffer offsets

struct DataOutput
{
    int indexModel;
    int indexTransformation;
};

RWStructuredBuffer<DataOutput> outputBuffer: register(u0);

cbuffer CommonData: register(b0)
{
    float4 cameraPosition;
    float4 rayPosition;
    float4 rayDirection;
    float4 countModel;
};

interface TriangleMethods
{
    void createEmpty();
    bool isEmpty();
    void newTriangle(float3 x, float3 y, float3 z);
    float3 getCenter();
};

class Triangle: TriangleMethods
{
    float3 a;
    float3 b;
    float3 c;
    float3 o;

    void createEmpty()
    {
        a = b = c = o = 0;
    }

    bool isEmpty()
    {
        float _a = a.x + a.y + a.z;
        float _b = b.x + b.y + b.z;
        float _c = c.x + c.y + c.z;
        return (_a == 0 && _b == 0 && _c == 0);
    }

    void newTriangle(float3 x, float3 y, float3 z)
    {
        a = x; b = y; c = z;
        float _x = (a.x + b.x + c.x) / 3;
        float _y = (a.y + b.y + c.y) / 3;
        float _z = (a.z + b.z + c.z) / 3;
        o = float3( _x, _y, _z );
    }

    float3 getCenter()
    {
        return o;
    }
};

bool equalsSFromCamera(Triangle t1, Triangle t2)
{
    bool result = true;
    float length1 = length(t1.getCenter() - (float3)cameraPosition);
    float length2 = length(t2.getCenter() - (float3)cameraPosition);
    if(length1 < length2)
        result = false;
    return result;
}

float3 generateNormal(float3 a, float3 b, float3 c)
{
    float3 u = b - a;
    float3 v = c - a;
    float3 p = normalize(cross(u, v));
    return p;
}

float intersectionRayAndPlane(float3 p, float3 normal)
{
    return -dot((float3)rayPosition - p, normal) / dot((float3)rayDirection, normal);
}

bool belongsPointInTriangle(float3 a, float3 b, float3 c, float3 m, float3 n)
{
    bool result = false;
    float3 tmp;

    float3 oa = a - m;
    float3 ob = b - m;
    tmp = dot(n, cross(oa, ob));
    float v1 = tmp.x;

    float3 oc = c - m;
    tmp = dot(n, cross(ob, oc));
    float v2 = tmp.x;

    tmp = dot(n, cross(oc, oa));
    float v3 = tmp.x;

    if ((v1 < 0 && v2 < 0 && v3 < 0) || (v1 >= 0 && v2 >= 0 && v3 >= 0))
        result = true;
    return result;
}

Triangle getNearTriangleFromCamera(Triangle t1, Triangle t2)
{
    Triangle t = t2;
    float length1 = length(t1.getCenter() - (float3)cameraPosition);
    float length2 = length(t2.getCenter() - (float3)cameraPosition);
    if(length1 < length2)
        t = t1;
    return t;
}

[numthreads(1, 1, 1)]
void main(uint3 groupThreadID : SV_GroupThreadID)
{
    Triangle tri;
    tri.createEmpty();
    DataOutput dataTriangle;
    dataTriangle.indexModel = -1;
    dataTriangle.indexTransformation = -1;
    int indexModel = -1;
    int indexModelMatrix = -1;

    int offTrans = 0;

    for(int k = 0; k <countModel.x;k++) // select every model
    {
        indexModel++;
        int start = arrayOffsets[k].countIndecedsAllPred; // select offset for current model
        int end = arrayOffsets[k].countIndeceds;
        for(int i = start;i<end;i+=3)  // select indexs current model
        {

            int i1 = (int)arrayIndeceds[i].index;
            int i2 = (int)arrayIndeceds[i+1].index;
            int i3 = (int)arrayIndeceds[i+2].index;

            // select vertex current model with gets index
            float3 p0_source = arrayPoints[i1].pos;
            float3 p1_source = arrayPoints[i2].pos;
            float3 p2_source = arrayPoints[i3].pos;

            // get count transformation for current model
            int countTransf = (int)arrayOffsets[k].countTransformations;
            for(int j = 0;j<countTransf;j++) // select transformation for current model
            {
                indexModelMatrix++;

                // mul three vertex on current matrix transformation
                float3 p0 = p0_source;
                float3 p1 = p1_source;
                float3 p2 = p2_source;

                matrix _pos = arrayTransformations[offTrans + j].pos;
                matrix _rot = arrayTransformations[offTrans + j].rot;
                matrix _sca = arrayTransformations[offTrans + j].sca;

                p0 = (float3)mul(float4(p0, 1), _sca);
                p0 = (float3)mul(float4(p0, 1), _rot);
                p0 = (float3)mul(float4(p0, 1), _pos);

                p1 = (float3)mul(float4(p1, 1), _sca);
                p1 = (float3)mul(float4(p1, 1), _rot);
                p1 = (float3)mul(float4(p1, 1), _pos);

                p2 = (float3)mul(float4(p2, 1), _sca);
                p2 = (float3)mul(float4(p2, 1), _rot);
                p2 = (float3)mul(float4(p2, 1), _pos);

               // generate normal
                float3 n = generateNormal(p0, p1, p2);

                // check ray and plane intersection
                float t = intersectionRayAndPlane(p0, n);

                // get point for ray and plane intersection
                float3 m = (float3)rayPosition + (float3)mul(t, (float3)rayDirection);

                // check ray and triangle intersection
                if(belongsPointInTriangle(p0, p1, p2, m, n))
                {
                    Triangle triangleNew;
                    triangleNew.newTriangle(p0, p1, p2);
                    triangleNew = getNearTriangleFromCamera(tri, triangleNew);
                    // ray hit the triangle
                    if(tri.isEmpty() || !equalsSFromCamera(tri, triangleNew))
                    {
                    // replace model indexes and transformation matrices
                        dataTriangle.indexModel = indexModel;
                        dataTriangle.indexTransformation = indexModelMatrix;
                        tri = triangleNew;
                    }
                }
            }
            indexModelMatrix = -1;
        }
        offTrans += (int)arrayOffsets[k].countTransformations;
    }

    outputBuffer[0].indexModel = dataTriangle.indexModel;
    outputBuffer[0].indexTransformation = dataTriangle.indexTransformation;

}

```

Here is the call to the compute shader in C ++ code:

```
DataOutput RayPick::run(ID3D11Device* device, ID3D11DeviceContext * deviceContext)
{
    ID3D11UnorderedAccessView* nullOutBuffer(nullptr);
    ID3D11ShaderResourceView* nullResourceBuffer(nullptr);
    ID3D11Buffer* nullConstantBuffer(nullptr);

    // output buffer
    DataOutput out; out.indexModel = out.indexTransformation = -1;

    deviceContext->CSSetShader(shader, NULL, 0);
    deviceContext->CSSetConstantBuffers(0, 1, &constantBufferData);
    deviceContext->UpdateSubresource(constantBufferData, 0, NULL, &BufferData, 0, 0);
    deviceContext->CSSetShaderResources(0, 1, &physicShaderResourceViewPoints);
    deviceContext->CSSetShaderResources(1, 1, &physicShaderResourceViewIndeceds);
    deviceContext->CSSetShaderResources(2, 1, &physicShaderResourceViewTransformation);
    deviceContext->CSSetShaderResources(3, 1, &physicShaderResourceViewOffsets);
    deviceContext->CSSetUnorderedAccessViews(0, 1, &physicShaderResourceViewOut, NULL);

    deviceContext->Dispatch(1, 1, 1);

    deviceContext->CSSetUnorderedAccessViews(0, 1, &nullOutBuffer, NULL);
    deviceContext->CSSetConstantBuffers(0, 1, &nullConstantBuffer);
    deviceContext->CSSetShaderResources(0, 1, &nullResourceBuffer);
    deviceContext->CSSetShaderResources(1, 1, &nullResourceBuffer);
    deviceContext->CSSetShaderResources(2, 1, &nullResourceBuffer);
    deviceContext->CSSetShaderResources(3, 1, &nullResourceBuffer);
    deviceContext->CSSetShader(NULL, NULL, 0);

    // get output buffer data
    deviceContext->CopyResource(outBuffer, physicBufferOut);
    D3D11_MAPPED_SUBRESOURCE mappedData;
    ZeroMemory(&mappedData, 0, sizeof(mappedData));
    HRESULT hr = deviceContext->Map(outBuffer, 0, D3D11_MAP_READ, 0, &mappedData);

    hr = device->GetDeviceRemovedReason();
    string message;
    switch (hr)
    {
    case DXGI_ERROR_DEVICE_HUNG:
        message = "DXGI_ERROR_DEVICE_HUNG"; // bug!
        break;

    case DXGI_ERROR_DEVICE_REMOVED:
        message = "DXGI_ERROR_DEVICE_REMOVED";
        break;

    case DXGI_ERROR_DEVICE_RESET:
        message = "DXGI_ERROR_DEVICE_RESET";
        break;

    case DXGI_ERROR_DRIVER_INTERNAL_ERROR:
        message = "DXGI_ERROR_DRIVER_INTERNAL_ERROR";
        break;

    case DXGI_ERROR_INVALID_CALL:
        message = "DXGI_ERROR_INVALID_CALL";
        break;

    case S_OK:
        message = "S_OK";
        break;

    default:
        message = "error";
        break;
    }

    if (hr != S_OK)
    {
        return out;
    }
    DataOutput* dataPtr = reinterpret_cast<DataOutput*>(mappedData.pData);
    out = *dataPtr;
    deviceContext->Unmap(outBuffer, 0);

    return out;
}

```

Create out and copy buffers:

```
// buffer for copy data
D3D11_BUFFER_DESC outputDesc;
outputDesc.Usage = D3D11_USAGE_STAGING;
outputDesc.BindFlags = 0;
outputDesc.ByteWidth = sizeof(DataOutput);
outputDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
outputDesc.StructureByteStride = sizeof(DataOutput);
outputDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
HRESULT hr = device->CreateBuffer(&outputDesc, 0, &outBuffer);
if (hr != S_OK)
    return false;

// create rw structured buffer
D3D11_BUFFER_DESC descGPUBuffer;
ZeroMemory(&descGPUBuffer, sizeof(descGPUBuffer));
descGPUBuffer.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE;
descGPUBuffer.ByteWidth = sizeof(DataOutput);
descGPUBuffer.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
descGPUBuffer.StructureByteStride = sizeof(DataOutput);
hr = device->CreateBuffer(&descGPUBuffer, NULL, &physicBufferOut);
if(hr != S_OK)
    return false;

// create rw structured buffer UAV
D3D11_BUFFER_DESC descBuf;
ZeroMemory(&descBuf, sizeof(descBuf));
physicBufferOut->GetDesc(&descBuf);
D3D11_UNORDERED_ACCESS_VIEW_DESC descView;
ZeroMemory(&descView, sizeof(descView));
descView.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
descView.Buffer.FirstElement = 0;
descView.Format = DXGI_FORMAT_UNKNOWN;
descView.Buffer.NumElements = 1;
hr = device->CreateUnorderedAccessView(physicBufferOut, &descView, &physicShaderResourceViewOut);
if(hr != S_OK)
    return false;

```

An error occurs at this location:

```
HRESULT hr = deviceContext->Map(outBuffer, 0, D3D11_MAP_READ, 0, &mappedData);

```

And the debug layer also reports the following message: *Removing device*

While the shader is called with one group of threads and one thread (1,1,1). How to understand why this error occurs? Thank.

PS: Sorry for my bad english:(

# Answer
This is called a Timeout Detection and Recovery (TDR) error which by default happens whenever the GPU stops responding for 2 seconds or longer--technically when a single driver packet takes longer than 2 seconds. For normal rendering, this is plenty of time for most shaders but long-running DirectCompute tasks can tie up the GPU for longer than 2 seconds.

One solution is to break up the work into smaller batches so the system stays more responsive, and general this is a good solution. You should also make sure your shader is as optimized as it can be for the workloads.

On DirectX 11.1 or later (Windows 7 SP 1 with KB 2670838, Windows 8.x, or Windows 10), you can use `D3D11_CREATE_DEVICE_DISABLE_GPU_TIMEOUT` when creating the device.

See Microsoft Docs
> 2 votes

---
Tags: c++, shaders, directx11, hlsl, compute-shader
---


# Question
Title: Howto apply alpha value (Color) to a sprite in libgdx
Howto apply alpha to a sprite so it will work.

With the following code, the sprite still is completely visible.

Can someone help me ?

```
batch.enableBlending();
if (sprite != null) {
    Color c = sprite.getColor();
        c.a = 0;
        sprite.setColor(c);
}
batch.draw(sprite, x, y);
sprite.setAlpha(0f);

```

# Answer
You're drawing the sprite the wrong way:

```
Gdx.gl.glClearColor(0, 0, 0, 1); // Clear the screen with black
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear the screen

batch.enableBlending(); // Enable alpha
batch.begin();

sprite.setAlpha(0);
sprite.draw(batch); // This is how you should draw a sprite.

batch.end();
batch.disableBlending();

```

This works fine for me.
> 2 votes

---
Tags: libgdx, alpha-blending
---


# Question
Title: Design constraints for games that the elderly (65+) get engaged with
I'm a newbie in game design and gaming in general (Tetris, board games, this sort of things). But have observed that the elderly got very much engaged with bubble shooter and solitaires (quite different approaches). I've tried to look for something similar, and have tried to initiate some in these games, but nope, the shooter is always preferred.

Does anybody know of general criteria, design constraints, or (even better) concrete examples of games that the elderly like to play, apart from these two?

Note: agreed, not correctly tagged, but can't find something that fit, nor can I propose new ones.

# Answer
The games you've stated are very simple in design, and are extremely easy to "win". Some people might argue they can be complex (ie. chaining properly in *Tetris* and Bubble Shooter), but at the end of the day, it is their simplicity and low entry levels of difficulty.

Following the examples you've stated:

* *Tetris* has you rotating blocks that fall down the screen to create lines. They fall slow enough at Level 1; there is ample time to think before it reaches the bottom.
* Bubble Shooters have you shoot balls to create groups of a color to clear them; it is easy for the same reasons as Tetris.
* Solitaire has you drag cards until they follow a certain set of rules. The controls are really simple (just drag and drop), but the ability to know what moves to take on the other hand, may not be as simple.
* Pokémon Go (a more recent example) has you walk around\*, tap on monsters and then throw (swipe) balls at them. It is both easy and simple.

* the elderly may find this difficult to do often and for long periods of time as required by the game.

It's also worth noting that both *Tetris* and a Bubble Shooter are not board games, per say.

---

Unlike younger people, who are open to learning, can discover patterns easily and are open to more complex gameplay ideas, or things that would have need us to actively think and be aware (ie. spatial awareness in shooters), the elderly may have difficulty grasping such concepts maybe because:

* They don't have the mindset or experience that most of us younger, modern gamers have.
* Their mental capacity/reflexes aren't as high (or fast) as, for example: a teenager, or an adult around the age of 40.

And with anything, there are of course some people that are exceptions to the above.
> 3 votes

# Answer
We don't have to speculate, people have studied this topic.

*What Older People Like to Play: Genre Preferences and Acceptance of Casual Games* mentions that older players prefer casual video games, and specifically identifies **casual puzzle games** as the subgenre most preferred.

> Results
>
> Overall, enjoyment and acceptance of casual game characteristics was high and significantly above the midpoint of the rating scale for all CVG \[Casual Video Games\] genres. Mixed model analyses revealed that ratings of enjoyment and casual game characteristics were significantly influenced by CVG genre. Participants’ mean enjoyment of **casual puzzle games** (mean 0.95 out of 1.00) was significantly higher than that for casual simulation games (mean 0.75 and 0.73). For casual game characteristics, casual puzzle and simulation games were given significantly higher game-play ratings than casual action games. Similarly, participants’ control ratings for casual puzzle games were significantly higher than that for casual action and simulation games. Finally, ownership was rated significantly higher for casual puzzle and strategy games than for casual action games.

*Beyond the “core-gamer”: Genre preferences and gratifications in computer games* goes even further, and correlates genre preferences with age as well as gratifications (i.e. "what I like in games"). A few relevant correlations from the result tables:

* Older people like games less overall, except for the "**competence**" ("to improve their skill") gratification which is about the same across ages. They are least interested in **fantasy** (role-playing, escapism) and **teamplay** (co-op multiplayer)
* Of all the genres, **puzzle** is the only one they like more than other age groups. They like **platformers**, **action** and **music** games the least
* For puzzle games, the gratifications they are most correlated with are **competence** and **narration** (topic and story)
> 3 votes

---
Tags: game-design, board-game
---


# Question
Title: What does the Sys_PageIn() function do in Quake?
I've noticed in the initialization process of the original Quake the following function is called.

```
volatile int sys_checksum;

//  **lots of code**

void Sys_PageIn(void *ptr, int size)
{
    byte *x;
    int j,m,n;
//touch all memory to make sure its there.  The 16-page skip is to
//keep Win 95 from thinking we're trying to page ourselves in (we are
//doing that, of course, but there's no reason we shouldn't)
    x = (byte *)ptr;

    for (n=0 ; n<4 ; n++)
    {
        for (m=0; m<(size - 16 * 0x1000) ; m += 4)
        {
            sys_checksum += *(int *)&x[m];
            sys_checksum += *(int *)&x[m + 16 * 0x10000];
        }
    }
}

```

I think I'm just not familiar enough with paging to understand this function. the void\* ptr passed to the function is a recently malloc()'d piece of memory that is *size* bytes big. This is the whole function - j is an unreferenced variable. My best guess is that the volatile int sys\_checksum is forcing the system to physically read all of the space that was just malloc()'d, perhaps to ensure that these spaces exist in virtual memory? Is this right? And why would someone do this? Is it for some antiquated Win95 reason?

# Answer
Raymond Chen answers this directly in a later post on his blog The Old New Thing (Maximus Minimius had the right source it turns out just 3 years too early for a direct explanation): https://blogs.msdn.microsoft.com/oldnewthing/20151111-00/?p=91972

> What this code does is access the memory block specified by the ptr and size parameters in an unusual pattern: It reads byte zero, then the byte at an offset of 16 pages, then byte one, then a byte at an offset of 16 pages plus one, and so on, alternating between a byte and its counterpart 16 pages ahead.
>
> This specific access pattern in Windows 95 defeated the "sequential memory scan" detection algorithm.
>
> Recall that computers in the Windows 95 era had 4MB of RAM. Suppose you were working in a document for a long time. Finally, you're done, and you close the window or minimize it. Boom, now your desktop is visible and the wallpaper bitmap needs to be paged in. If your screen is 1024 × 768 at 16 bits per pixel, that comes out to 1.5MB of memory. Paging in 1.5MB of memory means for the bitmap means kicking out 1.5MB of memory being used for other stuff, and that's a lot of memory for a machine that has only 4MB to work with (especially since a lot of that 4MB belongs to stuff that isn't eligible for being paged out). The phenomenon we saw was that repainting your desktop would flush out most of your memory.
>
> And then the next thing you do is probably launch a new application, which will cover the wallpaper, so the wallpaper memory isn't going to be needed any more. So we basically purged all the memory in your system in order to handle a huge block of memory that got accessed only once.
>
> The trick that Windows 95 used was to watch your pattern of page faults, and if it saw that you were doing sequential memory access, it started marking the memory 16 pages behind the current access as *not recently accessed*. In the case of a straight sequential scan, this means that the entire buffer cycles through a 64KB window of memory, regardless of the buffer size. With this trick, a 4MB buffer ends up consuming only 64KB of memory, as opposed to using all the memory in your system.
>
> The `Sys_PageIn` function specifically defeates the sequential-scan detector by intentionally going back 16 pages and accessing the page again. This causes it to be marked *recently used*, counteracting the *not recently used* that the sequential-scan detector had done. Result: The memory pages are all marked *recently used* and are no longer prime candidates for being paged out.
> 1 votes

# Answer
Your guess is basically correct, and it's being done as an optimization (most likely; I can only speculate of course as I did not write the code).

While an application in Windows appears to have full access to the entire range of RAM in the machine (or at least the range reported to it by the OS), in practice the OS is virtualizing an application's access to the actual physical memory and will store regions (pages) of virtual memory to disk when it needs to. The process of transferring these regions from disk to physical RAM is often called "paging in" (when going from disk to RAM) or "paging out" (when going from RAM to disk).

Disk IO is slow, compared to RAM, and so avoiding paging is ideal for achieving maximum performance. The intent of this function appears to be to attempt to minimize paging during the lifetime of the program by forcing the OS to page all the memory in at the start of the program -- the forcing is accomplished by trying to read from all the memory.

Presumably Windows 95 had some kind of code to detect and stop this behavior, which the comment suggests is being circumvented by reading the memory in a particular pattern. It makes sense that the OS would do this, because forcing a complete page-in like this will force other processes memory to be paged out to disk, probably slowing *them* down.

It can be argued that this is acceptable behavior for a game because a user will generally only run the game and not try to do a lot of multitasking while the game is up, so sacrificing the performance of other processes that may be running isn't that evil.

Some other notes:

* This sort of thing is not likely to work nearly as well today as it probably did back in Windows 95. The nature of OS schedulers has changed quite a lot since then, so it's not necessarily a technique I would suggest you adopt unless you have compelling profiler data and metrics to support the fact that your attempt is a benefit.
* `volatile` is a hint to the implementation to avoid aggressive optimization of an object so declared because that object might change via means the implementation cannot be expected to predict. In other words, it's like a "don't optimize me" flag. This way the compiler, even if it realizes that the variable essentially unused in any significant fashion, will not optimize out the reads from memory into that variable as part of its optimization pass.
* `j` being unused is probably just an oversight.
> 6 votes

# Answer
Resurrecting this, I noticed this entry on Raymond Chen's site recently: Link

> Why am I in the Quake credits? I don't remember what it was that I did specifically...the advice I gave was almost certainly related to memory management and swapping.

This indicates that there is at least a decent possibility that this function is the result of Raymond's advice (and when Raymond Chen says "you need to do this" there is at least a decent possibility that he is right).

It's easy to forget nowadays, but back in 1996 the average gamer PC would have had maybe 16mb of RAM, *max*, and Quake was an absolute *monster* of a program. In those days hard disks used to grind away relentlessly due to paging, and pulling in all allocated memory in this manner would have (at least) helped prevent the page file from having to be touched at runtime, which could have led to a stall of anything up to a second or more.
> 0 votes

---
Tags: c, win32
---


title: HLSL Manual Alpha Blending

text:
# Question
Title: HLSL Manual Alpha Blending
I'm trying to do alpha blending manually because I only want to apply alpha blending on certain pixels. Underlying is the texture I'm writing to. This is what I got so far, but it doesn't give the same result as when AlphaBlendEnable = TRUE

What formula does default alpha blend in HLSL use?

```
matrix WorldViewProjection;

texture2D OverlyingShadingMap;
sampler2D OverlyingShadingMapSampler = sampler_state
{
    texture = <OverlyingShadingMap>;
};

texture2D UnderlyingShadingMap;
sampler2D UnderlyingShadingMapSampler = sampler_state
{
    texture = <UnderlyingShadingMap>;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
    float2 TextureCoordinates : TEXCOORD0;
};

VertexShaderOutput SpriteVertexShader(float4 position : POSITION0, float4 color : COLOR0, float2 texCoord : TEXCOORD0)
{
    VertexShaderOutput output;
    output.Position = mul(position, WorldViewProjection);
    output.Color = color;
    output.TextureCoordinates = texCoord;
    return output;
}

float4 SpritePixelShader(VertexShaderOutput input) : COLOR
{
    float4 overlying = tex2D(OverlyingShadingMapSampler, input.TextureCoordinates);
    clip(overlying.a - 0.001);
    float4 underlying = tex2D(UnderlyingShadingMapSampler, input.TextureCoordinates);
    // Alphablending
    float3 rgb = overlying.rgb * overlying.a + (1 - overlying.a) * underlying.a * underlying.rgb;
    float alpha = underlying.a + (1 - underlying.a) * overlying.a;
    return float4(rgb, alpha);
}

technique SpriteDrawing
{
    pass P0
    {
        AlphaBlendEnable = FALSE;
        VertexShader = compile vs_2_0 SpriteVertexShader();
        PixelShader = compile ps_2_0 SpritePixelShader();
    }
};

```

# Answer
Change this:

```
float3 rgb = overlying.rgb * overlying.a + (1 - overlying.a) * underlying.a * underlying.rgb;
float alpha = underlying.a + (1 - underlying.a) * overlying.a;
return float4(rgb, alpha);

```

To this:

```
return underlying + (1 - underlying.a) * overlying;

```

Formula for alpha blending is: $$pixelColour=src\\\_pixel+(1−src\_α).dest\\\_pixel$$ Taken from here, which also lists formulas for other blendstates in XNA: http://glasnost.itcarlow.ie/~powerk/technology/xna/blending/blending.html
> 2 votes

---
Tags: xna, monogame, hlsl, fragment-shader, alpha-blending
---


# Question
Title: Combine rotation XZ (horizontal) with YZ (vertical). Math formula
I'm trying to make a rotation vertically and horizontally around a point at the same time but I'm not able to combine both.

I have this formula for the horizontal rotation:

```
camera.position.x = x * Math.cos(inc) + z * Math.sin(inc)
camera.position.z = z * Math.cos(inc) - x * Math.sin(inc)

```

And this one for the vertical:

```
camera.position.y = y * Math.cos(inc) + z * Math.sin(inc)
camera.position.z = z * Math.cos(inc) - y * Math.sin(inc)

```

I guess I need to use a Matrix, but not sure how. Here an example with Three.js: https://codepen.io/josema/pen/xyQoga

# Answer
> 0 votes
As @DMGregory mentioned above what I really needed was a way to translate a polar/spherical coordinates into cartesian coordinates.

In other words, I have two angles and one radius and I need to convert it into a Vector3/XYZ.

Here is the code:

```
function polarToCartesian( angleV, angleH, radius ) {

  var phi = ( 90 - angleV ) * DEG2RAD
  var theta = ( angleH + 180 ) * DEG2RAD

  return {
    x: -(radius * Math.sin(phi) * Math.sin(theta)),
    y: radius * Math.cos(phi),
    z: radius * Math.sin(phi) * Math.cos(theta),
  }

}

```

Source: https://gist.github.com/jhermsmeier/72626d5fd79c5875248fd2c1e8162489

---
Tags: mathematics, rotation, matrix, three.js, trigonometry
---


# Question
Title: Nullpointer exception with Scrollpane in LIBGDX
I get a strange Nullpointer exception and I don't understand why. Can someone help me ?

Exception:

```
Exception in thread "LWJGL Application" java.lang.NullPointerException
    at com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.draw(ScrollPane.java:583)
    at com.badlogic.gdx.scenes.scene2d.Group.drawChildren(Group.java:123)
    at com.badlogic.gdx.scenes.scene2d.Group.draw(Group.java:57)
    at com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup.draw(WidgetGroup.java:163)
    at com.badlogic.gdx.scenes.scene2d.ui.Table.draw(Table.java:119)
    at com.solvapps.tests.NewStoryBook.draw(NewStoryBook.java:40)

```

My Code ACTOR:

```
public class NewStoryBook extends Actor {

    Table table;
    ScrollPane pane;
    Table tableScroller;

    public NewStoryBook(Skin skin) {

        int w = Gdx.graphics.getWidth();
        int h = Gdx.graphics.getHeight();
        table = new Table();
        table.setPosition(400, 400);
        table.setSize(w / 3, h * 0.8f);
        tableScroller = new Table();
        tableScroller.add(new Label("bla bla",skin));
        pane = new ScrollPane(tableScroller);

        table.add(pane);

    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        table.draw(batch, parentAlpha);
    }

```

My Code App:

```
public class StoryBoxTest4 extends ApplicationAdapter {

    private Stage stage;
    NewStoryBook newstoryBook;

    public void create() {
        stage = new Stage(new ScreenViewport());
        Skin skin = new Skin(Gdx.files.internal(SkinManager.getSkin()));
        newstoryBook = new NewStoryBook(skin);
        stage.addActor(newstoryBook);
        Gdx.input.setInputProcessor(stage);
    }

```

# Answer
> 0 votes
This line is the line that throws a NullPointerException:

```
getStage().calculateScissors(widgetAreaBounds, scissorBounds);

```

From this we can deduce that `getStage()` is returning `null`. Why? Because you haven't added your table to a `Stage`. Instead you draw it manually in your `NewStoryBook` actor which is something you shouldn't do.

Solution? Make `NewStoryBook` extend `Group` instead and use `addActor`:

```
public class NewStoryBook extends Group {
    ...

    public NewStoryBook(Skin skin) {
        ...
        addActor(table);
    }

    // Remove draw() function
}

```

---
Tags: libgdx, side-scroller
---


# Question
Title: Resize rigidbody in runtime, Box collider OnTriggerEnter not work
Scene setting:

Object A: Rigidbody, kinmeatic Box collider, is trigger true.

Object B: Box collider, is trigger true.

Script is on Object A:

```
void FixedUpdate()
{
    if(increaseScale)
    {
        transform.localScale += transform.forward* speed;

        // when to stop
        if ((AEForward * transform.localScale.z).sqrMagnitude >= range * range)
            increaseScale = false;
    }
}

void OnTriggerEnter(Collider other)
{
    Debug.Log(other.transform);
}

```

No log message when part of object A is inside B.

And the funny part is if I use it on a sphere collider, it works. (use transform.localScale += new vector3(1,1,1)\* speed; instead )

# Answer
I believe that you need to have a Rigidbody attached to both object A and object B to register a trigger collision. It looks like you only have one attached to object A.
> -1 votes

---
Tags: unity, collider
---


# Question
Title: Extrude only vertices where the assigned texture is transparent?
I am looking at implementing a water surface on my spherical object and have created a texture with transparent pixels where the water should be. However, I am currently confused on how I can extrude only vertices where the texture is transparent. Do I have to test the texture at the appropriate position prior to assigning the vertex and just assign a `Color.Transparent` value to that vertex or am I thinking about this all wrong?

---

Special thanks to @Bram for helping me to answer some questions that could help clarify my specific situation.

* What geometry do you extrude?
    + Individual vertices with a geometry, fragment, or hull shader.
* What is the extrusion for?
    + To make waves in the water.

When I mention testing texels and then assigning colors to a vertex, I mean doing so beforehand when creating the `Vertex[]` object. This would be easy enough to do I suppose; I'd have to look into some samples of how to test the texture on the `C#` side, which is why I'd love to do it in a shader that has a similar flow as below:

* Vertex Shader
    + Create the sphere.
* Pixel Shader
    + Grab only vertices that have transparent pixels via `TEXCOORD0`.
* Geometry/Fragment/Hull Shader
    + Extrude those vertices.

# Answer
> 0 votes
NOTE: the vertex shader would not create a sphere. It would consume the sphere vertices, and generate fragments. A fragment is kind of like a pixel on your screen, but may or may not be visible depending on fragments in front of it.

I see three possible ways of creating a globe with water and land, and have water show wave animation.

(1) **Split land/water on CPU**: Separate the sphere mesh into two parts: The land part, and the water part. Then use different shader programs to render them.

(2) **Split land/water in vertex shader**: Render the globe as a single mesh, and at render time, figure out if a vertex lies on land or water. If it is a water vertex you could perturb the vertex.

(3) **Split land/water in fragment shader**: In the fragment shader, you look up the texel to see if it is sea or land. If it is sea, you could apply an animated bump map, or better: procedural animation by just perturbing the surface normal a little bit.

Note that your globe geometry will have a much lower resolution than your land/sea texture. So doing a land/sea test per vertex (solution 1 and 2) will only roughly follow coast lines. Solution 3 would definitely look better.

When going for (3) you could even do something similar to "percentage-closer-filtering". Instead of a single texel lookup, you do 9 or so look-ups in its neighborhood. Then you count the number of land texels. If you see both land and sea textures, you know you are on the coast-line. And at coastlines, you can then render a white band to show the "surf" of waves breaking.

In pseudo code:

```
colour = texture_lookup( uv );
float delta_uv[9][2] =
{
  -e,-e,  0,-e,  e, e,
  -e, 0,  0, 0,  e, 0,
  -e, e,  0, e,  e,-e
};
int numland = 0;
for ( int i=0; i<9; ++i )
{
   samplecoord = uv + delta_uv[i];
   rgba = texture_lookup( samplecoord );
   if ( rgba.a >= 1 ) numland++;
}
if ( numland == 9 )
{
   // inland:
}
else if ( numland == 0 )
{
   // deep sea:
   PERTURB THE SURFACE NORMAL TO CREATE WAVE
   ...
}
else
{
   // coast line: render as white.
   colour = surf_colour;
}
// Shade the fragment using the surface normal, light source, colour, etc.
...

```

Note that you could have the surf wash in/out the coast by replacing the ( numland == 0 ) test with something more dynamic: some frames you render more surf, some frames, you render less.

**UPDATE**: because it seemed like a fun challenge, I implemented it on shadertoy. You can see the results and code there.

---
Tags: c#, directx11, sharpdx
---


# Question
Title: Unreal Engine: Is it possible to animate inside unreal engine?
I have a skeleton mesh and want to slightly tweak it. Is there a way to do this natively in Unreal Engine instead of resorting to a 3D program?

# Answer
> 2 votes
According to Unreal Engine Docs you can modify any existing animation sequences as part of "Additive Layer Tracks".

# Answer
> 0 votes
Yes, you can edit the animation within the animation editor.

---
Tags: animation, unreal-4, skeletal-animation, unreal
---


# Question
Title: Scaling web game to suit any screen size
I've made a simple multiplayer game, and now trying to make it fit on any screen size. I've tried stretching it out to fit the browser size, but it just appears weird and distorted. I'm also trying to avoid having borders around the edges as it doesn't look particularly nice.

Is there a way to solve this that is fair to all players?

# Answer
> 0 votes
I usually center the frame in the browser and give it fixed dimensions. If the user's screen is smaller than the dimensions, scale the window proportionally at a set interval until it fits.

For example, if your game is 600px * 400px, and your user has a 500px * 700px display (not realistic), you could set your interval to .25 and scale it down to 450px * 300px, or 75% of its original size. If that doesn't fit, scale it down again (300px * 200px).

This also means everything rendered in the game has to be as well, so keep that in mind.

---
Tags: game-design, scale
---


# Question
Title: How do I implement 2d color animation like in this video?
link on youtube at 1:38 - 1:42, purple things (I think this is particle system) that come off from the moon.

Someone else had decompiled the game in the past, and the assets shows that the dark blue area around the moon (after purple things come off) is just background image. So my assumption is that there are many of those 'purple things', that use additive blending to give different density of 'purpleness'.

The details that I'm looking at are:

1. As those purple things come off completely from the moon, it forms jagged shapes
2. At the edge of those jagged shapes, color blends smoothly instead of sharp turn between purple and dark blue(I know how to do it with simple shapes, but in here, the jagged shape itself constantly changes)
3. further from edge between dark blue and purple, at the light purple direction, the density of purple is nice and smooth

I'm pretty familiar on animating objects by manipulating transform, but this one seems like a lot of color works with programatically created shapes, any idea?

# Answer
> 1 votes
How about first rendering the bright colors, then rendering the dark colours as jagged spikes multplicatively over the bright colors and then doing an additive gauss blur of all the colours and add the result to the original layer (the layer which had it's colours multiplied by those of the jaggies)?

The spikes could be made using points radiating from the moon connecting to two points somwehere on the area of the moon, forming a triangle.

# Answer
> 1 votes
I would create this effect using a flow map and a shader. This video shows a great example of how these effects are achieved. Wel worth watching.

The basic idea is this: Textures are maps with r, g, b and alpha values. Usually these are used to store a color and is shown as-is on the screen. However, these values can be used for anything. Most well known are normalmaps or bumpmaps. In these the RGB values are used as XYZ vectors for representing angles on the texture for lightreflection calculations. A flowmap does something similar, it uses the R and G components as X,Y offsets to simulate waterflow, smoke or any other warping effect. With a well crafted flowmap effects like these can be created without the need for complex custom code for each effect.

As for your question, I assume a flowmap was created to have the shape of the effect originate from the center with irregular shapes. Another texture with purple to black and transparent hues is then rendered with that flowmap over the background. Check the video I linked and I think it becomes more clear what is going on.

There are many examples, but I think the Heartstone gold card effect shows how powerful such system can be. Many different effect are used with a single well thought out shader system.

\[1\]: https://youtu.be/OYjMnMZe1Vg “Heartstone gold cards”

---
Tags: 2d, animation, color
---


title: Best way to store map?

text:
# Question
Title: Best way to store map?
I am trying to make a simple game that simulates ants inside a colony, in the Java language. They can move around the paths randomly, go outside to eat leaves, etc. The game is meant to be more of an exercise in programming logic, than an actual game, so I want to try to stay away from graphics, if at all possible. The idea I currently have is to use a 2D array, perhaps like:

```
public class Map {
    int mapArray[][] = new int[5][5];

    public static void main(String[] args) {
        Map m = new Map();
    }

    public map() {
        //Create the map
        for(int x = 0; x < 5; x++) {
            for(int y = 0; y < 5; y++) {
                mapArray[y][x] = 0;
            }
        }

        //Print the map
        for(int x = 0; x < 5; x++) {
            for(int y = 0; y < 5; y++) {
                System.out.print(mapArray[x][y]);
            }
            System.out.println();
        }
    }
}

```

I would then do my logic based on the values at different positions in the array.

Is this the best way, or is there a different method that would work better than this one?

# Answer
> 1 votes
Yep, this is a good tactic for learning!

Focusing on the goal you actually want to achieve and not getting lost in the things you don't care about achieving right now (graphics) means you'll reach your goal faster and can move on to the next thing.

As far as this technique specifically of having a simple 2D text grid for your game/simulation, yeah that works great.

That's how I started, using QBasic and later C++ to make text games that used text for graphics. I am self taught and now I'm a professional game programmer so it worked out pretty well for me.

# Answer
> 1 votes
A 2D array is definitely the right way to go, if you want the ants to be limited to a flat surface. (This makes sense if you have, say, an ant terrarium.) Keep in mind, though, that if you want your ants to be walking around in 3D space, you will need a 3D array.

I do a lot of Java programming professionally, and I have a lot of suggestions to make your code a bit more advanced, but I don't want to overwhelm you, and I think that this is a really good start if you don't want to get into things like `ArrayList<Integer>` and `enum` *(enumerated types)* just yet.

You do need to decide what the different `int` values mean in your map. Is `0` a wall? Is `1` sand? Is `2` leafy growth? That's something you'll need to plan as you go, and where `enum` would come in handy.

Then you can model an ant's position with its `(x,y)` coordinate, and you should be good to go.

Good luck!! Programming is a lot of fun, and Java and Python are both great languages to start in.

# Answer
> 0 votes
Your on the right track and I would use nested `for` loops for the `x` and `y`, just like you, except unless I'm missing something, I think you can store the grid coordinates and print them to the screen in the same loop.

---
Tags: java, logic
---


# Question
Title: How can I move objects in a cyclic loop?
I have number of objects I want to move them up and forward then when the last one each time in the array get to the end position move this object to the start of the array and to the start position the original start position of the first object.

The idea is to make the objects cyclic on place. Not to move all the objects but to cyclic them up and forward.

I tried this but it's totally wrong. It's moving all the objects as a group to another place and the last one return to the first position big mess.

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

public class MoveObjects : MonoBehaviour
{
    public float speed = 1f;

    private Vector3[] startPos;
    private Vector3[] endPos;
    private Vector3[] currentPos;
    private GameObject[] objectstoMove;

    // Use this for initialization
    public void Init()
    {
        objectstoMove = GameObject.FindGameObjectsWithTag("Stair");
        startPos = new Vector3[objectstoMove.Length];
        endPos = new Vector3[objectstoMove.Length];
        currentPos = new Vector3[objectstoMove.Length];

        for(int i = 0; i < objectstoMove.Length; i++)
        {
            startPos[i] = objectstoMove[i].transform.position;
            endPos[i] = new Vector3(objectstoMove[i].transform.position.x + 50, objectstoMove[i].transform.position.y + 50, 0);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (objectstoMove != null)
        {
            for(int i = 0; i < objectstoMove.Length; i++)
            {
                currentPos[i] = objectstoMove[i].transform.position;
                objectstoMove[i].transform.Translate(1, 1, speed * Time.deltaTime);

                if(currentPos[i].x >= endPos[i].x && currentPos[i].y >= endPos[i].y)
                {
                    SetTransform(objectstoMove[objectstoMove.Length-1]);
                }
            }
        }
    }

    void SetTransform(GameObject n)
    {
        n.transform.position = startPos[0];
    }
}

```

Example screenshot:

Each cube should move up and forward following the one above it. The top one when it's reaching to the end position it should move back to the first cube start position. Then the next top cube when reaching the end position it should move to the original first cube start position !

The idea is to simulate some kind of stairs escalator. So the cubes should move in cyclic. The whole cubes not should change position but they should cyclic.

I tried also this for testing: But not working at all.

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

public class MovingTest : MonoBehaviour
{
    public List<Transform> objectstomove = new List<Transform>();
    public float speed = 1;
    public Vector3 position1;
    public Vector3 position2 = new Vector3(2, 2, 2);

    private Transform lastobj;

    // Use this for initialization
    void Start ()
    {
        position1 = objectstomove[0].position;
        lastobj = objectstomove[objectstomove.Count - 1];
    }

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

        for (int i = 0; i < objectstomove.Count; i ++)
        {
            objectstomove[i].position = Vector3.MoveTowards(objectstomove[i].position,
                                                 position2, speed * Time.deltaTime);
        }

        if (lastobj.position.x == 2)
        {

            lastobj.position = position1;
            objectstomove.Remove(lastobj);
            objectstomove.Insert(0, lastobj);
            lastobj = objectstomove[objectstomove.Count - 1];

            for (int i = 0; i < objectstomove.Count; i++)
            {
                objectstomove[i].position = Vector3.MoveTowards(objectstomove[i].position,
                                                     position2, speed * Time.deltaTime);
            }
        }
    }
}

```

# Answer
I'd approach this by thinking of the hypothetical track the steps are sliding along.

It has a start and an endpoint, and each step takes its respective position in line between the two.

For a simple straight line track, we can use a `Lerp` to find the corresponding spot on the line. If you want to use a more realistic escalator track, with a short flat section at the top and bottom curving to a slope in between, you can sample an AnimationCurve instead.

```
public Transform[] steps;
public float stepsPerSecond = 1f;

Vector3 trackStart;
Vector3 trackEnd;
float phase = 0f;

void Start() {
    // Infer the start & end positions of the track
    // from the position of the first & last steps
    trackStart = steps[0].position;
    int count = steps.Length;
    var span = steps[count - 1].position - trackStart;
    // The track ends one more step distance after the last step.
    // (So the last step has some distance to travel before it wraps)
    trackEnd = trackStart + (count + 1) * span / count;
}

void Update() {
    float divisor = 1f / steps.Length;

    // Compute the current phase of the escalator,
    // from 0 (1st step at track start) to 1 (1st step at track end)
    phase = Mathf.Repeat(phase + stepsPerSecond * divisor * Time.deltaTime, 1f);

    // Place each step a proportional distance along the track.
    for(int i = 0; i < steps.Length; i++) {
        float t = Mathf.Repeat(phase + i * divisor, 1f);
        steps[i].position = Vector3.Lerp(trackStart, trackEnd, t);
    }
}

```

Note that if you want to use this escalator to push physics objects, you might instead want to (in FixedUpdate) treat this calculated position as a target, then compute a velocity to reach that target, and apply it to the step's RigidBody. This gives the collision solver more to work with, since instead of the steps teleporting every frame they're pushing with a specific momentum that they can transfer to objects riding on top of them. You'll find you get less jittering and tunneling this way, though it will be possible to nudge the steps slightly out-of-track with enough force.
> 0 votes

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


# Question
Title: Why does the first red-zone sometimes appear too close to the border in my battle-royale red-zone feature?
## The Problem:

If you've ever played or watched some gameplay of a battle royal game (like PUBG, for example), you'll always find an event during any battle called **the red zone**.

Basically, at a certain point in time during the game, a random zone on the map (possibly a square, possibly a circle) will be bombarded with artillery fire, for around 30 seconds or so. The game will fire, say, 20 shells at random positions within that red zone. If you're in the red zone, and it happens that you are within the **splash radius** (see below) of the shell, you will instantly die.

## My attempt at recreating the Red-Zone feature using the JS canvas:

using an `eventListener`, whenever the user clicks on the canvas, a random point will be generated and a circle of radius `50` will be plotted around that point, but there's a catch:

**If the point generated is less than `50` units away from the border of the zone *or* the point generated is less than `100` units away from another already generated point**, the algorithm will keep generating new points and test it against the 2 previously stated conditions until it meets them, then it will add that point to the array containing all the dots.

The algorithm does work as intended for all test cases, **but sometimes the first point, and ONLY the first point generated, violates these 2 conditions.** I have no idea why. I've tried using a `do-while` loop instead of a `while` loop, (which keeps generating new points until one meets the 2 conditions), but no luck.

Please help me with this issue as fast as possible. Thanks in advance. Here's the code (CodePen): https://codepen.io/Undefined\_Variable/full/oQeoqE/

```
let canvas = document.body.querySelector("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 0.75 * screen.width;
canvas.height = 0.8 * screen.height;
let CW = canvas.width;
let CH = canvas.height;
canvas.style.top = (screen.height / 2) - (canvas.height / 2) + "px";
canvas.style.left = (screen.width / 2) - (canvas.width / 2) + "px";

let dotArr = [];
let dotSize = 50
let dotDistance = 100;
let borderDistance = 50;
let dotCounter = 0;

class dot {
  constructor(posX, posY) {
    this.posX = posX;
    this.posY = posY;
    this.radius = dotSize;
  }
  drawDot() {
    ctx.save();
    ctx.translate(this.posX, this.posY);
    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
  }
}

function mainLoop() {

  function drawCircle() {
    ctx.save();
    ctx.translate(CW / 2, CH / 2);
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.arc(0, 0, 0.25 * CW, 0, Math.PI * 2);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }

  function drawDots() {
    for (let dot of dotArr) {
      dot.drawDot();
    }
  }

  ctx.clearRect(0, 0, CW, CH);
  drawCircle();
  drawDots();
  requestAnimationFrame(mainLoop);
}

function addDot() {

  function generateDot() {
    let center_x = CW / 2;
    let center_y = CH / 2;
    let angle = Math.random() * 360;
    let distance = Math.random() * (0.25 * CW);
    let radius = 0.25 * CW;

    return [center_x + Math.cos(angle) * distance, center_y + Math.sin(angle) * distance, center_x + Math.cos(angle) * radius, center_y + Math.sin(angle) * radius]
  }

  function verifyDotPosition(xPar, yPar, xBorder, yBorder) {
    for (let dot of dotArr) {
      if (Math.sqrt(Math.pow(xPar - dot.posX, 2) + Math.pow(yPar - dot.posY, 2)) < dotDistance) {
        return false;
      }
      if (Math.sqrt(Math.pow(xPar - xBorder, 2) + Math.pow(yPar - yBorder, 2)) < borderDistance) {
        return false;
      }
    }
    dotCounter++;
    return true;
  }

  let newDots = generateDot();
  let x1 = newDots[0];
  let y1 = newDots[1];
  let x2 = newDots[2];
  let y2 = newDots[3];

  while (!verifyDotPosition(x1, y1, x2, y2)) {
    newDots = generateDot();
    x1 = newDots[0];
    y1 = newDots[1];
    x2 = newDots[2];
    y2 = newDots[3];
  }

  if (dotCounter < 10) {
    dotArr.push(new dot(x1, y1));
  } else {
    canvas.removeEventListener("click", addDot);
  }
}

mainLoop();

canvas.addEventListener("click", addDot);
```

```
canvas {
  border: 1px solid black;
  position: absolute;
}

body {
  margin: 0;
}
```

```
<!DOCTYPE html>
<html>

<head>
  <title>redZone-demo</title>
</head>

<body>
  <canvas></canvas>
</body>

</html>
```

---

-*each shell has a splash radius, if you are **inside** a circle of a radius equal to that **splash radius** surrounding the point where the shell hit it, you will die*

---

## Clarification:

When I said that sometimes the algorithm doesn't work for the first point, I mean that sometimes the first point is generated too close to the border of the "red zone".

# Answer
> 1 votes
The issue is in `verifyDotPosition`:

```
function verifyDotPosition(xPar, yPar, xBorder, yBorder) {
    for (let dot of dotArr) {
        if (Math.sqrt(Math.pow(xPar - dot.posX, 2) + Math.pow(yPar - dot.posY, 2)) < dotDistance) {
            return false;
        }
        if (Math.sqrt(Math.pow(xPar - xBorder, 2) + Math.pow(yPar - yBorder, 2)) < borderDistance) {
            return false;
        }
    }
    dotCounter++;
    return true;
}

```

You only check if the generated position is too close to the border inside the for-loop, and that for loop is not evaluated if `dotArr` is empty, which it is for the first dot to be generated. Simply move the border condition outside of the for loop:

```
function verifyDotPosition(xPar, yPar, xBorder, yBorder) {
    for (let dot of dotArr) {
        if (Math.sqrt(Math.pow(xPar - dot.posX, 2) + Math.pow(yPar - dot.posY, 2)) < dotDistance) {
            return false;
        }
    }
    if (Math.sqrt(Math.pow(xPar - xBorder, 2) + Math.pow(yPar - yBorder, 2)) < borderDistance) {
        return false;
    }
    dotCounter++;
    return true;
}

```

---
Tags: javascript, trigonometry
---


title: simple 2d car AI unity

text:
# Question
Title: simple 2d car AI unity
I have a top down Car Game. how can I implement AI for the Cars? how the car follow the way points? I want AI cars also rotate itself along the path.

I tried this solution

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

public class waypoint : MonoBehaviour {

    public List<Transform> waypoints;
    private Transform currentWaypoint;
    public float speed = 5f;
    private float closeEnouth = 0.5f;
    int point = 0;

    void Start()
    {
        currentWaypoint = waypoints[point];
    }
    // Update is called once per frame
    void Update()
    {

        Quaternion rotation = Quaternion.LookRotation(waypoints[point].position - transform.position, transform.TransformDirection(Vector3.forward));
        transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);
        float dist = Vector3.Distance(waypoints[point].position, transform.position);
        transform.position = Vector3.MoveTowards(transform.position, waypoints[point].position, Time.deltaTime * speed);
        if (Vector3.Distance(this.transform.position, waypoints[point].position) < closeEnouth)
        {
            if (point + 1 < waypoints.Count)
                point++;

        }
    }
}

```

and the car moved in the path but it moves reversed and if arrives the final node it stops and corrects its direction and console displays "Look rotation viewing vector is zero" error.

Thanks in advance

# Answer
This tutorial series aims to create a simple AI for a racing game in 3D. You can simply achieve the same thing in 2D as well.
> -1 votes

---
Tags: unity, 2d, car, waypoints
---


# Question
Title: HTML5 games: play() failed because the user didn't interact with the document first
I'm creating an HTML5 game using MelonJS game engine. Before I load the game, I have a simple pre-login page with a Splash and background music. This page has no need to load the game engine or game scripts.

The game will most likely be played on Chrome, but with the latest Chrome 66 update, you cannot autoplay music until someone "interacts" with the page:

> login.html:72 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

With code

```
<audio id="soundtrack" src="data/bgm/Music_Login_Splash_v1.ogg" type="audio/ogg"></audio>

```

and

```
$(document).ready(function() {
    $('#soundtrack').get(0).play();
});

```

Google states: Autoplay with sound is allowed if:

* User has interacted with the domain (click, tap, etc.).
* On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
* On mobile, the user has added the site to his or her home screen.

Mousemove no longer counts as "an event" or "interaction".

Wondering if there's a solid workaround for this as not autoplaying the login splash soundtrack will be odd and ruin the user gaming experience. Workarounds I've tried are to have an autoclick event happen, or autoreloading the page if it's their first time. Otherwise, I can try loading the game engine for the login page and playing thru canvas audio.

# Answer
There is a good reason for this precaution: Users usually don't expect audio from websites. They get really angry when they load a website, and an audio advertisement blares at them at full volume. This is even worse if they opened multiple tabs and are not sure which one is responsible. That's why all browser vendors prevent websites from playing audio unless the user interacts with them. Yes, I understand that you want to use this feature for good and not evil, but if there was a workaround, that workaround could also be used by the advertisers. So be glad that such a workaround does not exist.

So the only real solution is to find some reason why the player would need to perform some form of interaction after the game HTML document is loaded. A good excuse is some kind of initial screen with a copyright message and other legalese which disappears after the user clicked on it. You can also use this splash screen as a preloader for the assets needed for your login screen. That makes sure the background music is actually loaded when a user with a low bandwidth connection sees it.
> 11 votes

# Answer
Please go through https://developers.google.com/web/updates/2017/06/play-request-was-interrupted if you need additional info.

To load the track

```
   var audio = new Audio('./soundtrack.format');

```

play it when you need like

```
   var playPromise = audio.play();

```
> 1 votes

---
Tags: html5, audio, music
---


# Question
Title: How can I keep the same speed to be static speed and how to move the objects all at the same time?
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class MoveObjects : MonoBehaviour
{
    public GameObject[] objectsToMove;
    public float stepsPerSecond = 1f;
    public float speed = 3f;

    private Vector3 trackStart;
    private Vector3 trackEnd;
    private float phase = 0f;

    // Use this for initialization
    public void Init()
    {
        objectsToMove = GameObject.FindGameObjectsWithTag("Stair");
        // Infer the start & end positions of the track
        // from the position of the first & last steps
        trackStart = objectsToMove[0].transform.position;
        int count = objectsToMove.Length;
        var span = objectsToMove[count - 1].transform.position - trackStart;
        // The track ends one more step distance after the last step.
        // (So the last step has some distance to travel before it wraps)
        trackEnd = trackStart + (count + 1) * span / count;
    }

    // Update is called once per frame
    void Update()
    {
        if (objectsToMove != null && objectsToMove.Length > 0)
        {
            MoveRealistic();
            //MoveRegular();
        }
    }

    private void MoveRealistic()
    {
        float n = (float)objectsToMove.Length;

        foreach (GameObject step in objectsToMove)
        {
            float step_x = step.transform.position.x;
            float max_x = (n - 1f) * 24f; // The javascript has this "24", which is based on the width of the step + the outline.
            step_x = Mathf.Repeat(step_x + speed * Time.time, max_x);

            float r = 5f;
            float x_for_atan = step_x * r / max_x - r / 2f;
            if (step_x < 3f * 24f)
            {
                x_for_atan = -r / 2f + .5f;
            }
            if (step_x >= max_x - 3f * 24f)
            {
                x_for_atan = r / 2f - .5f;
            }

            float step_y = 180f + 120f * (float)Math.Atan(x_for_atan);

            step.transform.position = new Vector3(step_x, -step_y, 0);
            // negative y because the javascript uses top, which starts at 0
            // at the top, and positive goes down. Unity goes the other direction.
        }
    }

    private void MoveRegular()
    {
        float divisor = 1f / objectsToMove.Length;

        // Compute the current phase of the escalator,
        // from 0 (1st step at track start) to 1 (1st step at track end)
        phase = Mathf.Repeat(phase + stepsPerSecond * divisor * Time.deltaTime, 1f);

        // Place each step a proportional distance along the track.
        for (int i = 0; i < objectsToMove.Length; i++)
        {
            float t = Mathf.Repeat(phase + i * divisor, 1f);
            objectsToMove[i].transform.position = Vector3.Lerp(trackStart, trackEnd, t);
        }
    }
}

```

Whne I'm using the MoveRealistic I'm using a break point on the line:

```
step_x = Mathf.Repeat(step_x + speed * Time.time, max_x);

```

I see that speed value is 3 and max\_x value is 216. The only value that change is the step\_x what make the speed to change to very very high. And I want a static speed(3).

Another problem is that each time one object(step) is moving when he finished moving the next one move. But I want to create a escalator stairs effect using this method and the objects should move all the same time like it is in this jsfiddle: And this is where I have take the code from and converted it to unity csharp:

jsfiddle

Last problem is that the objects the step's(stairs) moving in other position/s and not on their original position/s.

This is the steps/stairs original position. And where they should move.

And this is where they are moving when using the MoveRealistic method:

When using the MoveRegular method they are moving fine but I want to be able to use also the MoveRealistic method like in the jsfiddle.

# Answer
As I mentioned in my previous answer, if you want to get a curve at the top and bottom of your escalator, I'd recommend using an AnimationCurve. That way you can precisely control the shape you want.

Here's a modified example using an animation curve instead of a Lerp to space out the steps.

```
public class Escalator : MonoBehaviour {

    public Transform[] steps;
    public AnimationCurve curve;
    public float stepsPerSecond = 1f;

    Vector3 trackStart;
    Vector3 horizontalTravel;
    float verticalTravel;
    float divisor;

    float phase = 0f;

    void Start() {
        trackStart = steps[0].position;
        int count = steps.Length;
        var span = steps[count - 1].position - trackStart;

        divisor = 1f / count;
        horizontalTravel = (count + 1) * span * divisor;
        horizontalTravel.y = 0f;

        verticalTravel = span.y;
    }

    void Update() {
        phase = Mathf.Repeat(phase + stepsPerSecond * divisor * Time.deltaTime, 1f);

        for (int i = 0; i < steps.Length; i++) {
            float t = Mathf.Repeat(phase + i * divisor, 1f);
            // Get the height of the curve at this step.
            float curveHeight = curve.Evaluate(t) * verticalTravel;

            steps[i].position = trackStart                // First step
                              + horizontalTravel * t      // evenly spaced horizontal
                              + curveHeight * Vector3.up; // curving vertical
        }
    }
}

```

This assumes your animation curve runs from 0 to 1 on the horizontal, and 0 to 1 on the vertical. (It works for "down" escalators too - it takes its direction from the offset between the first and the last step, so you don't need to change the curve itself)

Here's an example of how I set up my curve:
> 1 votes

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


title: How to get camera to follow car

text:
# Question
Title: How to get camera to follow car
i am making a top down racing game where the car progresses along the track, however i need the camera follow the car as it progresses through the track. I am unsure how to fix the error. I am new to python/pygame so sorry for any obvious errors. :P thanks

P.S. the background and camera code is towards the bottom

```
import os
import pygame
import random
from tkinter import *
from math import tan, radians, degrees, copysign
from pygame.math import Vector2
from Login import *

class Buttons:
#window
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.quitButton = Button(frame, text="Race!", fg="red", command=frame.quit)
        self.quitButton.pack(side=LEFT)

root = Tk()
b = Buttons(root)
root.mainloop()

###############################################################
#music player
pygame.mixer.pre_init(44100,16,2,4096)
pygame.init()
screen = pygame.display.set_mode((1280, 800), pygame.RESIZABLE)
rect = screen.get_rect()
clock = pygame.time.Clock()

#music
pygame.mixer.music.load("GasGasGas.mp3")
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(-1)
###############################################################

class Car:
    def __init__(self, x, y, angle=0.0, length=4, max_steering=30, max_acceleration=5.0):
        self.position = Vector2(x, y)
        self.velocity = Vector2(0.0, 0.0)
        self.angle = angle
        self.length = length
        self.max_acceleration = max_acceleration
        self.max_steering = max_steering
        self.max_velocity = 20
        self.brake_deceleration = 10
        self.free_deceleration = 2

        self.acceleration = 0.0
        self.steering = 0.0

    def update(self, dt):
        self.velocity += (self.acceleration * dt, 0)
        self.velocity.x = max(-self.max_velocity, min(self.velocity.x, self.max_velocity))

        if self.steering:
            turning_radius = self.length / tan(radians(self.steering))
            angular_velocity = self.velocity.x / turning_radius
        else:
            angular_velocity = 0

        self.position += self.velocity.rotate(-self.angle) * dt
        self.angle += degrees(angular_velocity) * dt

class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Project BrmBrm")
        width = 1280
        height = 720
        self.screen = pygame.display.set_mode((width, height))
        self.clock = pygame.time.Clock()
        self.ticks = 60
        self.exit = False

    def run(self):
        current_dir = os.path.dirname(os.path.abspath(__file__))
        image_path = os.path.join(current_dir, "RedLambo.png")
        car_image = pygame.image.load(image_path)
        car = Car(0, 0)
        ppu = 32

        while not self.exit:
            dt = self.clock.get_time() / 1000

            # Event queue
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.exit = True

            # User input
            pressed = pygame.key.get_pressed()

            if pressed[pygame.K_UP]:
                if car.velocity.x < 0:
                    car.acceleration = car.brake_deceleration
                else:
                    car.acceleration += 1 * dt
            elif pressed[pygame.K_DOWN]:
                if car.velocity.x > 0:
                    car.acceleration = -car.brake_deceleration
                else:
                    car.acceleration -= 1 * dt
            elif pressed[pygame.K_SPACE]:
                if abs(car.velocity.x) > dt * car.brake_deceleration:
                    car.acceleration = -copysign(car.brake_deceleration, car.velocity.x)
                else:
                    car.acceleration = -car.velocity.x / dt
            else:
                if abs(car.velocity.x) > dt * car.free_deceleration:
                    car.acceleration = -copysign(car.free_deceleration, car.velocity.x)
                else:
                    if dt != 0:
                        car.acceleration = -car.velocity.x / dt
            car.acceleration = max(-car.max_acceleration, min(car.acceleration, car.max_acceleration))

            if pressed[pygame.K_RIGHT]:
                car.steering -= 500 * dt
            elif pressed[pygame.K_LEFT]:
                car.steering += 500 * dt
            else:
                car.steering = 0
            car.steering = max(-car.max_steering, min(car.steering, car.max_steering))

            # Logic
            car.update(dt)

            # Drawing
            self.screen.fill((0, 0, 0))
            rotated = pygame.transform.rotate(car_image, car.angle)
            rect = rotated.get_rect()
            self.screen.blit(rotated, car.position * ppu - (rect.width / 2, rect.height / 2))
            pygame.display.flip()

            self.clock.tick(self.ticks)
        pygame.quit()

##########track
BACKGROUND = pygame.Surface((1280, 800))
BACKGROUND.fill((127, 69, 2))
BACKGROUND = pygame.image.load("track1.png").convert()
screen.blit(BACKGROUND,(0,0))
pygame.display.update()

############background

class Background(pygame.sprite.Sprite):

    def __init__(self, image, location):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect(topleft=location)

background = Background(BACKGROUND, [0, 0])
camera = pygame.math.Vector2(0, 0)

screen.blit(background.image, background.rect.topleft+camera)

for sprite in Car:
    screen.blit(sprite.image, sprite.rect.topleft+camera)

if __name__ == '__main__':
    game = Game()
    game.run()

```

# Answer
> 0 votes
When you move the car you need to move the camera vector with the same velocity as well. Then you can subtract the camera from the positions of the game objects to offset them.

I've modified your code and adjusted some values to make it work (I didn't know what the purpose of the `ppu` variable was, but I had to remove it). The `camera` vector is now an attribute of the car, because that way it was easier to update it.

```
import pygame
import random

from math import tan, radians, degrees, copysign
from pygame.math import Vector2

pygame.mixer.pre_init(44100,16,2,4096)
pygame.init()
screen = pygame.display.set_mode((1280, 800), pygame.RESIZABLE)
rect = screen.get_rect()
clock = pygame.time.Clock()
BACKGROUND = pygame.Surface(screen.get_size())
# Drawing a grid.
for x in range(screen.get_width()//20):
    pygame.draw.line(BACKGROUND, (160, 90, 0), (x*20, 0), (x*20, 800), 1)
for y in range(screen.get_height()//20):
    pygame.draw.line(BACKGROUND, (160, 90, 0), (0, y*20), (1280, y*20), 1)

class Car:
    def __init__(self, image, x, y, angle=0.0, length=4, max_steering=10, max_acceleration=5.0):
        self.orig_image = image
        self.image = image
        self.rect = self.image.get_rect(center=(x, y))
        self.position = Vector2(x, y)
        self.velocity = Vector2(0.0, 0.0)
        self.angle = angle
        self.length = length
        self.max_acceleration = 450
        self.max_steering = max_steering
        self.max_velocity = 220
        self.brake_deceleration = 150
        self.free_deceleration = 100

        self.acceleration = 0.0
        self.steering = 0.0
        self.camera = Vector2(0, 0)  # Assigned the camera as an attribute.

    def update(self, dt):
        self.velocity += (self.acceleration * dt, 0)
        self.velocity.x = max(-self.max_velocity, min(self.velocity.x, self.max_velocity))

        if self.steering:
            turning_radius = self.length / tan(radians(self.steering))
            angular_velocity = self.velocity.x / turning_radius / 2
        else:
            angular_velocity = 0

        vel = self.velocity.rotate(-self.angle) * dt
        self.position += vel
        self.camera += vel  # Update the camera position as well.
        # If you use the rect as the blit position, you should update it, too.
        self.rect.center = self.position
        self.angle += degrees(angular_velocity) * dt

        self.image = pygame.transform.rotozoom(self.orig_image, self.angle, 1)
        self.rect = self.image.get_rect(center=self.rect.center)

class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Project BrmBrm")
        width = 1280
        height = 720
        self.screen = pygame.display.set_mode((width, height))
        self.clock = pygame.time.Clock()
        self.ticks = 60
        self.exit = False

    def run(self):
        car_image = pygame.Surface((68, 43), pygame.SRCALPHA)
        pygame.draw.polygon(car_image, pygame.Color('dodgerblue1'), ((0, 0), (68, 20), (0, 41)))
        car = Car(car_image, *self.screen.get_rect().center)  # I center the car.

        while not self.exit:
            dt = self.clock.tick(self.ticks) / 1000
            # Event queue
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.exit = True

            # User input
            pressed = pygame.key.get_pressed()

            if pressed[pygame.K_UP]:
                if car.velocity.x < 0:
                    car.acceleration = car.brake_deceleration
                else:
                    car.acceleration += 890 * dt
            elif pressed[pygame.K_DOWN]:
                if car.velocity.x > 0:
                    car.acceleration = -car.brake_deceleration
                else:
                    car.acceleration -= 1 * dt
            elif pressed[pygame.K_SPACE]:
                if abs(car.velocity.x) > dt * car.brake_deceleration:
                    car.acceleration = -copysign(car.brake_deceleration, car.velocity.x)
                else:
                    car.acceleration = -car.velocity.x / dt
            else:
                if abs(car.velocity.x) > dt * car.free_deceleration:
                    car.acceleration = -copysign(car.free_deceleration, car.velocity.x)
                else:
                    if dt != 0:
                        car.acceleration = -car.velocity.x / dt
            car.acceleration = max(-car.max_acceleration, min(car.acceleration, car.max_acceleration))

            if pressed[pygame.K_RIGHT]:
                car.steering -= 20 * dt
            elif pressed[pygame.K_LEFT]:
                car.steering += 20 * dt
            else:
                car.steering = 0
            car.steering = max(-car.max_steering, min(car.steering, car.max_steering))

            # Logic
            car.update(dt)

            # Drawing
            self.screen.fill((30, 30, 30))
            # Now use the camera to adjust the positions of the game objects.
            screen.blit(BACKGROUND, -car.camera)
            self.screen.blit(car.image, car.position - (car.rect.width / 2, car.rect.height / 2)-car.camera)
            # You can blit the car at its rect.topleft position minus the camera as well.
            # self.screen.blit(car.image, car.rect.topleft-car.camera)
            pygame.display.flip()

        pygame.quit()

if __name__ == '__main__':
    game = Game()
    game.run()

```

I've also got an example on Stack Overflow in which I demonstrate how a smooth camera effect can be achieved in pygame.

---
Tags: python, pygame, racing
---


# Question
Title: The second double jump animation doesn't finish before the player touches the ground
I have an issue with double jump for the player my code is working but I want the second double jump animation finish(idle Animation: anim.SetBool("Jump", false)\] before he touches the ground can anyone help me on that here is my code :

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

public class PlayerMovement : MonoBehaviour
{
    private Animator anim;
    private float speed = 5f;
    private Rigidbody2D myBody;
    public Transform groundCheckPosition;
    public LayerMask groundLayer;
    private bool isGrounded;
    private bool jumped;
    private float jumpPower = 5f;
    private bool doubleJump;
    void Start()
    {
        myBody = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        isGrounded = false;
        jumped = false;
        doubleJump = false;
    }
    // Update is called once per frame
    void Update()
    {
        PlayerJump();
    }
    private void FixedUpdate()
    {
        CheckIfGrounded();
        PlayerWalk();
    }
    void PlayerWalk()
    {
        float h = Input.GetAxisRaw("Horizontal");
        if (h > 0)
        {
            anim.SetInteger("Speed", (int)speed);
            ChangeDirection(1);
        }
        else if (h < 0)
        {

            anim.SetInteger("Speed", (int)speed);
            ChangeDirection(-1);
        }
        else
        {
            anim.SetInteger("Speed", 0);
        }
        myBody.velocity = new Vector2(h * speed, myBody.velocity.y);
    }
    void ChangeDirection(int direction)
    {
        var temp = transform.localScale;
        temp.x = direction * (0.8f);
        transform.localScale = temp;

    }
    void CheckIfGrounded()
    {
        if (!Physics2D.Raycast(groundCheckPosition.transform.position, Vector2.down, 0.1f, groundLayer))
        {
            isGrounded = false;
        }
        else
        {
            isGrounded = true;
            doubleJump = false;
        }
        if (isGrounded)
        {
            jumped = false;
            anim.SetBool("Jump", false);
        }
    }
    void PlayerJump()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if ((isGrounded && !jumped) || (!doubleJump && !isGrounded))
            {
                jumped = true;
                doubleJump = true;
                myBody.velocity = new Vector2(myBody.velocity.x, jumpPower);
                anim.SetBool("Jump", true);
            }
        }
    }

}//class

```

## Edit

I have changed the code from that :

```
void Update()
    {
        PlayerJump();
    }
    private void FixedUpdate()
    {
        CheckIfGrounded();
        PlayerWalk();
    }

```

to that :

```
void Update()
{

}
private void FixedUpdate()
{
    CheckIfGrounded();
    PlayerJump();
    PlayerWalk();
}

```

I have changed it because FixedUpdate, we use it only for physics because it's not called every frame, unlike update function.

the problem is that the double jump doesn't work in this case can you explain me why?

# Answer
So I looked into your project and here's what the issue is:

```
    void CheckIfGrounded()
{
    if (!Physics2D.Raycast(groundCheckPosition.transform.position, Vector2.down, 0.1f, groundLayer))
    {
        isGrounded = false;
    }
    else
    {
        isGrounded = true;
    }
    if (isGrounded)
    {
        jumped = false;
        doubleJump = false;
        anim.SetBool("Jump", false);
    }
}

```

This snippet is being called every tick which means, it continuously checks whether the player is near the ground and when it is, it sets the *Jump* bool as false which then transistions from jump animation to idle.

**Why it works for single jump?**

The reason is that single jump is really short in terms of height, so as soon as you jump, by the time the jump animation finishes, you are already near the floor and the transition occurs. In double jump you are high enough that by the time the jump animation finishes, you are still far from floor, thus the transition doesn't happens.

**How to fix it?**

One way to fix it is by simply waiting for a few seconds when jumping and then as soon as the jump animation finishes, change the boolean so the transition happens from jump to idle. You can use Coroutines to achieve that.

Second way of fixing it is by removing the ongoing transition to jump like this:

and after that use Animator.Play(String StateName) just when the player jumps (Jump key is pressed). I Usually use the 2nd one but both should work.
> 0 votes

# Answer
I tried to get an answer by myself, tell me if I'm wrong or not.

**Update()** function runs at each frame so the **playerJump()** function is faster than the **checkifgrounded()** function so the value of **isgrounded** is still true because checkifgrounded() is not executed yet so the **jumped** and **doublejump** values are always false until the next execution of **checkifgrounded()** method, so the player jumps twice.

In the second case When we have moving the **playerjump()** method to **fixedUpdate**, in this case, the two methods **checkifgrounded()** and **playerJump()** are executed at the same time so there is no offset the **isgrounded** value is false as soon as we press space, so the player jump only once.
> 0 votes

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


title: How can I set AnimationCurve by script?

text:
# Question
Title: How can I set AnimationCurve by script?
In the top of the script:

```
public AnimationCurve curve;

```

Then the object in the editor have AnimationCurve but without any curve yet:

I want to set one of the curves via the script in the Start.

For example to select this one the most one in the right:

# Answer
In top of script:

```
public AnimationCurve curve;

```

In Start:

```
public void Start()
    {
      if(curve == null)
        {
          curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
        }
        curve.preWrapMode = WrapMode.Clamp;
        curve.postWrapMode = WrapMode.Clamp;
    }

```
> 0 votes

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


# Question
Title: Unity3D C# Drag object smoothly on it's x axis that's already bouncing
In my scene, I have a bouncing ball that collides with a cube. On each collision the ball returns to the same height. How can I get the ball to smoothly move along the x-axis by dragging my finger across the screen, while at the same time having no effect on the y or z values?

The y position is changing every frame depending on the state of the jump, so setting it's y position to transform.position.y in the Update function causes the movement to be jittery if the frame renders when it isn't caught up with the position of the ball.

Also, I set the interpolate value of the rigidbody to interpolate to get a smoother jumping motion, not sure if this is relevant to my problem or not.

Here is where I am at so far with little success. A few mobile games that replicate what I'm trying to achieve in terms of ball movement are Hop, Color Hop, and Splashy!

```
void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        // Control sliding using touch input.
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        transform.Translate(touchDeltaPosition.x * slidingSpeed, 0, 0);
    }
    transform.position = new Vector3 (Mathf.Clamp(transform.position.x, - xPosLimit, xPosLimit), transform.position.y, transform.position.z);
}

```

# Answer
You've almost got it. Given that you want the absolute position, I would switch from using the touch delta position to the touch position (absolute). I then normalized it and used your xPosLimit variable to determine the final xPosition.

Treat it as pseudocode tho, I wrote it from memory.

```
void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        // Control sliding using touch input.
        Vector2 touchPos = Input.GetTouch(0).position;

        //normalize the X coord (make it between 0 and 1), Y coord is irrelevant
        float normalizedX = touchPos.x / Screen.width;

        //interpolate between -xPosLimit and +xPosLimit by the normalizedX coord
        //no need to clamp it
        float xPos = Mathf.lerp(-xPosLimit, xPosLimit, normalizedX);

        //set the new position, leave Y and Z alone
        transform.position = new Vector3(xPos, transform.position.y, transform.position.z);
    }
}

```

**Update:** See comment below, the issue was solved with the above code AND by disabling interpolation on the rigidbody.
> 0 votes

---
Tags: unity, c#, 3d, game-mechanics, touch
---


# Question
Title: How to create temp folder to store a file from external directory and use it in a game
I would like to copy a 3D model from external library and save it in temp/Resources/StreamingAssets folder to instantiate an object in unity scene. \`

```
public class FBXOBJLoader : MonoBehaviour {

    string src;
    // Use this for initialization
    void Start () {
        src = EditorUtility.OpenFilePanel("Select Model", "", "fbx");
        //Output the Game data path to the console
        Debug.Log("Path : " + src);
        StartCoroutine("CopySomething");
    }

    IEnumerator CopySomething()
    {
        print("Start");
        string path;
        path = Application.temporaryCachePath;
        FileUtil.CopyFileOrDirectory(src,path);
        yield return null;
    }
}

```

It's creating some unknown file format in the asset folder. can anybody please help me to complete this task.

Thanks in advance

# Answer
The issue is that `Application.temporaryCachePath` returns the folder, you need the intended filepath. If you print it to the console it looks like this: `C:/Users/MyName/AppData/Local/Temp/SomeCompanyName/SomeProjectName`

Therefore, to fix the issue, change:

```
path = Application.temporaryCachePath;

```

To:

```
path = string.Concat(Application.temporaryCachePath, "/", Path.GetFileName(src));

```

Note, to use `Path.GetFileName` you must add `using System.IO` to the top of your script.
> 1 votes

---
Tags: unity, c#, 3d-modeling
---


title: Where to keep game images

text:
# Question
Title: Where to keep game images
I am new to gamedev, and I have one question about architecture. Where to locate game images? Should I keep this in the class object or in the main function and draw it depending on object variables?

# Answer
> 1 votes
There is no correct answer to this question. Fortunately, every programmer can choose any way to organise their project. You can follow the Object Oriented design, or you can pick something you think is better.

It is generally discouraged to put anything low-level in the main function, but it's not impossible to make something this way. Usually you'd want to go from high level to low level, so your main function should handle how the game runs (initialise libraries/tools, initialise the game itself, etc) then each part takes care of more and more details (the game itself contains images, and figures out how to display them).

But that's just one way to do it, there are design architectures out there, for different people. If you are doing this as a hobby, pick one that makes the most sense to you, and stick with it. If this is for a professional environment, learn the popular ones, so it's easier to work with other people.

---
Tags: architecture, software-engineering
---


# Question
Title: Changing transform of ParticleSystem makes it not play?
Unity 2018.2.9f1, only 1 script, there is no other code. The scene is very simple (I just started).

I'm working on a mobile game and I'm trying to play a particle effect at the tap location.

I managed to get the particle effect to play, but when I attempt to change `transform.position` the particle no longer displays at all. I see the TapEffect's GameObject X and Y coordinates being updated in the Editor, but the actual animation is not playing.

This is the script I have attached to my player, the particle is the only child of Player at the moment.

```
public class Player : MonoBehaviour {

    private ParticleSystem tapEffectParticle;
    private Vector2 touchPos;

    void Start () {
        this.tapEffectParticle = transform.GetChild(0).GetComponent<ParticleSystem>();
    }

    void Update () {
        if(Input.touchCount > 0) {
            Touch touch = Input.GetTouch(0);
            if(touch.phase == TouchPhase.Began) {
                touchPos = touch.position;
                tapEffectParticle.transform.position = touchPos;
                tapEffectParticle.Play();
            }
        }
    }
}

```

Here is a screenshot of the `TapEffect` Particle, default particle.

This is a view of the `Player` GameObject selected.

# Answer
> 0 votes
I managed to get this working, as DMGregory stated in the comments it had to do with local vs world simulation.

I fixed it this way but in all honesty, I don't understand WHY. Can someone please shed some light as to why we need to do this "Conversion":

```
if(Input.touchCount > 0) {
        Touch touch = Input.GetTouch(0);
        if(touch.phase == TouchPhase.Began) {
            touchPos = touch.position;
            tapEffectParticle.transform.position = touchPos;
            tapEffectParticle.Play();
        }
    }

```

with this

```
if(Input.touchCount > 0) {
        Touch touch = Input.GetTouch(0);
        if(touch.phase == TouchPhase.Began) {
            touchPos = touch.position;
            tapEffectParticle.transform.position = Camera.main.ScreenToWorldPoint(touchPos);
            tapEffectParticle.Play();
        }
    }

```

---
Tags: unity
---


# Question
Title: Why does order matter in constant buffers?
I have a rather peculiar question remaining after solving most of my own question on StackOverflow. When creating the constant buffers used by my shaders, I've learned that the order of variables between the `cbuffer` and the `struct` representing it have to be an accurate match. I am still unsure as to why this is such an issue, and that's why I'm here.

When creating a `cbuffer` to hold object data, I create the `cbuffer` and `struct` like so:

```
cbuffer ObjectBuffer : register(b0) {
    float4x4 World;
    float4x4 WorldViewProjection;
    float4x4 WorldInverseTranspose;
}
public struct ObjectBuffer {
    public Matrix World;
    public Matrix WorldViewProjection;
    public Matrix WorldInverseTranspose;
}

```

This way works just fine, but if I reorder the `cbuffer` variables, or the `struct` variables and do not reflect the changes in the other, issues arise and I can't even create the buffer.

```
cbuffer ObjectBuffer : register(b0) {
    float4x4 WorldInverseTranspose;
    float4x4 WorldViewProjection;
    float4x4 World;
}
public struct ObjectBuffer {
    public Matrix World;
    public Matrix WorldViewProjection;
    public Matrix WorldInverseTranspose;
}

```

---

In this case, the types are exactly the same and given the fact that `HLSL` expects constant buffers to be in 16 byte chunks; why does the ordering matter so much?

Aren't `float4x4` types the same as `Matrix` types where it's essentially an array of arrays?

```
[ 0, 0, 0, 0 ] = 16 bytes
[ 0, 0, 0, 0 ] = 16 bytes
[ 0, 0, 0, 0 ] = 16 bytes
[ 0, 0, 0, 0 ] = 16 bytes
[    TOTAL   ] = 64 bytes

```

Since a `float` is 4 bytes on its own, this would mean a `float4` is 16 bytes, and thus a `float4x4` is 64 bytes. So why does the order matter if the size remained the same?

---

## Update

So I've re-visited the issue and turns out I was wrong about the issue given above. This does allow the objects to be compiled correctly but presents grotesque effects in the shaders since the variables are in the wrong order which is expected.

However, this issue came up because I misread which buffer was causing the issue initially. It was all related to my material buffer in which I have a `bool` and a `float`. When I swapped the two on either side without reflecting the changes in the other it failed to create. I presume this is due to the difference in expected types. The `cbuffer` is in `bool-float` order while the `struct` is the opposite. This I expect to cause an issue, but it would still be nice to know what's happening under the hood to cause it to break. Is it because `bool` is a single byte but perhaps allocated into a chunk of 4 bytes?

# Answer
DirectX doesn't see your `struct`. When you set the uniform buffer all it sees is a bunch of bytes that it needs to map to the `cbuffer` definition in the shader. This is also why you may need to add padding between subsequent fields when alignments between the host language (C/C++/C#/etc.) and hlsl don't match. In particular when dealing with multi-float variables.

In effect it does a `reintepret_cast` on your `struct` to the one declared in the shader.

If the layout does not match then you get surprising behavior.
> 1 votes

---
Tags: directx11, hlsl
---


# Question
Title: How can I detect when the formations of units are broken? - Unity 2018.2.x
Sorry if I don't write this properly, this is my first post here. I am working in Unity 2018.2.xx I have an issue where the current solution for checking whether a squad formation is broken. For ease of explanation, it's easier to visualise in 2D space from a top-down perspective. currently, there is the Squad is tracked by its own class and is an empty game object. the units in the squad have their own unit class and pass data to the Squad controller when needed. i.e on the death of a unit, it tells the squad manager to remove itself from the squad

the Squad formation is tracked in a 2D array and for testing purposes, the squad was formed in a 3\*3 square as I tried to display below

```
o o o
o o o
o o o

```

what I need, is a way to detect when the squad is split into two, by the player killing/ removing units from the middle. i.e the squad on the left still has one unit in the middle, and when the unit in the middle column, the unit "breaks" and the remaining survivors scatter.

```
o o o    o x o
o x o    o x o
o x o    o x o

```

Currently, I am checking each column and making sure it isn't the start or end. Then, checking the row to see if there are still units in that column. if not, it runs the splitting functions.

so my question is, is there a better way to do this without going too complex with the approach

# Answer
> 0 votes
Perform a flood fill starting on an arbitrary unit and see if it covers all living units. When it does, the formation is still coherent.

The flood fill algorithm works like this:

1. Every unit can have one of three states: "dead", "visited" or "unvisited". At the beginning, all units have the state "dead" or "unvisited". I would recommend to create a local 2-dimensional array to represent these states.
2. Pick any "unvisited" unit as your starting point.
3. Mark the current unit as "visited"
4. For each neighbor-unit of the current unit check if it is "unvisited" and when it is, recursively call the algorithm from step 3 with that neighbor as the current unit.

When all the recursive call-chains return, then any units which are still "unvisited" do not have an unbroken connection to the unit you started with. As a side-effect, you also found a first connected sub-group. If you are interested in knowing all connected sub-groups, keep performing the above algorithm on the remaining units until they are all "visited" (some sub-groups might consist of only one unit).

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


title: Top down off-screen indicator

text:
# Question
Title: Top down off-screen indicator
I'm working on a top-down 3D game where things spawn off camera. Movement only occurs on 2 axis (x and z). Rotation is about y axis.

The player is in the center of the camera and needs to have indicators at the edge of the screen to show where the item is relative to the players location.

I've managed to figure out the distance from my player to the target just using the distance between 2 Vector3 points.

However, I can't figure out how to translate this into a direction/angle for an indicator arrow that I have instantiated as a child of the canvas UI and make it point to the edge of the screen.

# Answer
> 1 votes
use the arctangent to find the angle

```
angle = Mathf.Atan2(z2-z1), x2-x1) * Mathf.Rad2Deg;

```

The output is in Radians, so multiplying by `Rad2Deg` converts it to degrees for you.

this will result in an angle in the range (-180, 180\] degrees. If you need it from (0, 360\], then just add:

```
if (angle < 0) angle += 360;

```

---
Tags: unity, c#, geometry, angles, top-down
---


# Question
Title: Player object's model starts to shake after some time
I created a default scene in a new project and imported a model from Unity's asset store and then get this strange behavior of the model starting to shake for no reason after some time after starting the game.

I also have a script to read keyboard input and then apply forces to the model when the player presses some keys but the shaking of the model starts to happen even when the player does absolutely nothing.

I'm really confused and have no idea where to look for a problem and google doesn't seem to have a solution to this either.

# Answer
> 0 votes
OK, I figured it out. I noticed the Y coordinate for the object was dropping when in game. I forgot to switch off "Use Gravity".

I'm creating a space-shooter game and didn't have any points of reference to see that my player object was falling. And once the Y coordinate reaches values below -10000 units the precision drops (not enough digits for the fraction) so the translation now cannot be shown smoothly and instead looks like the model is "shaking".

---
Tags: unity, rendering, models, 3d-modeling
---