# Question
Title: How can I create a radial animation that hollows out a shape from the inside?
I want to create the radial/circular animation seen in the explosions in this .gif of Flat Heroes.

I made an image using Illustrator of a radial ring (as below), but I'm not sure if this is the right approach. How can this be done?

Also, I would like to know how this could be extended to make similar animations for other shapes like squares and triangles.

# Answer
> 8 votes
For a circular cutout we can do this with a little radius math and no textures at all. But since you mention wanting to extend to squares and triangles, I'll show a more general approach.

First we create a texture in the shape we want, with a gradient falloff toward the interior. This gradient should follow the shape of the perimeter - we'll use it to control the shape of the inner cutout. For a circle, this can be a simple radial gradient.

Next we write a shader that reads this texture, as well as a threshold parameter, and displays only parts of the gradient that are brighter than the threshold as opaque, and everything darker as translucent, like so:

```
Shader "Unlit/RadialParticle"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        // Treat this material as transparent
        Tags { "RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True" }
        LOD 100

        // Set up alpha blending
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                // Vertex color field
                // (used by the particle system to tint)
                fixed4 color : COLOR0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                // Pass through color information to fragment
                fixed4 color : COLOR0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                // Pass our color parameter through to the fragment
                o.color = v.color;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                // Hide any part of the image that's darker than
                // the _Cutout parameter
                col.a = saturate((col.r - i.color.a) * 10.0f);

                // Replace the visible color of the image
                // with the particle color
                col.rgb = i.color.rgb;

                return col;
            }
            ENDCG
        }
    }
}

```

Attach your shader to a material and configure it with your gradient texture and you're off to the races. :)

Here I've configured the shader to work in a particle system, reading the threshold from the vertex colour's alpha channel. That let me use the particle system's "Color Over Lifetime" curves to create the animation above quickly.

If you need to do this with just a single quad, you could instead expose `_Cutout` material parameter, and vary that material property via script.

```
Shader "Unlit/RadialSprite"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Color ("Color", Color) = 1, 1, 1, 1
        _Cutout ("Cutout", Range(0, 1)) = 0.5
    }
    SubShader
    {
        // Treat this material as transparent
        Tags { "RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True" }
        LOD 100

        // Set up alpha blending
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            // Add shader variables for our material properties.
            fixed4 _Color;
            float _Cutout;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                // Hide any part of the image that's darker than
                // the current alpha value of the particle color
                col.a = saturate((col.r -_Cutout) * 10.0f);

                // Replace the visible color of the image
                // with the material color
                col.rgb = _Color.rgb;

                return col;
            }
            ENDCG
        }
    }
}

```

In my examples all the displayed colour is coming from the particle system / material parameters, but you could just as easily have colour detail in your texture, and store the cutout gradient in the alpha channel.

---
Tags: unity
---


# Question
Title: Why are .xnb files used rather than source files?
XNA and Monogame are built using a content pipeline, which takes source files (images, sound effects, 3D models, etc.) and converts them to proprietary .xnb files. What's the benefit of doing this as opposed to simply loading source files directly?

To be clear, I'm not asking **how** to use the content pipeline. Just why .xnb files are used in the first place.

# Answer
It is much simpler to only support a single format at runtime.

A lot of formats just are not suited for quickly loading in the asset it contains. For example wavefront obj is a horrible format for that.

Doing the heavy lifting of conversion just once during build means that while the player is waiting on you to start showing stuff you are not doing dumb busywork of decompressing files, parsing text, ...
> 3 votes

---
Tags: xna, monogame, xna-content-pipeline
---


# Question
Title: Array with multiple linked objects in Unity
This might be too primitive, but for my use case, I need to maintain an array in which two attributes are linked to each other... For example - If I want to do Score gathering... Then I need an array which has scores and corresponding player names as each element.

So, when I do `Array.Sort(PlayerScorearray)` I even need the playername to be sorted in the order so that if I want to know the player with lowest score, I just go for the first element and then go to the corresponding player name.. Is it possible to do it in a simpler way? My mind can't think of a simple way to do this.

Edit : I am using C# for scripts

# Answer
> 0 votes
Two ways to do this:

1. Make a tuple type that combines both pieces of information

`public struct ScoreEntry {
 public string playerName;
 public float score;
 }`

Then you can sort them using a custom comparer, like so:

`Array.Sort(scoreEntries,
 (ScoreEntry a, ScoreEntry b) => { return a.score - b.score; } );`

Or, to be more concise, you can make your ScoreEntry implement IComparable so that the default Sort knows how to sort them without this helper. ;)
2. You can use the Array.Sort overload that takes two arrays and sorts them in parallel:

`Array.Sort(scores, playerNames);`

(In my experience, this method is not very efficient, but your mileage may vary)

Both these strategies are easily found by reviewing the MSDN documentation on sorting or doing a simple Google search (sorting is a pretty bread-and-butter operation, so there's tons of information out there about how to tackle it) - so please don't neglect to do your own research.

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


# Question
Title: Debugging an AMD GPU specific problem without an AMD GPU
I've recently started to receive reports from users that I game I'm working on isn't rendering properly on AMD GPUs. I'd like to track down the problem and fix it, but I'm a hobby developer just using my own computer and I don't have an AMD GPU.

Do I have any options here besides going out and buying another graphics card? Perhaps some sort of emulator or a cloud compute service with AMD GPUs? I've looked at the major cloud compute providers (AWS, Google Cloud and Azure) but they all seem to offer only Nvidia GPUs.

# Answer
> 4 votes
No. You will need to find a computer with a matching GPU to test.

You can sometimes get previous-generation graphic cards for cheap (that often still exhibit the same problem) if you ask **small computer repair store** nicely for a few **old, used GFX cards**.

They often have some left from customer upgrades that they can't sell because the cards are too old.

Another source are **flea markets and classified ads** for used computers and parts.

Maybe your **local public library or school** uses the GPU brand you need and let people run software off USB sticks. They may have rules against that (for good reasons); Check with the library first and **don't run the game back on your computer** from the USB stick: If they let anyone run any software **you don't want to get any viruses back from that computer**.

Other than that look into your **personal contacts** or maybe one of **your customers** is willing to help.

If it's a shader issue you can make a unit test with just the shader in question to iterate on the issue faster. One might be tech-savvy enough to edit the shader themselves.

Yet another source if there is one in your area would be your **local game developer meet up / dev jam session.**

Maybe some people at a **local LAN party** would be willing to help.

---
Tags: debugging, amd
---


# Question
Title: Where should I put the code for objects interactions?
I'm working on a 2D puzzle game, and one of the features is the ability to push crates so you can climb on top of them to get to a destination.

I've tried many things to get this to work but none of them succeed.

My main problem is that I don't know where to put my code. For example, I don't want to handle the movement of the crate in the player class because that wouldn't be neat, the same way some people say something along the lines of "If you're making chess, the rules of the pawn and knight shouldn't be in the rules of the queen".

If anyone has an answer or could provide a pseudo-code explanation it would be appreciated.

# Answer
The short answer is a physics system. I job usually is to handle collisions in a believable way, among other tasks. Many game engines have this build in.

Long answer is that you have to add conditions to your movable objects, so that when objects collide with them a force is applied to them ( or at least they move with the them). This can be simple or complex depending on the rest of your project. This would all happen in the update() part of the standard game loop.
> 1 votes

# Answer
Your physics code is responsible for detecting collisions. Once detected, you need to respond to the collision, based on the "types" of A and B.

This is called "double dispatch" and Scott Meyers discusses it in More Effective C++.

Personally I use a more C-style approach to collision response, and use a simple bit-field to denote the type of object.

I look up a collision handler for (A,B) and if its not available, see if there is one for (B,A). Once found, use that one (\*). If there is no special handler set for this type combo, just call a generic response function that pushes the colliding objects apart with contact joint.

This way, you can define a handler for (barrel, player) and another one for (barrel, barrel) for instance. A handler for (player, powerup) would typically remove the powerup without affecting the physics of the player, play a sound, and reward the player.

I simply keep an array of these handlers, and search it every time two objects collide. The response function will reside outside both Barrel:: and Player:: objects. The downside is that it does need to know about both Barrel and Player, and thus will typically include the headers for both.

(\*) Alternatively, you could always sort A and B, so you know whether to look for A,B or B,A.
> 1 votes

---
Tags: c++, architecture
---


# Question
Title: LWJGL Wait for key press in a single method
Currently I am implementing the possibility in my game to change the keyboard configuration.
Therefor, I have a menu in which is a button for each action the player can do. If the player clicks on one of these buttons, the game should wait until the player hits a key on the keyboard.

But this is my problem. I have no idea how to wait for a keypress. I tried to do something like:

```
while(!Keyboard.next()){}
// Now there should be events. Just get the key of the last event.

```

But it did not work and ended with an infinite loop.
The problem is, it has to work in a single method, as it is the onClick method of the button.

Does somebody know a way to handle this problem correctly?
And how is this done usually? (I have seen such functionality in some games)

# Answer
As I'm sure you found: `while(!Keyboard.next()){}` would just wait forever, since `Keyboard` is not getting updated during the wait.

In your `OnClick` function, I'd store the action that's being set. Then, when entering your update loop, check to see if you're waiting for an action. If you are, check for a keypress. Something like:

```
//check for cancel (like clicking a separate action)
if(actionToSet != null) {
    if(Keyboard.hasNext()) {
        //check to make sure key pressed is not cancel set action key (like ESC)
        actionToSet.bind(Keyboard.getNext());
    }
}
//do other stuff

```
> 2 votes

# Answer
Thanks to MichaelHouse for his suggestion, but what I actually found works (since those methods he suggested didn't appear to exist for the Keyboard class I had), is to set a boolean `waitingToSet` and in my update method, I had this:

```
    if (waitingToSet){
        if (Keyboard.getEventKeyState()){
            System.out.println(Keyboard.getKeyName(Keyboard.getEventKey()));
            waitingToSet = false;
        }
    }

```

This worked perfectly for me. Of course you can just then go and bind that `Keyboard.getEventKey()` returned value as the setting you want.

EDIT: Just a caveat: if you're planning on using this with LibGDX, it won't work properly. The Integer values for the `Keyboard` class and the `Input.Keys` field are different, so calling `Gdx.Input.isKeyPressed(i)` where `i` is the int value you caught earlier, will map to the wrong key. It turned out to be a huge mission for me to get new key mappings to work properly for LibGDX. Ended up using a `Preferences`file and writing my own method that looped through every possible Key and/or button to return the proper one:

```
public static int getKey(){
    for (int i=0;i<256;i++){
        if (Gdx.input.isKeyJustPressed(i)){
            return i;
        }
    }
    return -1;
}

```

This worked perfectly. So change the `Keyboard.getEventKeyState()`to `Gdx.input.isKeyJustPressed(Input.Keys.ANY_KEY)` and then call the above method inside the if statement. Then you'll have the right key.
> 1 votes

---
Tags: java, lwjgl, input, gui, keyboard
---


title: First-person shooter -style controls

text:
# Question
Title: First-person shooter -style controls
This is not in regard to a video game, but to a 3D model viewer someone else created and I am modifying.

I would like to implement first-person -style mouse and keyboard controls in the viewer, so that you can navigate through the model as if it were a house or building.

Right now, when you move the mouse up, down, left or right, the rotations are relative to the camera's coordinate axes. Which means over time you can end up with some really weird camera positions.

How do I change this to FPS-style rotations where (I think) you use latitude/longitude rotations, and the "up" direction is always perpendicular to the ground plane.

Is there a simple conversion formula I can use on the mouse input? Thanks!

(BTW, I've already implemented correct lateral camera translation. The only issue remaining is the camera rotation.)

\[edit\]

The article below describes my problem well, but does not provide a solution I can use since I am not using Unity.

I'm rotating an object on two axes, so why does it keep twisting around the third axis?

\[edit\]

Here is the function I am trying to edit. Most of it is not relevant, but you can browse through it to see what's going on. The only part I really want to change is the line with the comment "fix rotations here!!".

```
void LDrawModelViewer::updateCameraPosition(void)
{
    float multiplier = 100.0f;
    float factor = 1.0f / multiplier;
    TCFloat motionAmount = 20.0f * (TCFloat)sqrt(fov / 45.0f);
    /*
    if (modifierKeys & MKShift)
    {
        motionAmount *= 2.0f;
        strafeAmount *= 2.0f;
        rotationAmount *= 2.0f;
        rollAmount *= 2.0f;
    }
    */
#ifdef WIN32
    if (hrpcFrequency.QuadPart != 0)
    {
        LARGE_INTEGER newCount;

        QueryPerformanceCounter(&newCount);
        factor = (float)((newCount.QuadPart - hrpcFrameCount.QuadPart) /
            (double)hrpcFrequency.QuadPart);
    }
    else
    {
        factor = (GetTickCount() - frameTicks) / 1000.0f;
    }
#endif // WIN32
#ifdef _QT
    factor = qtime.elapsed() /1000.0f;
#endif
#ifdef COCOA
    if (FRAME_TIME != nil)
    {
        factor = (float)-[FRAME_TIME timeIntervalSinceNow];
    }
#endif // COCOA
    if (viewMode == VMFlyThrough && flyMode == FMUpSide)
    {
        TCVector upVector(0.0f, -1.0f, 0.0f);
        TCVector tempMotion(0.0f, 0.0f, 0.0f);
        TCFloat matrix[16];
        TCFloat inverseMatrix[16];
        TCVector::invertMatrix(camera.getFacing().getMatrix(), inverseMatrix);
        TCVector::multMatrix(inverseMatrix, rotationMatrix, matrix);
        TCVector tempVector = upVector.transformNormal(matrix);
        if (cameraMotion[2] > 0.0f)
        {
            tempMotion[1] += -tempVector[2];
            tempMotion[2] += tempVector[1];
        }
        else if (cameraMotion[2] < 0.0f)
        {
            tempMotion[1] += tempVector[2];
            tempMotion[2] += -tempVector[1];
        }
        if (cameraMotion[1] > 0.0f)
        {
            tempMotion[1] += (1 - tempVector[2]);
            tempMotion[2] += (1 - tempVector[1]);
        }
        else if (cameraMotion[1] < 0.0f)
        {
            tempMotion[1] += -(1 - tempVector[2]);
            tempMotion[2] += -(1 - tempVector[1]);
        }
        tempMotion[0] = cameraMotion[0];
        camera.move(tempMotion * motionAmount * factor * multiplier);
        // fix rotations here!!
        camera.rotate(TCVector(cameraXRotate, cameraYRotate, cameraZRotate) *
            factor * multiplier * 1.5f);
    }
    else
    {
        //camera.move(cameraMotion * size / 100.0f * factor * multiplier);
        camera.move(cameraMotion * motionAmount * factor * multiplier);
        camera.rotate(TCVector(cameraXRotate, cameraYRotate, cameraZRotate) *
            factor * multiplier * 1.5f);
    }
}

```

\[edit\]

~~On a hunch, I changed that line to this:~~

~~```
    // Form a view vector using total pitch & yaw as spherical coordinates.
    TCVector globeVector
    (
        cos(cameraXRotate) * sin(cameraYRotate),
        sin(cameraXRotate),
        cos(cameraXRotate) * cos(cameraYRotate)
    );
    camera.rotate(globeVector * factor * multiplier * 1.5f);

```~~

~~But this did not have the desired effect.~~

\[edit\]

~~Okay, I replaced the previous code with:~~

~~```
    TCFloat identity[16];
    memcpy(identity, TCVector::sm_identityMatrix, sizeof(TCVector::sm_identityMatrix));
    TCVector::calcRotationMatrix(cameraXRotate, cameraYRotate, identity);

```
But I get an error that `TCVector::sm_identityMatrix` is inaccessible.<br>~~

~~Also,~~ how do I feed the new matrix back to the camera? The `camera.rotate` method only takes a three component vector as input AFAIK. I was unable to locate any documentation on the `camera` object, and the code has few comments in it.

# Answer
You need a conversion matrix from world space to local space. So you can rotate the camera from the clients view (local space).
> -1 votes

---
Tags: camera, rotation, first-person-shooter
---


# Question
Title: Realistically, how long would it take for 1 person to create a 2D isometric RPG?
Something I have been looking into for a while is developing my own PC game. I'm very into CRPGs like Fallout 1 and 2, UnderRail, Wasteland 2, etc. I have long desired to create my own game like this, with an emphasis on plot.

While I don't have any experience in development, I use several (mostly proprietary) programming languages in my job, and have a natural aptitude for learning syntax etc. I have taken a few tutorials in Unity and Godot but generally I prefer to feel my way through software myself (tutorials rarely give you enough 'why and how') or reverse engineer an existing product.

I plan for the game to be quite minimal on the asset front, at least to begin with. I've done some basic 3d modelling and mapping (a long time ago, in Source engine - I built my school!)

My question is, if I decide to dedicate the time to this, how long does it generally take for one person to create a game like UnderRail or Darklands? I'd like to know if it's a doable project or a laughable pipe dream for an inexperienced one-man enthusiast!

# Answer
**WARNING**: this answer can be depressing. It can be depressing in two fronts: A) Our tools and data on software (size and time) estimation are not that good, and B) It probably will take longer than you think.

Positive aspect: expending extra time studying and familiarizing with development tools is probably always a good idea. Up to what extend it is unclear. Yet, one of the best ways to do it is by using those tools, for example to develop a game. If you do not expect this game to be your final game, but one you do to learn, you will be good.

---

I will take for reference the case of a single developer working on Underrail engine and alpha game: Dejan Radisic. This was from 2008 to September 2012, at which point it went on steam early access (there were a few prereleases before), which game him money to hire some help, and the final version was completed on December 2015.

Therefore, Dejan Radisic worked for about four years alone, and then there were three more years working in a team. It is unclear how much it would have taken him to complete the task alone.

Consider that new people on the team would have required Dejan Redisic to teach them how to work with the engine and familiarize them with the code base, during this phase we would expect his output to be lesser because he is giving time to train the other developers. After this initial phase (which I have no idea how much it took, or how relevant was its impact) we would expect the team to have some level of synergy, meaning that their output would be greater than if they were working on it independently. Furthermore, some tasks cannot be broken apart, and adding many developers will not make them any faster.

*See: The Mythical Man-Month.*

---

Next, we know that the output of a developer is roughly stable in terms of lines of code per unit of time, regardless of language. It can be improved by incentives (although the effect of incentives plateaus) and better tools and training. This is good news for high-level languages and tools, because using high-level languages will allow you to finish your work in less time. Furthermore, we know that number lines of code is the best predictor for software defects. Thus using a language that allows you to accomplish more with less lines of code (or an engine that allows you accomplish so much, with even less) are good in terms of software quality and developer output.

Of course, everything is a tradeoff… using high-level tools means that you will have less control over the performance. As a result, you may end with a game done in less time, with less defects… but that runs too slow.

*See: Making Software: What Really Works, and Why We Believe It \- see also: Greg Wilson - What We Actually Know About Software Development, and Why We Believe It’s True.*

Note: We do not know how you compare to Dejan Radisic. Assuming that you are as bad (or good) as Dejan Radisic will result in a wrong estimation. Yet, I cannot control for this.

Addendum: We also do not know how many hours per day did Dejan Radisic put into the development.

---

Considering all that. Creating a game like Underrail, for a single developer should take **somewhere from 4 years to 13 years** (at the end Underrail was a team of 3 people for 3 years, plus the 4 solo years... 3\*3+4=13; and I know that estimation is wrong because of The Mythical Man-Month).

Do you know Hofstadter's law? - The truth is that the majority of software development projects fail their estimation. We know that agile methodologies are arguably better; we can attribute this to the steady adjustments they do to their estimation during development. A common practice in agile teams is to multiply the estimation they get by some arbitrary factor... because *It always takes longer than you expect* (see Standing Group's CHAOS Report). In fact...

*Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.*

Therefore, I may pick the arbitrary factor 3 and multiply our estimation to get a total time of **12 to 39 years**. Then Hofstadter's Law.

---

On the other hand, most of that time is expend into creating a custom engine. If you use an existing engine instead, it will probably save you around 3 to 9 years of work.

If you use free art assets, or can get somebody to work on the art assets (sound, music, graphics, etc...) I would expect it would save you... ern... some time. It is hard to compare making assets with programming; also, the amount of work depends on how heavily your game depends on art assets. Let us say it is 50% of the time, just to be politically correct.

Now, if we start on 39 years, we take 9 years off, and half the time, we have: (39-9)/2 = **15 years**.

---

Note: I base the above on what we know about software engineering and a single data point: Dejan Radisic working on Underrail. Do not consider this single data point statistically relevant. We also know that software estimation is susceptible to psychological anchoring (that is, given a guess estimate, even professional and well-trained engineers will yield estimates that approach the guess estimate given).

---

Finally, consider the Wait Equation\[1\]. We are steadily getting better developer tools and reusable software that will allow you to develop a similar product in less time. Therefore, there is an ideal wait time that optimizes the total time to finish a development task by taking advantage of the improvements in the technology.

It might be the case that it took Dejan Radisic three to four year to work on the game engine simply because the tools available at 2008 were not as good as those you find today. I do not think we have enough data to calculate the how much time you will save by just waiting to start your project (and taking that time to study software development and familiarize yourself with a variety of tools) by merit of improvement in existing tools and you getting better as developer.

\[1\]: The Wait Equation is the formula for the wait calculation proposed by Andrew Kennedy in his paper Interstellar Travel - The Wait Calculation and the Incentive Trap of Progress. The underlying idea is that given the improvements in travel technology, for a given arrival date to a destination there must be an ideal departure moment. Since tha article in Wikipedia has been proposed for deletion since I wrote this answer here a mirror, and two YouTube videos that mention it for context: The Race to a Habitable Exoplanet - Time Warp Challenge | Space Time and Will We Ever Visit Other Stars?.

---

Addendum: If you did pay attention, I told a lot of reasons why these estimations are wrong.
> 6 votes

# Answer
Doing a prototype could be a good idea in your case. Do it as small as possible, like a single room with one NPC, a little bit a dialogue and/or combat.

This will let you:

* Try out the underlying technology and learn
* Spot some issues you may not have thought of
* Get an idea of the amount of work involved

After this you can scope your full game based on what you want the final result to be and how much time you are willing to commit.

Building a full game as a one person team generally takes months even for an experienced developer, maybe even years. The usual advice is to start small. You can always expand more on a small game later - maybe that first prototype evolves all the way into a final product. Or you start a fresh one making use of all the skills you learned building your first small game. The important thing at your stage (and I believe the only way to truly answer your question) is starting to develop something.
> 2 votes

---
Tags: game-design, time-management
---


# Question
Title: What approaches are there to re-designing 8/16-bit sprites for HD?
I'm new to game development, and my skills with Photoshop are not that great.

I was planning to try to convert a old game to HD, but for this I need HD sprites. What is a good way to approach converting 8/16 bit sprites into something like HD? I mean something like this:

# Answer
you could try waifu 2X thing is youll have to make all the sprites look antialised first. find a way to size them up using the other methods people already mentioned, then re scale them down using Berlinier sampling, and then upload it to http://waifu2x.udp.jp/ and youll be happy

legit what i got it to do, to the donkey Kong game over screen.
> -5 votes

---
Tags: sprites
---


title: Collision event function not running

text:
# Question
Title: Collision event function not running
I am recreating flappy bird as a quick project to help me understand the ins and outs of unity. However I have hit a road block. When the bird collides with the pipe or ground it is not kicking off the `void onCollisionEnter2D(Collision2D target)`

The Bird, the pole, and the ground are not triggers. They are all tagged correctly. Here is my code for the onCollisionEnter2D function.

```
    void onCollisionEnter2D(Collision2D target)
{
    Debug.Log("Entered 2D Collision");

    if (target.gameObject.tag == "Ground" || target.gameObject.tag == "Pipe")
    {
        if (isAlive)
        {
            isAlive = false;
            anim.SetTrigger("Bird Died:");
            audioSource.PlayOneShot(deadClip);
        }
    }
}

```

Even my debuging code is not being reached. So I am stuck as to why this function isn't being executed when the bird collides with the pole or ground. They both all have 2D collision boxes on them.

# Answer
It's `OnCollisionEnter2D`, not `onCollisionEnter2D`. See the docs here.
> 2 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: Efficient Rendering for multiple light sources
I'm building a 3D rendering engine using C++ and OpenGL.

Right now, I've added support for multiple light sources in my GLSL shaders, but I've hit a bit of a bump for my rendering methods.

I'm worried about my engines performance if it has to render a lot of objects for a lot of light sources.

The straight-forward approach would be something like this:

```
for every object to be rendered
    closestLights []

    for every light in the scene
        if (light closer than all lights in closestLights)
            swap furthest light from closestLights with current light

    loadLightSourcesToShader(closestLights)

    renderObject(object)

```

However, I'm afraid the performance of this rendering-loop will degrade quickly since when either the amount of lights or the amount of objects increases, the amount of calculations will rise even quicker.

1) Is there any way to circumvent this?

2) How is this implemented in 'real' engines?

3) How can I find the closest K lightsources to an object efficiently?

I've heard about kd-trees and octrees, but I feel like building a tree everytime I render is probably worse than what I'm thinking about doing right now.

4) I could keep an octree and a kd-tree for every object (which keeps track of all other objects), which when using (smart) pointers, could be quite efficient in terms of time (but not space?).

Is this a good approach?

I know the saying 'Premature optimization is the root of all evil', but I'm pretty sure this WILL become a problem when a game/program reaches a certain complexity/size.

# Answer
> 2 votes
There are, broadly speaking, two common ways to handle lots of light sources.

1. Deferred techniques involve rendering some or all the information you need about your scene for lighting to render targets. For example, you may need normals, position (calculated usually from depth) and colour, each with their own render target. Then each light is drawn as a simple shape encompassing the light's range, and in the shader it uses the corresponding colour, normals, position from those render targets to add its influence to the rendered scene. This has been popular for a long time as it makes it easy and efficient to have a lot of lights in view, but doesn't easily support transparent objects or anti-aliasing. It also gets more difficult or expensive to support more material properties.
2. Forward shading is the more traditional rendering, where an object's shader determines how it looks on screen, rather than outputting properties to a variety of render targets as in deferred shading. Different materials can handle lights differently, and transparency and anti-aliasing are straightforward. But handling an arbitrary number of lights is more difficult. Recent techniques include Forward+ and Clustered Shading, which are variations on the idea that a low-resolution texture can be prepared each frame, containing information about which lights might affect the corresponding section of the screen. Shaders can access this information by looking up the fragment's screen coordinates in a texture or two, and looping through the lights that affect that portion of the screen.

Forward+ and Clustered Shading are increasingly popular, with games like DOOM (2016) and Just Cause 3 using the latter to great effect.

I name those two games specifically, because they both have excellent resources available online detailing their lighting.

---
Tags: opengl, c++, rendering, lighting, optimization
---


title: Falling through the ground

text:
# Question
Title: Falling through the ground
I spawn my player he falls hits the ground and starts falling through it slowly. Code:

```
 package com.pumkinmelon.Systems;

 import com.badlogic.ashley.core.ComponentMapper;
 import com.badlogic.ashley.core.Entity;
 import com.badlogic.ashley.core.Family;
 import com.badlogic.ashley.systems.IteratingSystem;
 import com.badlogic.gdx.graphics.OrthographicCamera;
 import com.badlogic.gdx.maps.MapLayer;
 import com.badlogic.gdx.maps.MapObjects;
 import com.badlogic.gdx.maps.objects.RectangleMapObject;
 import com.badlogic.gdx.maps.tiled.TiledMap;
 import com.badlogic.gdx.math.Rectangle;
 import com.badlogic.gdx.math.Vector2;
 import com.pumkinmelon.Components.HitBox;
 import com.pumkinmelon.Components.Player;
 import com.pumkinmelon.Components.Position;
 import com.pumkinmelon.Components.Velocity;

 public class CollisionSystem extends IteratingSystem {

    ComponentMapper<HitBox> Box;
    ComponentMapper<Position> Pos;
    ComponentMapper<Velocity> Vel;
    ComponentMapper<Player> Player;

TiledMap map;

private OrthographicCamera cam;

public CollisionSystem(TiledMap map, OrthographicCamera cam) {
    super(Family.all(HitBox.class, Position.class, Velocity.class).get());

    Box = ComponentMapper.getFor(HitBox.class);
    Pos = ComponentMapper.getFor(Position.class);
    Vel = ComponentMapper.getFor(Velocity.class);
    Player = ComponentMapper.getFor(Player.class);

    this.map = map;
    this.cam = cam;
}

@Override
protected void processEntity(Entity e, float dt) {
    HitBox box = Box.get(e);
    Position pos = Pos.get(e);
    Velocity vel = Vel.get(e);
    Player player = Player.get(e);

    Vector2 Topright = new Vector2(box.rect.x + box.rect.width, box.rect.y + box.rect.height);
    Vector2 bottomleft = new Vector2(box.rect.x, box.rect.y);

    MapLayer collisionObjectLayer =  map.getLayers().get(1);
    MapObjects objects = collisionObjectLayer.getObjects();

    for (RectangleMapObject rectangleObject : objects.getByType(RectangleMapObject.class)) {
        Rectangle rectangle = rectangleObject.getRectangle();

        if(player.falling) {
            if(rectangle.contains(bottomleft)) {
                vel.velY = 0;
                player.falling = false;
                player.canjump = true;
                player.falling = false;
            }
        }

        if(!player.falling) {
            if(!rectangle.contains(bottomleft)) {
                player.falling = true;
            }
        }

        if(rectangle.contains(Topright)) {
            vel.velX = 0;
        }
    }

    cam.position.x = pos.pos.x + box.rect.width / 2;
    cam.position.y = pos.pos.y;

    box.rect.x = pos.pos.x;
    System.out.println(box.rect.x);
    box.rect.y = pos.pos.y;
    System.out.println(box.rect.y);
    System.out.println("falling " + player.falling);
    System.out.println("Can Jump " + player.canjump);

  }

}

```

.

```
package com.pumkinmelon.Systems;

import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.pumkinmelon.Components.Player;
import com.pumkinmelon.Components.Position;
import com.pumkinmelon.Components.Velocity;

public class VelocitySystem extends IteratingSystem {

ComponentMapper<Velocity> Vel;
ComponentMapper<Position> Pos;
ComponentMapper<Player> Player;

float G = -15f;

@SuppressWarnings("unchecked")
public VelocitySystem() {
    super(Family.all(Velocity.class, Position.class, Player.class).get());

    Vel = ComponentMapper.getFor(Velocity.class);
    Pos = ComponentMapper.getFor(Position.class);
    Player = ComponentMapper.getFor(Player.class);

}

@Override
protected void processEntity(Entity e, float dt) {
    Velocity vel = Vel.get(e);
    Position pos = Pos.get(e);
    Player player = Player.get(e);

    if(player.falling) {
        vel.velY += G * dt;
    }
    else vel.velY = 0;
    System.out.println("Falling velSystem " + player.falling);

    pos.pos.y += vel.velY;
    pos.pos.x += vel.velX;

    System.out.println("posY" + pos.pos.y);
    System.out.println("velY" + vel.velY);

  }

}

```

I think the problem is that when i check for collision i check too many rectangles. I'm i right?

If i am or not i can't fix this i have tried for so long.

# Answer
I believe it is as you say, you check for too many rectangles, specifically you check rectangles, presumably find one that sets `player.falling` to `false`, then you keep checking rectangles and you find one that is not directly under the player which sets `player.falling` to `true`.

So what you want to do is stop checking rectangles if you find one under the player. You can use the `break` keyword to do that like so:

```
if(player.falling) {
    if(rectangle.contains(bottomleft)) {
        vel.velY = 0;
        player.falling = false;
        player.canjump = true;
        player.falling = false;
        break;
    }
}

```

When the `break` line runs the `for` loop stops immediately and the next line after it is executed. In this case, `cam.position.x = pos.pos.x + box.rect.width / 2;`.

## Edit

You essentially want the player to fall unless there's a block under them right? Looking at the code some more, I think you can simplify by removing these lines:

```
if(!player.falling) {
    if(!rectangle.contains(bottomleft)) {
        player.falling = true;
    }
 }

```

and adding `player.falling = true;` just before the `for` loop. In that case, the `if(player.falling)` check is unnecessary, (keep the part inside it of course).
> 0 votes

---
Tags: java, libgdx, collision-detection, physics, platformer
---


# Question
Title: Why do my sprites jitter when moving diagonally?
I am working on an low resolution, isometric, pixel game in which several objects move from tile to tile. I do this with this simple interpolation:

```
let percent = elapsedTime / SPEED

vec.x = start.x + ( (dest.x - start.x) * percent )
vec.y = start.y + ( (dest.y - start.y) * percent )

```

This seems to work fine except when moving diagonally. It starts to jiggle pretty heavy. Is there a way to smooth this out?

I am using a 32x16 tile size.

edit: added video for better understanding: (video deleted)

edit: for anyone interested. I've solved it using this:

```
let
percent = elapsedTime / SPEED,
num = Math.round( (dest.x - start.x) * percent )

vec.x = start.x + num
vec.y = start.y + Math.floor(num / 2)

```

This works only for diagonal movement with 1:2 ratio tiles. I also added some stuff to make it work for all 4 diagonal directions.

# Answer
With out code, this might be hard, but if I had to take a guess, your sprites aren't gittering, your *camera* is. I suspect you are moving the camera either to the exact x or y position both when having it follow your character, on horizontal and vertical movement, this will appear smooth, but when you take diagonal movemnt, since there is no exact x y location for the camera to move to, your scene ends up finding the closest value some how to move everything to.

If you look at the movement you can tell this is probably the case as your camera follows the red dot (your characters position) and thus produces jittery movements (because the red dot produces the same movements on the tiles).

There are three ways to fix this that I've seen. Allow sprite aliasing, so non integer movements can be represented (may not be practical if you aren't using OpenGL or something built off of that). Or possibly limit the directions you can move, such that you can only move in 8 directions. When you move in a diagonal direction both x and y coordinates will update by one. You may also want to slow down diagonal movement to about 70% of the cardinal direction movement speed in order to make sure you can't go faster in one direction than the other. You want to make sure that given a direction, the same number of pixels are added to each side of the screen at once each time you move in that same direction.

You'll notice in a lot of sprite based games they limit movement to either 4 way cardinal direction (manhattan) or 8 way direciton (Chebyschev).

In other games like Zelda this isn't a problem because the camera does not always have to move with the player (another way to solve this problem). For the last method, you have to make sure that one or both are updated at the same time for a given direction (for example, always update x by 1 in traversing one direction, then update y by 1 when you get a chance). updating each by one every other time causes the gittery behavior you see (x gets updated, then y, then x, then y).

This is solved my making sure that your camera moves integers at the proper slope rate for that direction. In your example you move like this (which causes un-even updates):

and you want to move like this:
> 3 votes

# Answer
Your guess is right. I had the same situation. It also involves transforming float coordinates to integer pixel coordinates.

I solved it in my game like this.

If X \< targetX { X += V } Else if X \> targetX { X -= V } ...// Duplicate the code for Y

Of course V should be actually V/sqrt(2) if you will go in both axis and V if you will go in one. Otherwise your diagonal movement will be faster.

This way when you need to go from p1 to p2, you always go diagonal with 45 degrees

At some point you will reach your targetX or targetY and you will go rest of the way in only one axis. Its not perfect but simpler and worked for me.
> 0 votes

---
Tags: movement, isometric, interpolation
---


# Question
Title: How do I write to a 16-bit depth buffer using Monogame and HLSL?
I'm working on shadow mapping. Part of the implementation involves drawing 3D models to a depth buffer with recommended 16-bit depth. To that end, I'm first creating a render target as follows:

`new RenderTarget2D(graphicsDevice, width, height, false, SurfaceFormat.HalfSingle, DepthFormat.Depth16)`

My HLSL shader is shown below.

```
#define VShaderModel vs_4_0_level_9_1
#define PShaderModel ps_4_0_level_9_1

matrix World;
matrix LightProjection;

struct MapVOutput
{
    float4 Position : SV_Position;
    float Depth : Depth;
};

MapVOutput MapVShader(in float4 position : SV_Position)
{
    MapVOutput output;
    output.Position = mul(position, mul(World, LightProjection));
    output.Depth = output.Position;

    return output;
}

float MapPShader(MapVOutput input) : Depth
{
    return input.Depth;
}

technique CreateShadowMap
{
    pass Pass0
    {
        VertexShader = compile VShaderModel MapVShader();
        PixelShader = compile PShaderModel MapPShader();
    }
};

```

The idea is to render the scene from the light's perspective (using the `LightProjection` matrix) and store depth information only. However, trying to compile this shader gives the following error:

`pixel shader must minimally write all four components of SV_Target0`

Note that the shader currently uses `vs_4_0_level_9_1` and `ps_4_0_level_9_1` to compile. I've tried changing those to simply `vs_4_0` and `ps_4_0`, which lets the shader compile, but causes an error to be thrown during runtime (with a cryptic error message).

Given all this, I have several questions I'm hoping to understand.

1. To generate a shadow map, I only need to store 16-bit depth information. **Is SurfaceFormat.HalfSingle the correct format to use for this purpose?**
2. I only need to store 16 bits, but the pixel shader function writes a float (32 bits). **How can I write only 16 bits to the render target?** If I write a float, is the value properly truncated anyway?
3. I've looked at existing shadow map samples and noticed that the `Depth` value in `MapVOutput` uses the `TEXCOORD0` semantic rather than \`DEPTH'. **Is DEPTH the correct semantic to use on this variable?**
4. **How do I resolve the HLSL error listed above without simply returning a color?** Google hasn't given me useful answers so far, and switching compiler versions seems to introduce other problems.

Thank you.

# Answer
First of all, I am not very familiar with monogame specifically, but what I say apply to DirectX 11, which I expect Monogame is using under the hood.

Now, for most cases, you don't need to expicitly write to a depth buffer from a pixel shader. Just enabling depth writes in the depth stencil state and setting a depth buffer before rendering should already enable depth buffering. For drawing shadow maps, you shouldn't even be setting a rendertarget by the way. Which means, that the pixel shader should return nothing, you should just declare it as void return type, or don't even set a pixel shader. You should only set a pixel shader in this case if you want alpha testing, so the shader would discard or clip based on the surface texture alpha and return nothing. When you finished rendering your depth buffer, you can just bind that as a readable texture for other shaders to sample from.

There are cases when you want to explicitly output depth from the pixel shader, for example with cube map shadows where you want to output the distance from light to pixel instead of the native depth alue. For that, you can use the SV\_DEPTH semantic in DX11 (there are also SV\_DEPTHGREATEREQUAL and SV\_DEPTHLESSEQUAL for conservative depth output). If you specify the output as SV\_DEPTH, you are expected to return a float. There are performance implications with this technique though, so try to avoid it if possible.

In your case, DepthFormat.Depth16 looks fine, as it is a 16 bit unorm integer format. You still write your shaders as float return type if you want to export depth with SV\_DEPTH semantic.

For your TEXCOORD question, the only reserved and meaningful semantic names are the ones starting with SV\_ (system value). Any other semantic names can be just whatever. Their only use is probably with shader reflections, where they can be queried from the application for custom shader management logic.
> 2 votes

---
Tags: monogame, hlsl, shadows, depth-buffer, shadow-mapping
---


# Question
Title: Isometric - Do I need to add shade to the sprite images itself, or render shade during runtime?
So I'm drawing sprites right now for my game world. It's going to be isometric, not rotatable, 2.5 Dimensional. Do I need to add in the shadow to my sprites right now (which would mean to have 5~6 variations of each sprite based on the shadow angle) or do I do that on runtime as the light source changes in the game?

Example: Say I have this drawn from a tileset.

https://i.stack.imgur.com/lIZMS.jpg

The horizontal tiles (https://i.stack.imgur.com/JPHhy.jpg) are reused on the top part of the wall and the bottom part of the wall. But the south side is lighter on the bottom part of the wall for reasons. I want to know if it's better to make 2 different images or make the color darker through coding. Thank you.

# Answer
> 2 votes
When you are using a 2d engine, you likely won't get around doing shading while you create your sprite and tile images. Properly shading an object requires information about its 3d shape, which is - per definition - not available in a 2d engine. That's why there are very few 2d games which have changing light directions. Usually you just decide on a fixed light direction and then stick to it for all your sprites and tiles.

If you want dynamic lighting calculated at runtime, use a 3d engine and create your assets as 3d meshes.

**Edit:** Sidar mentioned an unorthodox but quite interesting new approach in the comments: Add a normal map to your 2d assets. That would allow you to shade them correctly with point-light sources. But I have never used that technique myself and I couldn't name any tools (sprite editors or 2d game engines) which support that.

# Answer
> 0 votes
The question you need to ask yourself is: How would you add the shading at runtime? Maybe make a little test program that draws 4 sprites in a square and changes the shading. If it works the way you imagine it being, sure, do it in code.

This is not generally possible in a 2D tile based engine. The computer just sees a bunch of flat colors, and can’t tell which of those are texture, and which are shading.

At the least, you would have to create extra assets: Mask overlays containing the edges of your sprites in all 4 cardinal directions, I‘d try. Then you could tint those masks light or dark and draw them at 20% alpha on top of a sprite. To lighten/ darken the requisite parts.

The question you‘ll have to ask yourself is: Is it more work to do this shading in the directions you need manually, or to create fewer masks and write code to do it at play-time?

Also, figure out how you can „cheat“ with your lighting. Do you really need all directions, or can you maybe get away with drawing only a few (maybe even only 2, from left or from right), and then blending the two. E.g. if you are 1/3rd from a light on the right and 2/3rds from one on the left, could you composite „lit from right“ with 66% alpha over „lit from left“?

Also, could you maybe get away with a fixed shading and just draw bright radial gradients (again, at a low opacity like 20%) around every light source?

Could you maybe use a hybrid approach of the above approaches?

---
Tags: shaders, isometric
---


title: Unity player movement in cells

text:
# Question
Title: Unity player movement in cells
I want to do a game where the map is cell based, like Pokemon, where when you press Left, you move from 210x100 to 209x100.

Like this:

```
    void Update()
    {
        var x = Input.GetAxis("Horizontal");
        var z = Input.GetAxis("Vertical");

        if (x == 0 && z == 0)
        {
            return;
        }

        if (x > 0)
        {
            x = 1;
        } else if (x < 0)
        {
            x = -1;
        }

        if (z > 0)
        {
            z = 1;
        } else if (z < 0)
        {
            z = -1;
        }

        transform.Translate(
            x,
            0f,
            z,
            Space.World
        );
    }

```

But with this approach, when you quick press and release the left, the Update is executed many times and you go from 210 to 203 easily.

How can I move from 210 to 209 in 0,5 seconds and don't allow other movement until the current movement has finished?

# Answer
I would suggest you to actually create a grid of tiles. Each tile represents some position. You then move from current tile to the tile you have picked next. For example, `Grid[currentX + movementX, currentZ + movementZ]`.

You can use coroutines to move between tiles. Or you can simply check if the tile currently used by your player hasn't changed yet. For example, in Update -

```
if (player.CurrentTile != player.CurrentDestinationTile) { Player moves to that tile }
else if (movementVector != Vector3.Zero) { player.CurrentDestinationTile = Grid[currentX + movementVector.x, currentZ + movementVector.z] }

```

NOTE: that movementVector can't be set to have movement on X and Z at the same time if you don't want a player to move diagonally.

If you want to use coroutines. You can start by creating a boolean that indicates if a player is already moving to some tile.

```
private bool IsPlayerMoving = false;
private void Update
{
    // Calculate movementVector here
    if (!this.IsPlayerMoving && movementVector != Vector3.Zero)
    {
        this.StartCoroutine(this.MovePlayer(player.position + movementVector));
    }
}

[SerializeField] private float PlayerMovementSpeed = 3f;
private IEnumerator MovePlayer(Vector3 newPosition)
{
    this.IsPlayerMoving = true;

    Vector3 playerStartingPosition = player.position;
    float progress = Time.deltaTime * this.PlayerMovementSpeed;

    while (progress <= 1)
    {
        player.position = Vector3.Lerp(playerStartingPosition, newPosition, progress);

        progress += Time.deltaTime * this.PlayerMovementSpeed;
        yield return null;
    }

    player.position = newPosition;

    this.IsPlayerMoving = false;
}

```

Best way to do that in a more advanced way is if you have player FSM - Finite State Machine. When you are in movement state - you don't set the input for his movement. If he is in an IDLE state, you set him to movement state and set the destination.
> 2 votes

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


# Question
Title: MonoGame ortho projection axis direction
I have perfect square screen and I want to capture everything between -1000.0f and 1000.0f, so I create projection matrix like that:

```
var proj = Matrix.CreateOrthographicOffCenter(left: -width,
                                              right: width,
                                              bottom: -height,
                                              top: height,
                                              zNearPlane: -1.0f,
                                              zFarPlane: 1.0f);

```

I expect the axes to be X - left \>\>\> right and Y down \>\>\> up, but if I project some points with `Vector2.Transform` I get following:

```
(-1000, -1000) is (-1, -1)
(1000, 1000) is (1, 1)

```

I expect -1 on Y axis to be the top of the screen, but it is actually the bottom. How so? Is there some convention I missed?

# Answer
The OpenGL and DirectX coordinate systems are traditional cartesian coordinate systems. (0, 0) is in the center, the positive x direction is to the right and the positive y direction is to up.
> 1 votes

---
Tags: monogame, projection
---


# Question
Title: Getting the top layer of 3D perlin Noise
I am generating 16x16x64 chunks. Afterwards I apply 3D noise to them. I want the first layer to be all grass blocks and after those I want layers of dirt.

The current problem is that I am getting some dirt blocks in my top layer. So how do I get the entire top layer of the noise?

```
TArray<int32> heightMap = CalculateNoise();

    for (int32 x = 0; x < 16; ++x)
    {
        for (int32 y = 0; y<16; ++y)
        {
            for (int32 z = 0; z< 64; ++z)
            {
                int32 voxelIndex = x + (y * 16) + (z * (16*16));

                int heightmapValue = heightMap[voxelIndex];

                if (z == 30 + heightmapValue)
                    ChunkIDs[voxelIndex] = 1;
                else if (z == 29 + heightmapValue)
                    ChunkIDs[voxelIndex] = 2;
                else
                    ChunkIDs[voxelIndex] = 0;

            }
        }
    }

```

# Answer
If you want to select the top layer of the heightmap can't you simply do the following:

```
TArray<int32> heightMap = CalculateNoise();

    for (int32 x = 0; x < 16; ++x)
    {
        for (int32 y = 0; y<16; ++y)
        {
            for (int32 z = 0; z< 64; ++z)
            {
                int32 voxelIndex = x + (y * 16) + (z * (16*16));

                int heightmapValue = heightMap[voxelIndex];

                //If the block we're looking at is at the same level as the height map it must be on the surface
                if (z == heightmapValue)
                    ChunkIDs[voxelIndex] = 1;
                else if (z < heightmapValue) //If it's less than that then it's underground
                    ChunkIDs[voxelIndex] = 2;
                else //If it's not below or equal to then it must be air.
                    ChunkIDs[voxelIndex] = 0;

            }
        }
    }

```

I hope this helps, Thomas.
> 1 votes

---
Tags: c++, unreal-4, perlin-noise
---


# Question
Title: 3D 3-axes rotation into 3D 2-axes rotation
Hello everyone and thanks in advance to anyone who'll help me through this !

I am currently working on the Kinect V2 (for XBox One) to interact with an avatar. I'd like to use the rotation quaternion that the SDK 2.0 give for each joint of the Skeleton. My avatar (virtual avatar of NAO robot) communicates through nautical angles, yaw, ptich and roll. There's no problem to convert quaternions into nautical angles, but here's my problem :

Let's take the shoulder as an example of joint; Where the Kinect express the rotation of my shoulder as a 3-axes rotation, I need to convert it into a 2-axes rotation. So for my shoulder I have a \[Yaw, Pitch, Roll\] from the Kinect, which I want to convert into a \[Pitch, Roll\] for NAO's avatar

At the beginning, I didn't see the problem; I just ignored the Yaw angle. But I rapidly noticed that the movement was not the same than in the Kinect (and it makes sense).

Can someone help me ? How can I convert a 3D 3-axes rotation into a 3D 2-axes rotation ?

# Answer
> 1 votes
What you want to do here is preserve the direction that the upper arm points. So let's first get that direction (relative to the parent bone's space)

```
localArmDirection = kinectJointQuaternion * neutralArmdirection;

```

Now that you have a unit vector describing the 3D direction that you want the arm to point (relative to the torso), you can convert it into spherical coordinates to get the corresponding pitch and roll angles.

Here I'll make some assumptions about your torso coordinate system, but these are easy to convert if your conventions are different. Let's say...

* x+ points to the right (ie. out like a T-pose for the right arm, or into the chest for the left arm)
* y+ points straight up
* z+ points forward / ventrally

Then your angles (in radians) are:

```
pitch = atan2(localArmDirection.y, localArmDirection.z)

roll = asin(localArmDirection.x) * (isLeftArm ? -1.0 : 1.0)

```

---
Tags: rotation, quaternion, angles, kinect, avatar
---


# Question
Title: How to implement D&D 4e's line of sight algorithm?
D&D 4th Edition (the tabletop game) has combat on a 2D map with square tiles. A creature occupies an entire single tile.

The attacker has clear sight on the defender if lines can be drawn from one corner of the attacker's square to all four corners of the defender's square and none of these lines are blocked.

The rules are as follows:

> To determine if a target has cover, choose a corner of your square and trace imaginary lines from that corner to every corner of the target's square. If one or two of those lines are blocked by an obstacle, the target has cover. (A line isn’t blocked if it runs along the edge of an obstacle’s or an enemy’s square.) If three or four of those lines are blocked but you have line of effect, the target has superior cover.

So, in the following situation:

* A can fully see B, but C has superior cover from A (the unblocked line is from topright corner of A to topright corner of C), and A cannot see D at all.
* B can fully see A, C and D.

**How can I implement this?**

Over the years, I have tried several solutions: some forms of Bresenham's line, testing for walls pixel by pixel, giving some tolerance around corners, and even dividing the map into line segments and comparing rays from the attacker to these line segments using a line-intersection formula. But everything either wasn't sufficiently rules-accurate or was too computationally expensive.

Can this line-of-sight algorithm be implemented efficiently (enough so that hundreds of checks may be performed for maps of 100x100 tiles per second) and accurately, and if so, how?

# Answer
> 2 votes
We can check if a square and a line segment intersects by dividing the square into 4 line segments, then using the following formula from here:

```
s = (1/d)  ((x00 - x10) y01 - (y00 - y10) x01)
t = (1/d) -(-(x00 - x10) y11 + (y00 - y10) x11)

```

`(x00, y00)` are the first segment's first point, `(x01, y01)` are the first segment's second point and similarly `(x10, y10)` and `(x11, y11)` are the second segment's first and second point respectively.

If both of these values are in the range `[0, 1]`, then the line segments intersect.

First of all, you should extract the cover squares from the map, then when you need to check for visibility, then you take the 4 points of the square the current player is standing on, for each of them create a line segment with the four points of the square the enemy is standing on (that's 16 line segments), then try intersecting them with the edges of every cover square.

If you're wondering, that's 64 * of collision checks, which considering how simple the formula is, isn't much

---
Tags: 2d, algorithm, line-of-sight
---


title: How to draw smooth circle in Libgdx

text:
# Question
Title: How to draw smooth circle in Libgdx
I am trying to draw an circle to Libgdx which is created from Image not ShapeRenderer. But when I try to draw image to SpriteBatch it does not draw smoothly.

I checked the image resolution and Image Dimension is 1673x1673 and Sprite Size is 80x80.

```
  //This is my GameState code
  @Override
    public void render(float delta) {
        update(delta);
        SpriteBatch sb = game.batch;
        Color bg = ThemeFactory.getInstance().getTheme().backgroundColor;
        Gdx.gl.glClearColor(bg.r, bg.g, bg.b, bg.a);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        sb.setProjectionMatrix(camera.combined);
        sb.begin();
        for(int i =0;i<elements.size();i++){
            if(!(elements.get(i) instanceof Arrow)){
                elements.get(i).render(sb);//HERE IS DRAWING HAPPENING
            }
        }
        sb.end();
        barriers.render(sb);
        renderHud();
    }

```

My circle constructor and rendering code is below.

```
public Circle(Texture texture, Size size, Vector3 position){
        mSprite = new Sprite(texture);
        mSprite.setSize(size.width, size.height);//80x80
        mSprite.setPosition(position.x, position.y);
        mSprite.setOriginCenter();
    }
@Override
public void render(SpriteBatch sb) {
    mSprite.draw(sb);
}

```

I tried **TextureFilters Nearest Nearest and Linear Linear** but nothing has changed. And also increased **samples** for desktop and android applications, nothing has changed too.

# Answer
Libgdx has to know to build the mip map. Use this constructor with the second parameter set to true

```
Texture(FileHandle file, boolean useMipMaps)

```

It's not really clear what you mean by "smoothly", different TextureFilters will affect the way it draws in different ways. In any case, mipmaps should be "best" for drawing a high-res texture at low res.
> 1 votes

---
Tags: libgdx, android, antialiasing
---


title: What to do to set gravity in unity

text:
# Question
Title: What to do to set gravity in unity
What to do to set gravity in unity? I'm working on a game called "OXYGEN", and for the space scene. I want to set the gravity of the Controller to 0.38, or Mar's gravity.

# Answer
You can set the global default Gravity vector in the Physics Manager. You can find it under Edit -\> Project Settings -\> Physics (or Edit -\> Project Settings -\> Physics2d for a 2d game).

If you want to change the gravity from a script while the game is running, set `Physics.gravity` to a new Vector3 (For a 2d game: `Physics2D.gravity` to a new Vector2).

If you have a more complicated gravity setup with zones with different gravity or point gravity sources, then you should set the global gravity to 0:0:0 and handle gravity acceleration on your own. I posted a simple script for a point gravity source here.
> 2 votes

---
Tags: unity
---


title: Isometric circle on map

text:
# Question
Title: Isometric circle on map
Here's an example of something existing:

<sub>(source: puzzlepirates.com)</sub>

I tried to replicate this:

I know that the diameter for that ship's circle is `6 blocks` (as u the circle is overlapping the edges of the 6ths blocks, which also counts).

I know that the size of the isometric tile is `64*48`.

So I replicated that, and that's the output I get:

**You can see a few problems:**

* The size of the ellipse is not the same, even though I use the provided size information.
* Even if the size is the same, the edges does not end at the same locations, as in the provided image.

Here's my implementation, I am sure I have done the math wrong, as usual:

```
// The vessel radius (diameter / 2)
int radious = vessel.getInfluenceRadius();
renderer.begin(ShapeRenderer.ShapeType.Line);
renderer.setColor(Color.RED);

// Calculate the size of the ellipse
int width = radious * GameTile.TILE_WIDTH;
int height = radious * GameTile.TILE_HEIGHT;

// Draw ellipse, centered around vessel where xx and yy is where the vessel starts drawing
renderer.ellipse(xx - width / 2 + vessel.getRegionWidth() / 2, yy - height / 2 + vessel.getRegionHeight() / 2, width, height);
renderer.end();

```

What did I do wrong in the calculation? You can see that the ship in the real preview covers 29 blocks (including the small corners on north/south/west/east, and my preview only covers .. like 13.

# Answer
.ellipse() uses width and height (2 diameters, you are giving it radius.

Also, notice that on the original, it is 6 blocks diagonally. but from top to bottom is only about 4 blocks. Your graphic is exactly 3 blocks from top to bottom. Are your sprites diamond-shaped? TILE\_SIZE is measuring the sprite height, but if you're using iso tiles that is the diagonal. Just dividing by sqrt(2) will probably give you the right value
> 1 votes

---
Tags: libgdx, isometric
---


# Question
Title: Implementing pixel-perfect collision - Libgdx
I just started learning game programming through the libgdx framework and I am at the collision detection stage of development. I made a pretty simple game that has some basic bounding-box collision detection system. However, I want to implement **pixel-perfect collision** for accuracy.

I will be showing snippets of code that I think are important to help you understand what is going on.

A two-dimensional array is created to define the position of the tiles on the screen:

```
int[][] map = {
        {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,1,1,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,1,1,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,1,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
        {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
    };

```

This `create()` method from my main game class adds a player and three entities to an `ArrayList` of type `Entity`.

```
  @Override
  public void create () {
      batch = new SpriteBatch();
      tileTexture = new Texture("block.png");
      screenWidth = Gdx.graphics.getWidth();
      screenHeight = Gdx.graphics.getHeight();

      // add some entities including a player
      entities.add(new Player(this, 100, 150, 20, 20, 120.0f, new Texture("player.png")));
      entities.add(new Entity(this, 50, 150, 20, 20, 120.0f, new Texture("enemy.png")));
      entities.add(new Entity(this, 200, 200, 20, 20, 120.0f, new Texture("enemy.png")));
      entities.add(new Entity(this, 180, 50, 20, 20, 120.0f, new Texture("enemy.png")));
  }

```

The `render() method` draws the tile map and the entities when the game is run. Another class named `Entity` holds the data of a particular entity (can be a block/player). The data can be the `x` and `y` position of that entity.

```
      // draw tile map
      // go over each row bottom to top
      for(int y = 0; y < mapHeight; y++) {
          // go over each column left to right
          for(int x = 0; x < mapWidth; x++) {
              // tile
              if(map[x][y] == 1) {
                  batch.draw(tileTexture, x * tileSize, y * tileSize);
              }
          }
      }

      // draw all entities
      for(int i = entities.size() - 1; i >= 0; i--) {
          Entity e = entities.get(i);
          batch.draw(e.texture, e.x, e.y);
      }

```

This produces:

To check for collision when the player (green block) moves, I have two methods that check if the player is colliding with an entity or a tile.

The `tileCollision()` method:

```
  public boolean tileCollision(Entity e, Direction direction, float newX, float newY) {
      boolean collision = false;

      // determine affected tiles
      int x1 = (int) Math.floor(Math.min(e.x, newX) / tileSize);
      int y1 = (int) Math.floor(Math.min(e.y, newY) / tileSize);
      int x2 = (int) Math.floor((Math.max(e.x, newX) + e.width - 0.1f) / tileSize);
      int y2 = (int) Math.floor((Math.max(e.y, newY) + e.height - 0.1f) / tileSize);

      // tile checks
      for(int x = x1; x <= x2; x++) {
          for(int y = y1; y <= y2; y++) {
              if(map[x][y] == 1) {
                  collision = true;
                  e.tileCollision(map[x][y], x, y, newX, newY, direction);
              }
          }
      }
      return collision;
  }

```

The line of code `e.tileCollision(map[x][y], x, y, newX, newY, direction);` in this method calls the `tileCollision()` method in the Entity class that prints the position of where the block collides with a tile.

To check collisions between entities, we have this method:

```
  public boolean entityCollision(Entity e1, Direction direction, float newX, float newY) {
      boolean collision = false;

      for(int i = 0; i < entities.size(); i++) {
          Entity e2 = entities.get(i);

          // we don't want to check for collisions between the same entity
          if(e1 != e2) {
              // axis aligned rectangle rectangle collision detection
              if(newX < e2.x + e2.width && e2.x < newX + e1.width &&
                  newY < e2.y + e2.height && e2.y < newY + e1.height) {
                  collision = true;

                  e1.entityCollision(e2, newX, newY, direction);
              }
          }
      }

      return collision;
  }

```

**NOTE:** The green block can move across an entity but cannot go through tiles. This is because the line `e1.entityCollision(e2, newX, newY, direction);` calls the `entityCollision()` method in the class `Entity` that lets the green block move.

This type of collision detection seems basic and inefficient (time complexity of `O(n^2)`).

How do I implement **pixel-perfect collision** in this context?

**Additional question:** If I want to improve the efficiency, what collision detection system can I use to eliminate unnecessary checks?

# Answer
The terms to google are *Broad Phase* and *Narrow Phase* collision detection. Broad phase is used to eliminate invalid collisions. One way to do broad phase is just divide the screen into grids, then only iterate through neighboring grids instead of the whole entity list. Here is another technique.
> 1 votes

---
Tags: java, libgdx, collision-detection, textures
---


# Question
Title: Getting error when following learnopengl.com "Hello Window" Tutorial; how can I fix them?
I am not sure what to do, I have added the include / lib files in the IDE include / lib folders. But I am getting these errors. Someone please help me! What am I doing wrong? Do I need to add some more code or what?

***Errors***

> ```
> Error C1189   #error:  OpenGL header already included, remove this include, glad already
> provides it OpenGLSetup
> c:\program files (x86)\microsoft visual studio 14.0\vc\include\glad.h 26
>
> Error (active)        #error directive: OpenGL header already included, remove
> this include, glad already provides it    OpenGLSetup
> c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\glad.h 26
>
> ```

======

Here is a link to the project on gitub: https://github.com/Kraycon/OpenGLSetup

# Answer
TL;DR: `#define GLFW_INCLUDE_NONE` before including GLFW, or include glad bfore including glfw.

When you get these errors, the first thing to do is search for where the message is being generated:

https://github.com/Kraycon/OpenGLSetup/blob/165ff0702f8882bf9e2fda6f3a14fd31a0f03fd6/Include%20Files/glad.h#L25

Okay, so Glad is telling you not to include OpenGL headers yourself because Glad already provides it.

But, uh, you're not including OpenGL ... so something else is including it. Searching for "#include .\*gl.h" gets you to

https://github.com/Kraycon/OpenGLSetup/blob/165ff0702f8882bf9e2fda6f3a14fd31a0f03fd6/Include%20Files/glfw3.h#L140

ah, GLFW includes OpenGL/gl.h among a bunch of other opengl-related headers. A look at GLFW's docs (http://www.glfw.org/docs/3.1/build.html) shows

> If you are using an OpenGL extension loading library such as glad, the extension loader header should either be included before the GLFW one, or the GLFW\_INCLUDE\_NONE macro (described below) should be defined.
> 3 votes

# Answer
The OpenGL header is already included as part of glfw3. Swap the first two lines of your program and pray glfw3 does not care that glad has included the OpenGL header.
> 0 votes

---
Tags: opengl, c++, visual-studio, glfw
---


title: Is my 3d terrain moving?

text:
# Question
Title: Is my 3d terrain moving?
I generate a 3d isometric terrain with the help of badlogicgames. I pass a perspective camera to the spriteBatch projectionMatrix, but when I move my player (perspective camera follows my player) it seems like the terrain is moving - here's some video of my game. I think the terrain should be static. I am also using decalBatch; my decals look fine - they remain in their position instead, the terrain does not.

This is part of the code where I render terrain:

```
sb.setTransformMatrix(matrix);
sb.setProjectionMatrix(cam.combined);//is perspective
sb.begin();
for(int z = 0; z < 100; z++) {
    for(int x = 0; x <80; x++) {
        sprites[x][z].draw(sb);
    }
}
sb.end()

```

here is the third person camera

```
cam.lookAt(player.getX(), 0, player.getZ());

cam.position.set(player.getX(),7f,player.getZ()-10f);

playerDecal.setPosition(player.getX(), player.getY(), player.getZ());

```

The problem is that terrain keeps moving around along with my camera's position. Does anybody have a clue?

# Answer
Why are you setting the transform matrix? cam.combined is already transformed. It's a combined projection/transformation matrix.

Try add this line at the top

```
matrix.idt();

```

If that fixes it, then just delete the top line of your code, you don't need to set it unless it's been set somewhere else.
> 1 votes

---
Tags: java, libgdx, 3d
---


title: Vulkan read from storage buffer

text:
# Question
Title: Vulkan read from storage buffer
I have been attempting to push data to a storage buffer then then read back from it but to no avail. I am creating the buffer like I always do, populate it with **VK\_BUFFER\_USAGE\_STORAGE\_BUFFER\_BIT**

And give it the flags

**VK\_MEMORY\_PROPERTY\_HOST\_VISIBLE\_BIT | VK\_MEMORY\_PROPERTY\_HOST\_COHERENT\_BIT**

Then when I read from the buffer I only get junk data.

```
Buffer payload_buffer;
VkDeviceSize buffer_size = sizeof(float);
CreateBuffer(engine, buffer_size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, payload_buffer);

// Create the data that will be saved
float payload = 5.0f;
// Move the data to the GPU
memcpy(payload_buffer.mapped_memory, &payload, buffer_size);
// Move the data back
memcpy(&payload, &payload_buffer.mapped_memory, buffer_size);
// Output the data
std::cout << payload << std::endl;

// Destroy the buffer instance
DestroyBuffer(engine, payload_buffer);

```

Dose anyone know how i would track down the issue?

# Answer
> 1 votes
Remove the ampersand from the 2nd parameter. It should be:

```
memcpy(&payload, payload_buffer.mapped_memory, buffer_size);

```

If `mapped_memory` is already a pointer.

Otherwise with the ampersand you're copying the pointer itself into your float rather than the memory it points to.

---
Tags: c++, vulkan
---


title: Rendering a 2D tree in WebGL

text:
# Question
Title: Rendering a 2D tree in WebGL
Assume a tree of objects that need to be rendered, each with their own x/y coordinates.

Now let's say I could crawl through the tree and give each element a "z" coordinate, before rendering.

Is there a technique to allow the tree to be rendered out-of-order, yet still have the appropriate layering?

In other words, it makes no difference whether parent is drawn before child, or child before parent, the parent will *always* be drawn before the child (or the other way around, but it will be consistent).

I'm just getting started with WebGL, but I'm thinking that with some sort of orthographic projection, this would work?

# Answer
OpenGL (including WebGL) by default uses the z coordinate of a fragment when it needs to decide if the current fragment should override the one already present on the screen if depth testing is enabled (`gl.enable(gl.DEPTH_TEST)` at the beginning of the code).

But you'll need some sort of projection anyways (ortographic in this case) to make sure a unit horizontally is the same length, as a unit vertically (OpenGL's coordinate system goes from -1 to 1 on the x and y axis, it doesn't care about the aspect ratio).
> 0 votes

# Answer
Most 2D games have transparent assets. As such it's more typical that if you have a tree structure you walk the tree and generate a list of things to draw. You then sort the list of things to draw by Z and draw back to front.

If you have no transparency then you can rely on the z-buffer and draw out of order.

If you have only on/off transparency (0 or 1) then you can `discard` in your fragment shader

```
...

if (color.a <= alphaThreshold) { // where alphaThreshold is close to 0
   discard;   // don't draw this pixel and therefore don't update the z-buffer
   return;
}
gl_FragColor = color;

...

```

And then you can still draw out of order

As for "orthographic projection" neither WebGL nor OpenGL require any kind of *projection*. Projection is a term left over from the old fixed function pipeline that is not part of modern OpenGL or WebGL.

Of course it's still common to use a projection and use math like

```
 gl_Position = projection * view * model * vertexPosition;

```

But since it's up to you to write that code you're free to write something else.

You might consider these tutorials helpful
> 1 votes

---
Tags: 2d, webgl, projection
---


title: Direct3D 12 can't create a swap chain

text:
# Question
Title: Direct3D 12 can't create a swap chain
I'm learning DirectX12 and I'm trying to create a simple application that clears the screen with a solid color, but I'm stuck in Direct3D initialization. I can't create the swap chain and the `DXGI` factory returns a `nullptr`. This is my initialization code:

```
bool Game::InitializeD3D()
{
ID3D12Debug *debug;
D3D12GetDebugInterface(IID_PPV_ARGS(&debug));
debug->EnableDebugLayer();

// hardware result returned by functions
HRESULT hr;

// create device
hr = D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&mDevice));
if (FAILED(hr))
    MessageBox(0, L"device creation failed", L"error", MB_OK);

// create fence
mDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&mFence));

// query descriptor size
mRTVDescriptorSize = mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
mDSVDescriptorSize = mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
mCBVSRVDescriptorSize = mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);

// check for 4X MSAA quality level support
D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS MSAAQuality;
MSAAQuality.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
MSAAQuality.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE;
MSAAQuality.NumQualityLevels = 0;
MSAAQuality.SampleCount = 4;
mDevice->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &MSAAQuality, sizeof MSAAQuality);
mMSAAQualityLevels = MSAAQuality.NumQualityLevels;

// create command queue
D3D12_COMMAND_QUEUE_DESC commandQueueDesc = {};
commandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
commandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
hr = mDevice->CreateCommandQueue(&commandQueueDesc, IID_PPV_ARGS(&mCommandQueue));
if (FAILED(hr))
    MessageBox(0, L"command queue creation failed", L"Error", MB_OK);

// create command allocator
mDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&mCommandAllocator));

// create main command list
mDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, mCommandAllocator, nullptr, IID_PPV_ARGS(&mCommandList));
static_cast<ID3D12GraphicsCommandList*>(mCommandList)->Close();

// create the swap chain
DXGI_MODE_DESC mode = {};
mode.Width = mWindowWidth;
mode.Height = mWindowHeight;
mode.Format = mBackBufferFormat;
mode.RefreshRate.Numerator = 60;  // 60 Hz refresh rate
mode.RefreshRate.Denominator = 1;
mode.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
mode.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferCount = bufferCount; // double buffering
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferDesc = mode;
swapChainDesc.OutputWindow = mWindow;
swapChainDesc.SampleDesc.Count = 4; // 4X MSAA
swapChainDesc.SampleDesc.Quality = mMSAAQualityLevels - 1;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.Windowed = true;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

hr = CreateDXGIFactory1(IID_PPV_ARGS(&mFactory));
if (FAILED(hr))
    MessageBox(0, L"factory creation failed", L"Error", MB_OK);

hr = mFactory->CreateSwapChain(mCommandQueue, &swapChainDesc, &mSwapChain);
if (FAILED(hr))
    MessageBox(0, L"swap chain creation failed", L"Error", MB_OK);

// more init code
......

```

My main window is created and the message box appears saying that the swap chain creation failed and Visual Studio raises an `access violation` exception. What am I doing wrong?

# Answer
> 2 votes
You haven't listed what type the `mFactory` variable is, but based on the fact that you are calling `CreateSwapChain` I'm assuming you are using the older DXGI 1.1 version (the original that shipped with DirectX 11).

For DirectX 12, you are expected to use the more modern DXGI 1.2 functions: `CreateSwapChainForHwnd`, `CreateSwapChainForCoreWindow` or `CreateSwapChainForComposition`. If your program requires DirectX 12, then it can safely require `IDXGIFactory4`. It does work to use the older DXGI 1.1 function `CreateSwapChain` but there's no reason to use it since you are already requiring a newer DirectX Runtime to use DirectX 12 in the first place.

```
// mFactory is type IDXGIFactory4
// mSwapChain is type IDXGISwapChain1

DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.Width = mWindowWidth;
swapChainDesc.Height = mWindowHeight;
swapChainDesc.Format = mBackBufferFormat;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = bufferCount;
swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

DXGI_SWAP_CHAIN_FULLSCREEN_DESC swapChainFSDesc = {};
swapChainFSDesc.Windowed = TRUE;

DWORD dxgiFactoryFlags = 0;
#ifdef _DEBUG
dxgiFactoryFlags = DXGI_CREATE_FACTORY_DEBUG;
#endif
hr = CreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(&mFactory));
if (FAILED(hr))
    MessageBox(0, L"factory creation failed", L"Error", MB_OK);

hr = mFactory->CreateSwapChainForHwnd(
    mCommandQueue.Get(),
    // You should be using a smart-pointer like Microsoft::WRL::ComPtr
    // and not raw pointers for COM interfaces!
    hWnd, &swapChainDesc, &swapChainFSDesc,
    nullptr, &mSwapChain);

```

Note that your original code also has a problem in that it assumes that a refresh rate of 1 / 60 is always valid, which is not actually the case. In practice, some vendor's drivers enumerate even 60 Hz with a different numerator/denominator than 1, 60 so it wouldn't match and you'd get a performance hit. You *have* to enumerate modes to do this correctly with DXGI if doing 'true fullscreen'. Of course, I'd advocate using 'fake full screen' in any case.

> See Anatomy of Direct3D 12 Create Device and the Direct3D Game VS Templates for best practices for DirectX 12 device creation.

**NOTE:** If you are new to DirectX generally you should consider learning DirectX 11 first. DirectX 12 is an expert API that assumes you are already very familiar with DirectX. See the *DirectX Tool Kit* tutorials for DirectX 11 and DirectX 12.

**UPDATE:** The problem here is that MSAA is being used. Part of the 'modern swapchain' is that you *cannot* create an MSAA swapchain. If you enable DXGI device debugging

```
hr = CreateDXGIFactory2(DXGI_CREATE_FACTORY_DEBUG, IID_PPV_ARGS(&mFactory));

```

Then you'd get:

> DXGI ERROR: IDXGIFactory::CreateSwapChain: Flip model swapchains (DXGI\_SWAP\_EFFECT\_FLIP\_SEQUENTIAL and DXGI\_SWAP\_EFFECT\_FLIP\_DISCARD) do not support multisampling. DXGI\_SWAP\_CHAIN\_DESC{ SwapChainType = ...\_HWND, BufferDesc = DXGI\_MODE\_DESC1{Width = 2032, Height = 954, RefreshRate = DXGI\_RATIONAL{ Numerator = 60, Denominator = 1 }, Format = B8G8R8A8\_UNORM, ScanlineOrdering = ...\_UNSPECIFIED, Scaling = ...\_UNSPECIFIED, Stereo = FALSE }, SampleDesc = DXGI\_SAMPLE\_DESC{ Count = 4, Quality = 0 }, BufferUsage = 0x20, BufferCount = 2, OutputWindow = 0x000D0620, Scaling = ...\_STRETCH, Windowed = TRUE, SwapEffect = ...\_FLIP\_DISCARD, AlphaMode = ...\_IGNORE, Flags = 0x2 } \[ MISCELLANEOUS ERROR #102: \]

Instead you always create a single-sample swapchain, and then you create your own MSAA render target that you then explicitly resolve. This is true of DX11 UWP as well as DX12 on UWP/PC. See SimpleMSAA.

> While I'm on the topic, you also cannot create an sRGB swapchain with 'modern swapchains'. You instead create a non-sRGB swapchain and then an sRGB render target view. MSAA + sRGB linearly correct rendering is also a little complicated due to the fact that the debug validation layer had some bugs with older versions of Windows 10 that are all fixed for Windows 10 Creators Update for DirectX 12. The `SimpleMSAA` sample covers this.

---
Tags: directx, directx12, initialization
---


# Question
Title: Isometric tiles drawing and picking - JAVA
I'm trying to draw isometric tiles in Java and implement a tile picking system using the mouse cursor. I draw the tiles using math formulas I found and adapted to my tile textures which you can find below. Tiles are 64x64px but flat tiles are only 32px height even if I draw them using the 64x64 sprite.

```
public int[] toIso(int x, int y){

    int i = (x - y) * tileWidthHalf;
    int j = (x + y) * tileHeightQuarter;

    i+=xOffset;
    j+=yOffset;

    return new int[]{i,j};
}

public int[] toGrid(int x, int y){

    x-=xOffset;
    y-=yOffset;

    int i = (x/tileWidthHalf + y/tileHeightQuarter)/2;
    int j = (y/tileHeightQuarter - x/tileWidthHalf)/2;

    return new int[]{i,j};
}

```

The map is a simple 2d array where my tiles are represented by their id.

Here is a video showing what is actually happening: youtu.be/baCVIfJz2Wo

---

# Answer
just wanted to say that I finally solved it. It was just a conversion to int issue. These are the final methods that I use. Hope it will help people who were trying to work with isometric tiles. Thank you !

```
public static int[] toIso(int x, int y){

    int i = (x - y) * TILE_WIDTH_HALF;
    int j = (x + y) * TILE_HEIGHT_QUARTER;

    i += xOffset-TILE_WIDTH_HALF;
    j+=yOffset;

    return new int[]{i,j};
}

public static int[] toGrid(double i, double j){

    i-=xOffset;
    j-=yOffset;

    double tx = Math.ceil(((i / TILE_WIDTH_HALF) + (j / TILE_HEIGHT_QUARTER))/2);
    double ty = Math.ceil(((j / TILE_HEIGHT_QUARTER) - (i / TILE_WIDTH_HALF))/2);

    int x = (int) Math.ceil(tx)-1;
    int y = (int) Math.ceil(ty)-1;

    return new int[]{x, y};
}

```
> 1 votes

---
Tags: java, tiles, isometric, picking, swing
---


title: Rendering 2D shadows in shader

text:
# Question
Title: Rendering 2D shadows in shader
Update:

I am getting slightly better results by modifying the shader so that it sets a flag on entering a obscured region, and then only sets the fragment to black if the ray casting exits the obscured region. The bordering light is a little less noticeable this way. Additionally objects behind other objects will now be correctly obscured as long as they are not touching.

However as you can see in the image, I have noticed a new problem. The shadow becomes very choppy at the back due to the way I am doing raycasting.

Original:

I am currently trying to render shadows in a 2d game. I use the following shader to do so:

```
#version 120
varying vec2 vTexCoord;

uniform vec3 u_lightColor;
uniform sampler2D u_texture;

float drawShadow(){
    vec2 loc;
    vec2 norm = normalize(vTexCoord - vec2(.5,.5)); // Pointing from center to point
    vec4 smp;

    float dst = 0.0;

    // For now draw all casters
    if(texture2D(u_texture, vTexCoord - dst * norm).a > 0)
        return 1.0;

    for(int i = 0; i < 256; i++){
        loc = vTexCoord - dst * norm;

        if (length(loc-vec2(.5,.5)) < 1.0/256.0)
            break;

        smp = texture2D(u_texture, loc);

        if(smp.a > 0){
            return 0.0;
        }

        dst += 1.0/256.0;
    }

    return 1.0;
}

void main() {
    float dist = length(vec2(.5,.5) - vTexCoord.xy);

    float shad = drawShadow();

    float intensity = 1-dist*2.0;

    gl_FragColor = vec4(u_lightColor, 1.0)*vec4(shad*vec3(intensity), shad);
}

```

The light is being rendered at the center of the screen, and the texture being drawn is one where any shadow caster is drawn as a non transparent sprite.

The trouble is because of the way I am sending out the rays I end up with the following:

Where the shadows don't hug the edges of the sprites. Also, I would like to somehow obscure shadow casters if they are in the shadow of another shadow caster, but not if they are the first caster the light hits.

# Answer
> 1 votes
A completely different approach to 2D shadows would be by making a dynamic mesh on the CPU or maybe in a geometry shader and using it with a stencil mask to do shadows.
I'd recommend checking out this website: https://www.redblobgames.com/articles/visibility/ for 2D visibility from a mesh.

I also tried implementing your solution in shadertoy:  And I had to crank the steps up to 32768 before it would drop below 60fps. So maybe you can get away with increasing the number of steps to reduce your aliasing problems.

Update while writing this answer I found out a way to smooth your shadows in the shader. It's kinda fake but it might work:
https://www.shadertoy.com/view/XlByDm

---
Tags: 2d, shaders, glsl, shadows
---


# Question
Title: Can't reference my custom editor script from a non-editor script even when using its namespace
I know that certain namespaces are necessary to include to specify under what scope certain methods are found, and this also saves typing. Otherwise the error CS0246 is thrown if referencing an unknown type.

The problem is, that I am using a namespace in a script in:

```
 Assets / Scripts

```

And that namespace is defined in a script in:

```
 Editors / Data / AnotherFile

```

So I am getting an error CS0246.

How could I solve this without moving that script into the `Assets / Scripts` location?

SCRIPT LOCATED IN EDITOR / DATA / ANOTHERFILE:

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

namespace NodeEditorWindow
{

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

    [SerializeField] private string _name;

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

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

}

```

SCRIPT LOCATED ON ASSETS / SCRIPTS / ...:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GameData;
using NodeEditorWindow; //HERE I AM USINGTHE OTHER CLASS'S NAMESPACE

public class LevelController : Singleton<LevelController>
{
    [Header("Level Data:")]
    [SerializeField] private LevelFlowData levelFlowData;
}

```

These are the errors I get in console (both CS0246):

Assets/Scripts/Scene Controllers/LevelController.cs(6,7): error CS0246: The type or namespace name \`NodeEditorWindow' could not be found. Are you missing an assembly reference?

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

Sorry if this seems to be a repeated question, but I haven't found any solution to this error due to having scripts on different paths (but using the namespaces). Thanks in advance.

# Answer
> 2 votes
The problem is that you're including editor code into the "runtime" code. Unity places the editor scripts in a different assembly, so basically your editor code is not accessible from the actual game code. You need to move your editor script and its parent classes) from the Editor folder and you can do something like

```
#if UNITY_EDITOR
using UnityEditor;
/*
  Editor code
*/
#endif

```

which should give you access to Unity's Editor API. In this way you're "simulating" the build-time stripping of editor code and still be able to use runtime scripts alongside editor scripts. It's a bit of a headache, especially if you're using a fair amount of custom editor scripts, which all need to be flipped to the runtime assembly.

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