# Question
Title: How to convert Resources.LoadAll to Addressables?
I have been advised to move away from the Resources system to the new Addressables system, which seems to have many advantages.

I need to convert the following code to use the Addressables:

```
public static void LoadDefs()
{
    foreach (var baseTileType in Resources.LoadAll(Settings.BASE_TILES_PATH, typeof(TextAsset)))
    {
        var baseTile = Deserializer.Deserialize<BaseTile.Initializer>(((TextAsset) baseTileType).text);
        BaseTileInstances.Add(baseTile.Name, baseTile.CreateInstance());
    }

}

```

It is important for me to detect the type of `TextAsset` because those are .yaml files that I need to load the information from. Then, derived from information in that YAML file, I load sprites that I need with `Resources.Load<Sprite>(path)` later, but that should be simple.

The documentation is pretty unclear on how to do this. It mentions labels, but not much else.

How can I achieve a similar result with this new system?

# Answer
> 2 votes
I've managed to come up with a basic solution for the following problem. Here's an example of needing to load and store sprites:

1. Add your `addressables` into a group and label them accordingly. In my case, `"pictures"`.

2. Add the code.

```
public static readonly Dictionary<string, Sprite> AllSprites = new Dictionary<string, Sprite>();

public static async Task InitSprites(string assetLabel)
{
    var locations = await Addressables.LoadResourceLocationsAsync(assetLabel, typeof(Sprite)).Task;
    List<Task<Sprite>> tasks = new List<Task<Sprite>>();

    foreach (var location in locations)
    {
        tasks.Add(Addressables.LoadAssetAsync<Sprite>(location).Task);
    }

    var loadedSprites = await Task.WhenAll(tasks);

    foreach (var sprite in loadedSprites)
    {
        AllSprites.Add(sprite.name, sprite);
    }
}

```

You may call `InitSprites` from any async method. For example, you can define a `public static async void Load()` method, which you call from the `Start()` method in your `GameManager` singleton.

Then, inside of that, call `await InitSprites("pictures")`. This will asynchronously load and store your sprites wherever you need (in my case, a dictionary).

3. Modify

You can get this code to work with any asset type. All you have to do is to replace the `typeof()` parameter with your desired type. You can even write `typeof(object)` and then store it into a `List<object>`. That way, one list can hold ALL of your assets of various types, which you can then use however you like.

# Answer
> 1 votes
No idea if this is more or less efficient than the OPs solution, but here is my take on the same problem. In my case, I have lots of different data types that derive from scriptable objects that I loaded by type into lists at runtime using Resources.LoadAll(). Some have prefabs which means they have dependencies thus making the main data payload quite large (project is WebGL), so moving these out of resources to load from addressables was critical. Like OP, I organize the Addressable assets with labels and groups. Instead of using `System.Threads.Task` I'm using the familiar Monobehaviour Coroutine, because, well, I'm familiar with it :)

```
IEnumerator  LoadAssetsAsync<T>(string label, List<T> list, System.Type type)
    {
        yield return null;
        AsyncOperationHandle<IList<IResourceLocation>> handle = Addressables.LoadResourceLocationsAsync(label, type);
        yield return handle;

        for(int i = 0; i < handle.Result.Count; i++)
        {
            StartCoroutine (LoadAssetAsync<T>(handle.Result[i], list));
        }
        Addressables.Release(handle);
    }

    IEnumerator LoadAssetAsync<T>(IResourceLocation location, List<T> list)
    {
        var handle = Addressables.LoadAssetAsync<T>(location);
        yield return handle;
        list.Add(handle.Result);
    }

```

And it gets called like so:

```
List<Foo> foos = new List<Foo>(); //Foo can be anything

void OnGameAwake()
    {
        StartCoroutine(LoadAssetsAsync<Foo>("Foo", foos, typeof(Foo)));
    }

```

Probably just a dumber way of restating the OPs solution, but it works...

---
Tags: unity, assets, loading, asset-management, addressable
---


# Question
Title: How is data regarding items in RPGs and other loot-based games stored and implemented?
I am currently practicing game design and development by implementing singular (or a small set) of mechanics in Unity.

For example, -- and this is relevant towards the end -- I've just finished a small MOBA-style system that implemented a few mechanics:

1. Three lanes with respawning enemy and ally creeps/minions,
2. Towers at the ends of each lane that attack the player characters and minions,
3. A final "boss tower" whose defeat is the victory condition, and
4. Player characters are equipped with four spells from a set of implemented spells.

Point 4 is the relevant mechanic here: I implemented the set of spells as an XML document. The XML document lists the spells and their properties (e.g., type, mana cost, damage per second, etc.), allowing them to be retrieved and converted into a C# list at runtime. Player characters then select and equip spells from this C# list.

I'm wondering: Is a similar methodology used to implement thousands of unique items in RPGs and other loot-based games? If not, or even if so, what other methods are there for implementing the items in these games?

# Answer
> 3 votes
We can't answer questions like "how do they do it" because, well, we don't know, and they won't tell us.

We can help you figure out a few things, though.

In software development in general, unless one has prior knowledge, an approach is to build a feature that works, in isolation from the rest of the software as much as possible (i.e. reduce coupling)(for example: what you've just told us--start with loading a small set of data from XML). Then you work on some other features.

Then you analyze what you've done: after using a profiler, is the process of loading the data from XML taking to long? What is taking so long, is it reading from disk, or is it the parsing, or is it creating the associated objects? Is the game designer complaining that they're always messing up XML syntax when editing the XML file and would like a better tool? Is the issue with the XML, or is it with how they interact with it? Would they need a specific tool to read the XML, edit the data, then save the data again as XML?

Then who needs this XML anyway? The clients? The server? Is the XML too verbose to be served to clients?

Now you get the feeling that "something is wrong" with this XML, but unfortunately, you don't know in advance what *exactly* is wrong, so you can't figure out a solution for a problem that does not exists yet. Fortunately, you've quite isolated the part of your game that loads the data into the game, so you can update that part without affecting too much the rest of the game.

But update it to what?

And this is why we can't tell you how "it's done". Because you don't know what issues you'll be facing.

A thing, for sure: yes, XML is very verbose and is bad with types, and can be long to read from disk and can take time to parse, so games that use a lot of data may have chosen other solutions. Or they may have hidden the complexity of loading XML under a "loading screen, presenting the menu to the player" (in a background thread) or conveniently decided to not load *everything*.

Other games use approaches like binary data that they could use to directly populate an object, or a database they load internally or from the server.

You need to consider a couple of trade-offs: with a human readable/editable data format, your game designers can start early on to create content; you don't *need* to write and maintain special tools, giving you, the programmer, more time to write actual game features. If you were to format your data in any other way, you would need to spend more time up-front developing the required tools. And if you decide to change the content creation pipeline mid-way, then you'll need to re-train your content creators, which may annoy them. ("Bla bla bla the old way was so much better bla bla bla I could do X with my Notepad and now I can't with this PoC bla bla bla.")

If you have doubts, I suggest you test early on with the kind of data you'll need to deal with when the game is ready to ship. See how it goes, and find the best solution for the needs you know you have at that point.

---

> If you wish to avoid cheating, then it is clearly impractical to use human-readable solutions like XML (as players could simply edit the XML file to create items with arbitrary properties).

This is roughly irrelevant. Yes, XML is in plain text and easily readable and editable. But in what context do you use this XML? If it is in a multi-player game, the XML used on the client will only be used to *display* text and information on the client, like in any multi-player game, it should *not* be used to do any logic, as this is the server's job. If it is in a single-player game, then why do you care? Players who paid for their game copy will not ruin anyone else's experience; I heard some call this "modding" and have embraced it ;)

You *could* add a layer of complexity between the player and your game data (e.g. turning your XML data into some kind of binary data), but ultimately, your players are collectively very smart and curious and will find a way to decrypt/modify game data (and they have a lot of time to spend on this), so they'll figure a way to edit this data anyway.

---

I'm sorry I could not offer a definitive answer, I still hope it will help you a little.

---
Tags: rpg, data-structure, databases, data, xml
---


# Question
Title: Is it a good idea to swap between a lot of different shader states during runtime?
What I'm trying to do is create a specific shader states(`depthstencil`, `blend`, and `rasterizer`) for each mesh in my program, so jumping straigth to the code:

```
pDeviceContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &strides, &offset);
pDeviceContext->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
{ // set the states bellow for each mesh drawn:
    pDeviceContext->OMSetDepthStencilState(m_pDepthStencilStateON, 0);
    pDeviceContext->OMSetBlendState(m_pBlendState, BlendFactor, SampleMask);
    pDeviceContext->RSSetState(m_pRasterizerState);
}
pDeviceContext->IASetPrimitiveTopology(Topology);

```

The code above depicts a function which is called for each mesh in a model, there are around 200~300 models currently being drawn in each frame. So to resume this is what is not clear to me:

**1-** Is this a good practice? Or is there a better way of using different shader states during runtime?

**2-** Is it a good practice to use one `DepthStencilView` to each mesh, like the ones above, and doing their cleanup with `pDeviceContext->ClearDepthStencilView(pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);` at the end of each frame?

The main reason I want to do this is because I want to draw different kind of things in runtime, in some cases I may or may not want to use the blend effect in a certain mesh, or could want the z buffer to be read-only on `DepthStencilView` during the drawing of a certain mesh.

I'm aware of the possibility to create a new state from the previous one, but I'm not sure if this would be a hit on performance aswell:

```
D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
pDepthStencilView->GetDesc(&dsvd);
dsvd.Flags = D3D11_DSV_READ_ONLY_DEPTH; // sets to Read-Only.
HRESULT hr = pDevice->CreateDepthStencilView(pDepthStencil, &dsvd, &pDepthStencilView);

```

If someone could explain to me what is the best approach to this kind of case it would help me pretty much.

# Answer
> 1 votes
As noted in the comments, profile your scene and look at where your bottle necks. It's going to vary greatly depending on exactly how those 200-300 models are actually built.

In general, you have to draw your transparent objects after drawing your opaque ones, and some kind of sorting by material setting can help avoid thrashing GPU texture caches. The transparent objects generally have to be drawn back-to-front (a.k.a. the Painter's algorithm).

In DirectX 10/11, the state objects helped a lot of the 'unknown stalls' problems in Direct3D 9 when you called Draw. Generally creating state objects and shader objects is expensive, but setting them is not.

In DirectX 12, you have to munge everything into a Pipeline State Object so creation is heavy, but setting is super cheap.

> "back in the day" of Windows XP and Direct3D 9, most games that had a good framerate had to keep total Draw calls per frame to less than ~1000. Later-generation Direct3D 9 stuff got up to 1000-3000 individual Draw routinely.

For pixel-shader heavy materials, a 'depth-prepass' (i.e. drawing the large objects with a trivial shader that just generates the depth values) and/or drawing all the opaque objects in rough front-to-back order can help.

In the end, profiling is typically needed to determine if your program is: (a) CPU-bound, (b) GPU-bound on the vertex processing, or (c) GPU-bound on pixel-fill.

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


# Question
Title: OpenGL gl_Position z-range and depth buffer range
Am I correct that the OpenGL depth buffer has values between 0 and 1 while the z component of gl\_Position is between -1 and 1?

# Answer
Yes, `gl_Position.z` should be between \[-1, 1\] after dividing `gl_Position.w`, otherwise will be clipped. OpenGL will map \[-1, 1\] to \[0, 1\], use `glDepthRange(near, far)` can change the default value.
> 1 votes

---
Tags: opengl, coordinates, depth
---


# Question
Title: 2d zooming function using transformation matrix
I'm trying to create a sort of "graphing calculator coordinate system" where you can zoom into a point by scrolling with the mouse wheel. I'm using javafx's transformation matrices (Affines) to keep track of scale and translation. I'm struggeling to come up with a function that allows me to zoom into a point when scrolling, it always comes out weird and moves the canvas in strange ways. This is what I have tried:

```
    double multiplier = event.getDeltaY() / 1000.0; //event.getDeltaY() = mousewheel scroll

    //event.getX() = mouseX, event.getY() = mouseY
    this.cam.move(new Point2D(-event.getX() * multiplier, -event.getY() * multiplier)); //calls Affine.appendTranslation
    this.cam.zoom(1 + multiplier); //calls Affine.appendScale

```

There is also Affine.prependScale and Affine.prependTranslation which adds scale / translation before existing operations. I'm not very good at matrix maths so if anyone knows a working zoom function please let me know.

# Answer
I don't know javafx, but I can tell you the math.

An affine transformation is a linear transformation combined with a translation. e.g.

```
A(p) = | l11 l12 | * | p_x | + | t_x |
       | l21 l22 |   | p_y |   | t_y |

```

Usually, for simplicity, we use homogeneous coordinates, which allows to write the transformation as a single matrix product:

```
       | l11 l12 t_x |   | p_x |
A(p) = | l21 l22 t_y | * | p_y |
       |  0   0   1  |   |  1  |

```

Now suppose that `A(c) = q` and you want to zoom in such that the new transform `A'` keeps `A'(c) = q`. The linear zoom matrix is trivial:

```
       | z 0 0 |   | p_x |
Z(p) = | 0 z 0 | * | p_y |
       | 0 0 1 |   |  1  |

```

where `z` is the zoom factor. Notice that `Z` has one fixed point, `(0, 0)`.

```
          | z 0 0 |   | 0 |   | z*0 + 0*0  + 0*1 |   | 0 |
Z(0, 0) = | 0 z 0 | * | 0 | = | 0*0 + z*0  + 0*1 | = | 0 |
          | 0 0 1 |   | 1 |   | 0*0 + 0*0  + 1*1 |   | 1 |

```

So basically, you want to combine `A` with a modified version of `Z` such that the fixed point is at `q` (if you place that modified `Z` in front of `A`) or `c` (if you place `A` in front of that modified `Z`).

To have a fixed point at `q`, simply translate so that `q` is sent to `0`, zoom, then translate back.

```
Z' = T⁻¹ * Z * T

```

where `T` is the relevant translation. Expanding the matrices, we have:

```
        | 1 0 q_x |   | z 0 0 |   | 1 0 -q_x |   | p_x |
Z'(p) = | 0 1 q_y | * | 0 z 0 | * | 0 1 -q_y | = | p_y |
        | 0 0  1  |   | 0 0 1 |   | 0 0   1  |   |  1  |

```

Notice that `Z'(q) = q`

Now you simply combine `Z'` with `A`:

```
A' = Z' * A

```

Now we can see that:

```
A'(c) = Z'(A(c)) = Z'(q) = q

```
> 0 votes

---
Tags: java, mathematics, matrix, javafx
---


# Question
Title: How the game engine handles camera view in DirectX
I am quite confused with how the game engine handles camera view in DirectX. I know all the matrix stuffs, but where the projection matrix goes finally seems rarely mentioned.

I looked up in the sample project by microsoft https://msdn.microsoft.com/en-us/windows/uwp/gaming/tutorial--create-your-first-metro-style-directx-game

in the `GameRenderer::CreateWindowSizeDependentResources()` method, the projection process is implemented

```
XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D();

        ConstantBufferChangeOnResize changesOnResize;
        XMStoreFloat4x4(
            &changesOnResize.projection,
            XMMatrixMultiply(
                XMMatrixTranspose(m_game->GameCamera()->Projection()),
                XMMatrixTranspose(XMLoadFloat4x4(&orientation))
                )
            );

        d3dContext->UpdateSubresource(
            m_constantBufferChangeOnResize.Get(),
            0,
            nullptr,
            &changesOnResize,
            0,
            0
            );

```

However I can't figure out what the `UpdateSubresources` method has anything to do with projection (yet such projection in the `UpdateSubresources` method exists in some other samples I found). But wouldn't it be absurd to change the entire buffer every frame for projection? Isn't the data in the buffer in world view coordinates?

The vertex shader seems also take the task of projection

```
PixelShaderInput output = (PixelShaderInput)0;

    output.position = mul(mul(mul(input.position, world), view), projection);

```

I do think this one is more plausible for the task.

**So the questions are:**

1. Which one exactly is the process of projection, and how does it come along in two places?
2. If it happens in UpdateSubresources, what should I do with dynamic buffer?
3. If it happens in the shader, where does the world, view, projection matrics come from?
4. How should I use it with SharpDX

# Answer
> 1 votes
Direct3D version 9, and even more 10, 11, and even even more, Direct3D 12, work at a very different level of abstraction compared to a game engine.

Put simply, Direct3D is simply a set of APIs that allow you to do stuff with the video card, but that's all there is to it. The concept of projection matrices and cameras, does not even exist inside Direct3D, so it's meaningless to talk about them.

Overly generalizing, what Direct3D allows you to do is to feed it a set of abstract "vertices", which you can then transform into screen coordinates, which are then rasterized as triangles. The process of transforming vertices into screen coordinates is done by a piece of code called the "Vertex shader", which is independently run for each input vertex, and each outputs a screen coordinate.

If it happens that the vertices you are feeding to Direct3D correspond to coordinates in a 3D world, you can have the vertex shader multiply the input vertex with a world-view-projection matrix, which will result in the output corresponding to the screen coordinate of the input 3D coordinate, looked at from a camera defined by the world-view-projection matrix.

It seems overly complicated, but what I'm trying to say is that the concept of cameras doesn't really exist in Direct3D. Instead, Direct3D gives you the tools to build a lot of things, one of them you can choose to be a camera.

In practical terms, since the projection is commonly (but not mandatorily) performed in the vertex shader, you need a way to tell the vertex shader which matrix to use. One way of doing this is with the `UpdateSubresource` API. If you have everything connected correctly, the matrix you set with `UpdateSubresource` will be seen by the vertex shader. Therefore, to implement the common concept of "cameras" in a low level API such as Direct3D, you need (in no particular order):

* Your vertices to include a 3D position in a virtual space
* Your code to create a world-view-projection matrix
* Your code to upload the matrix to the GPU via `UpdateSubresource`
* Your vertex shader to multiply the matrix with the vertex
* Your pipeline to wire everything
* The rest of the program to work

As you're reading the sample code, keep a look at which parts of the code do each one of these steps, so you can see how it all fits together.

# Answer
> 0 votes
In the older Direct3D 9 era 'fixed function pipeline' the lighting & transformation was done by a specific set of hardware that made use of the transformation matrices. In the modern 'programmable pipeline' model, lighting & transformation is typically done in the vertex shader.

In the older Direct3D 9 version of the 'programmable pipeline', variables could be communicated to the shader via a global array of shader constants. In Direct3D 10 and 11 this was made into the concept of a 'Constant Buffer' which is usually updated much more often than a Vertex Buffer or Index Buffer. These can be updated either using the "Map DISCARD" pattern (such as is used for dynamic Vertex Buffers) or by copying from memory using `UpdateSubresource`.

> With Direct3D 12, there's now even more programmatic control over how data is shared between shaders and the CPU using the concept of root signatures. Data can be placed into the root signature itself, copied into the command-list, or referenced indirectly in heap allocated memory which results in much the same thing as a Direct3D 10/11 constant buffer. With Direct3D 12, you have to ensure you don't change the memory until after the GPU has finished drawing with the references, which means in many cases explicitly allocating many small chunks of memory in a frame to serve as a constant buffer, then not reclaiming that memory until appropriate GPU fences are crossed. In other words, it's all up to the application to handle what the Direct3D Runtime used to do for you.

---
Tags: camera, directx11, sharpdx
---


# Question
Title: Free camera navigation and pre-defined locations
I have an interactive scenery app written in Unity, where users can freely navigate the camera through the scene. What I want to do now, is to let user automatically fly to some "hotspots" with a single key stroke, while still allowing the users to navigate manually.

I tried Animation, but with it, auto-fly and manual navigation are mutually exclusive - I have to disable one in order for the other to work.

Right now, I'm attempting the fall-back solution, where I create some empty game objects with special scripts attached, so that when public script functions are invoked, the game object animates the camera to a pre-defined transformation.

My question being: is there a better solution than my fall-back?

# Answer
I've only ever seen this solved with the animation being controlled by a script - This can be done in the Update() method or via a tweening plugin like DoTween.

In the Update method you have a few options, including manual movement (manually manipulating `transform.position`'s x, y and z parameters), using `transform.position = Vector3.MoveTowards(transform.position, _movementTarget, MaxSpeed * Time.DeltaTime);` and `transform.position = Vector3.Lerp(_movementStart, _movementTarget, _animationState)` where `_animationState` goes from 0 to 1 to indicate how far through the animation you are. The choice between `MoveTowards` and `Lerp` comes down to whether you care more to set the movement speed, or the time it'll take to get to the target.

For rotation, you can also use `Transform.LookAt()`, `Quaternion.Lerp()` and `Quaterion.LookRotation()` however I tend to compute this manually to absolutely ensure the Z rotation is never changed.

In my solution I've gone with the `Lerp` approach for position, and am manually animating rotation by only lerping the y axis, you could also separately lerp the x rotation axis, that'd be fine, just make sure to never change the z axis.

```
using UnityEngine;

namespace Assets
{
    public class MoveMe : MonoBehaviour
    {
        private bool _isMoving = false;
        private Vector3 _movementStart;
        private Vector3 _movementTarget;
        private float _rotationStartEulerY;
        private float _rotationTargetEulerY;
        private const float AnimationSpeedFactor = 2f;
        private float _animationProgress = 0;

        private void Update()
        {
            if (_isMoving)
            {
                _animationProgress += Time.deltaTime * AnimationSpeedFactor; //Animation progress 0..1
                transform.position =
                    Vector3.Lerp(_movementStart, _movementTarget, _animationProgress); //Animate position
                var rot = transform.rotation.eulerAngles;
                transform.rotation = Quaternion.Euler(rot.x,
                    Mathf.Lerp(_rotationStartEulerY, _rotationTargetEulerY, _animationProgress),
                    rot.z); //Animate rotation
                if (_animationProgress >= 1)
                {
                    _isMoving = false; //End animation, player free to move camera manually
                }
            }

            if (Input.GetKeyDown(KeyCode.A)) StartAnimationTowards(new Vector3(0, 1, -2.96f), -51.145f);
            if (Input.GetKeyDown(KeyCode.S)) StartAnimationTowards(new Vector3(-2.88f, 1, -3.52f), 39.054f);
            if (Input.GetKeyDown(KeyCode.D)) StartAnimationTowards(new Vector3(-8.97f, 3.97f, 3.2f), 103.39f);
        }

        private void StartAnimationTowards(Vector3 position, float rotation)
        {
            _isMoving = true;
            _movementStart = transform.position;
            _movementTarget = position;
            _rotationStartEulerY = ClampRotation(transform.rotation.eulerAngles.y);
            _rotationTargetEulerY = ClampRotation(rotation);
            _animationProgress = 0;
        }

        private float ClampRotation(float rotation)
        {
            //Ensures the returned value is between -180 .. 180. This ensures rotation doesn't animate the long way around the circle.
            rotation %= 360;
            return (rotation > 180)
                ? rotation - 360
                : rotation;
        }
    }
}

```
> 2 votes

# Answer
I have never tried honestly, but perhaps you could create multiple cinemachines and switching between them via a certain parameter: You have your main virtual camera "MainCam" that follows the user. As the user presses a button or any other trigger event occurs, the parameter "activateCamX" will disable "MainCam" and activate "CamX", which in turn will not follow the player but rather fix the view on a certain location/target.
> 0 votes

---
Tags: unity, animation, transformation
---


# Question
Title: How do I correctly use userData in Box2d?
Many guides used userData. But with the source of Box2d I have, I don't see the `SetUserData` functions in the code as I see them in the guides.

After understanding it, I realized that these manuals were outdated, and now there is no such function and userData should be set in a different way. After digging through the Box2d files for three days, I realized that I could not cope alone.

I found out that it is possible to edit the b2FixtureDef structure to add my new data there. But I don't understand how to do this correctly, because just adding a line to the structure of the program crashes.

This is what I want to do:

```
class MyContactListener : public b2ContactListener
{
    void BeginContact(b2Contact* contact)
    {
        //check if fixture A was the foot sensor
        std::string fixtureUserData = contact->GetFixtureA()->getmy();
        if ((int)fixtureUserData == 3)
            fixturesUnderfoot.insert(contact->GetFixtureB());//A is foot so B is ground
        //check if fixture B was the foot sensor
        fixtureUserData = contact->GetFixtureB()->GetUserData();
        if ((int)fixtureUserData == 3)
            fixturesUnderfoot.insert(contact->GetFixtureA());//B is foot so A is ground
    }

    void EndContact(b2Contact* contact)
    {
        //check if fixture A was the foot sensor
        void* fixtureUserData = contact->GetFixtureA()->GetUserData();
        if ((int)fixtureUserData == 3)
            fixturesUnderfoot.erase(contact->GetFixtureB());//A is foot so B is ground
        //check if fixture B was the foot sensor
        fixtureUserData = contact->GetFixtureB()->GetUserData();
        if ((int)fixtureUserData == 3)
            fixturesUnderfoot.erase(contact->GetFixtureA());//B is foot so A is ground
    }
};

```

previously, it was possible, as I understood, to create a body and write:

```
body.setUserData = smth;
body.getUserData();

```

but this is not possible because the method returns a structure:

```
b2BodyUserData& b2Body::GetUserData()
{
    return m_userData;
}

struct b2BodyUserData
{
    b2BodyUserData()
    {
        pointer = 0;
    }

    /// For legacy compatibility
    uintptr_t pointer;
};

```

next to the structure definition, it is written "You can define this to inject whatever data you want in b2Fixture".

When I did something like this, the program is crashing:

```
struct B2_API b2FixtureUserData
{
    b2FixtureUserData()
    {
        pointer = 0;
        objectType = "";
    }
    std::string objectType;
    /// For legacy compatibility
    uintptr_t pointer;
};

```

# Answer
> 2 votes
It seems that box2d recently changed the way they manage userData. They went from storing `void` pointers to storing an actual object. So it may explain why you see tutorials around that "do no work" with a more recent version of Box2d.

This part of the official documentation illustrates how this should be done now, however it lacks an important information, IMHO.

The user data is an object that *you* control and you *need hold alive for the whole life of the box2d object*.

Since the userData deals with "opaque pointers" (Box2d does not know what those are nor what they're for, only you do), and the example uses raw pointers, Box2d will *not* clean the memory associated to those once the Box2d objects are destroyed, *you* need to take care of cleaning those.

A way to do it is to wrap those into smart pointers.

So somewhere in your code you need to create your own class:

```
struct MyFixtureUserDataType
{
    int mObjectType {};
    b2Fixture* mOwningFixture {};
}

```

Then when you create your fixtures, you also create the data:

```
// Store this somewhere in your game managing classes
std::vector<std::unique_ptr<MyFixtureUserDataType>> mFixtureUserData;

// Create your userData object
auto myUserData = std::make_unique<MyFixtureUserDataType>();
myUserData->mObjectType = 3; // whatever this fixture is about

// create the def
b2FixtureDef fixtureDef;
fixtureDef.userData.pointer = reinterpret_cast<uintptr_t>(myUserData.get());

// create your fixture
myUserData->mOwningFixture = body->CreateFixture( fixtureDef );

// Now you store you data
mFixtureUserData.emplace_back( std::move(myUserData) );
myUserData = nullptr;

```

Then when you destroy the fixture, you can remove the associated instance of MyFixtureUserDataType.

```
b2Fixture* myFixtureToDestroy = ....;

body->DestroyFixture(myFixtureToDestroy);

for ( int i = 0; i < mFixtureUserData.size(); ++i )
{
  if( mFixtureUserData[i]->mOwningFixture == myFixtureToDestroy )
  {
    std::swap( mFixtureUserData[i], mFixtureUserData[mFixtureUserData.size() - 1] );
    mFixtureUserData.pop_back();
    break;
  }
}

```

This is a trivial example; mFixtureUserData could also be an `std::map<[fixture pointer], std::unique_ptr<MyFixtureUserDataType>>` to allow faster search.

But you get the gist of it, the idea is to keep track of your user data in some way an make sure you clean it when you destroy the associated Box2d objects.

I've created a small complete-ish example here on coliru of this workflow.

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


# Question
Title: How can I assign a World.createBody to a variable after initialization, `var` and `val` don't work?
```
Class entity()
{ // there is obviously more code but i dont think if adding them will help
    val bodyInTheWorld: Body? = null // nulls mean that it will be initialised later, obviously
}

```

I need to set it to null because I need to do a

```
createThis.bodyInTheWorld = world!!.createBody(createThis.body)

```

in main.kt. And that I don't have access to the world object of the main class inside my entity.kt class

```
class main : ApplicationAdapter() {
    private var batch: SpriteBatch? = null
    private var image: Texture? = null
    private var player: entity? = null
    private var camera: OrthographicCamera? = null
    private var world: World? = null
    private val entities = mutableListOf<entity>()

    fun createObject(createThis: entity) // will create reference or copy issues probably...
    {
        if(!entities.contains(createThis))
                entities.add(createThis)
        createThis.bodyInTheWorld = world!!.createBody(createThis.body)
        var temporaryShape = PolygonShape()
        temporaryShape.setAsBox(50f, 1f)
        createThis.bodyInTheWorld.createFixture(temporaryShape, 1f)
    }

```

I was about to write more code but I couldn't fix this damn thing: if I set it to `var` the last line will tell me that it requires an immutable argument.

> *Smart cast to 'Body!' is impossible, because 'createThis.bodyInTheWorld' is a mutable property that could have been changed by this time*

And if I set it to `val`, the code doesn't let me do the main thing I want, which is to make that body exist in the world.

```
        createThis.bodyInTheWorld = world!!.createBody(createThis.body)

```

This time the problem is, by syntax and complexity, more reasonable at least, it tells me that I can only define `bodyInTheWorld` variable only once and that I already did that by setting it to null in entity.kt

I need help on this. This is the guide I used to implement box2d btw

# Answer
Well, so i added a double exclamation mark to the end of the createThis.bodyInTheWorld `createThis.bodyInTheWorld!!.createFixture(temporaryShape, 1f)` and everything suddenly started to work, i still have no idea how it works at all, anyone care to explain?
> 0 votes

---
Tags: libgdx, box2d, kotlin
---


# Question
Title: Unity3D: My Admob Setting window isn't showing properly
so i wanted to experiment with google ads using admob. i am following the official guide from google. i downloaded the Unity Package from official github and imported all the stuff. but i am unable to see all the options in admob settings window.

as soon as i press play button those ID field goes blank. i reimported all the files, downgraded the version but i cant get it to work. it keeps giving me error like assertion failed. some UI bugs. and sometime inspector freezes.

please guide me!

# Answer
> 0 votes
Did you open Unity dashboard, create the project, link the id's then use the scripts.

Do so then add these scripts. Watch this video, then if you want, copy these scripts into your project.

## SDK

Create a script, call it "sdk" then paste this:

```
using UnityEngine;
using UnityEngine.Advertisements;

public class sdk : MonoBehaviour, IUnityAdsInitializationListener
{
    [SerializeField] string _androidGameId;
    [SerializeField] string _iOsGameId;
    [SerializeField] bool _testMode = true;
    [SerializeField] bool _enablePerPlacementMode = true;
    private string _gameId;

    void Awake()
    {
        InitializeAds();
    }

    public void InitializeAds()
    {
        _gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsGameId
            : _androidGameId;
        Advertisement.Initialize(_gameId, _testMode, _enablePerPlacementMode, this);
    }

    public void OnInitializationComplete()
    {
        Debug.Log("Unity Ads initialization complete.");
    }

    public void OnInitializationFailed(UnityAdsInitializationError error, string message)
    {
        Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
    }
}

```

## Interstitial

Create a script call it "interstital" then paste this code:

```
using UnityEngine;
using UnityEngine.Advertisements;

public class interstitial : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] string _androidAdUnitId = "Interstitial_Android";
    [SerializeField] string _iOsAdUnitId = "Interstitial_iOS";
    string _adUnitId;

    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;
    }

    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }

    // Show the loaded content in the Ad Unit:
    public void ShowAd()
    {
        // Note that if the ad content wasn't previously loaded, this method will fail
        Debug.Log("Showing Ad: " + _adUnitId);
        Advertisement.Show(_adUnitId, this);
    }

    // Implement Load Listener and Show Listener interface methods:
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        // Optionally execute code if the Ad Unit successfully loads content.
    }

    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit: {adUnitId} - {error.ToString()} - {message}");
        // Optionally execite code if the Ad Unit fails to load, such as attempting to try again.
    }

    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Optionally execite code if the Ad Unit fails to show, such as loading another ad.
    }

    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}

```

## Rewarded

Create a script, call it "rewarded" then paste this code:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;

public class rewarded : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOsAdUnitId = "Rewarded_iOS";
    string _adUnitId;

    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;

        //Disable button until ad is ready to show
        _showAdButton.interactable = false;
    }

    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }

    // If the ad successfully loads, add a listener to the button and enable it:
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        Debug.Log("Ad Loaded: " + adUnitId);

        if (adUnitId.Equals(_adUnitId))
        {
            // Configure the button to call the ShowAd() method when clicked:
            _showAdButton.onClick.AddListener(ShowAd);
            // Enable the button for users to click:
            _showAdButton.interactable = true;
        }
    }

    // Implement a method to execute when the user clicks the button.
    public void ShowAd()
    {
        // Disable the button:
        _showAdButton.interactable = false;
        // Then show the ad:
        Advertisement.Show(_adUnitId, this);
    }

    // Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
    {
        if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
        {
            Debug.Log("Unity Ads Rewarded Ad Completed");
            // Grant a reward.

            // Load another ad:
            Advertisement.Load(_adUnitId, this);
        }
    }

    // Implement Load and Show Listener error callbacks:
    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }

    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }

    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }

    void OnDestroy()
    {
        // Clean up the button listeners:
        _showAdButton.onClick.RemoveAllListeners();
    }
}

```

## Banner

Create a script call it banner, then paste this code:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;

public class banner : MonoBehaviour
{
    // For the purpose of this example, these buttons are for functionality testing:
    [SerializeField] Button _loadBannerButton;
    [SerializeField] Button _showBannerButton;
    [SerializeField] Button _hideBannerButton;

    [SerializeField] BannerPosition _bannerPosition = BannerPosition.BOTTOM_CENTER;

    [SerializeField] string _androidAdUnitId = "Banner_Android";
    [SerializeField] string _iOsAdUnitId = "Banner_iOS";
    string _adUnitId;

    void Start()
    {
        // Disable the button until an ad is ready to show:
        _showBannerButton.interactable = false;
        _hideBannerButton.interactable = false;

        // Set the banner position:
        Advertisement.Banner.SetPosition(_bannerPosition);

        // Configure the Load Banner button to call the LoadBanner() method when clicked:
        _loadBannerButton.onClick.AddListener(LoadBanner);
        _loadBannerButton.interactable = true;
    }

    // Implement a method to call when the Load Banner button is clicked:
    public void LoadBanner()
    {
        // Set up options to notify the SDK of load events:
        BannerLoadOptions options = new BannerLoadOptions
        {
            loadCallback = OnBannerLoaded,
            errorCallback = OnBannerError
        };

        // Load the Ad Unit with banner content:
        Advertisement.Banner.Load(_adUnitId, options);
    }

    // Implement code to execute when the loadCallback event triggers:
    void OnBannerLoaded()
    {
        Debug.Log("Banner loaded");

        // Configure the Show Banner button to call the ShowBannerAd() method when clicked:
        _showBannerButton.onClick.AddListener(ShowBannerAd);
        // Configure the Hide Banner button to call the HideBannerAd() method when clicked:
        _hideBannerButton.onClick.AddListener(HideBannerAd);

        // Enable both buttons:
        _showBannerButton.interactable = true;
        _hideBannerButton.interactable = true;
    }

    // Implement code to execute when the load errorCallback event triggers:
    void OnBannerError(string message)
    {
        Debug.Log($"Banner Error: {message}");
        // Optionally execute additional code, such as attempting to load another ad.
    }

    // Implement a method to call when the Show Banner button is clicked:
    void ShowBannerAd()
    {
        // Set up options to notify the SDK of show events:
        BannerOptions options = new BannerOptions
        {
            clickCallback = OnBannerClicked,
            hideCallback = OnBannerHidden,
            showCallback = OnBannerShown
        };

        // Show the loaded Banner Ad Unit:
        Advertisement.Banner.Show(_adUnitId, options);
    }

    // Implement a method to call when the Hide Banner button is clicked:
    void HideBannerAd()
    {
        // Hide the banner:
        Advertisement.Banner.Hide();
    }

    void OnBannerClicked() { }
    void OnBannerShown() { }
    void OnBannerHidden() { }

    void OnDestroy()
    {
        // Clean up the listeners:
        _loadBannerButton.onClick.RemoveAllListeners();
        _showBannerButton.onClick.RemoveAllListeners();
        _hideBannerButton.onClick.RemoveAllListeners();
    }
}

```

**Do watch the video because it does contain some changes to the script and show to use.**

---
Tags: unity, android, google-play-services, admob
---


title: How to create a wavy beam?

text:
# Question
Title: How to create a wavy beam?
I want to implement a wavy laser beam similar to the Proton Backpack in Enter the Gungeon.

https://youtu.be/wl-o6gbMqFM?t=58

It's easy enough to draw a line from one point to another, but how to get the undulating curviness and the lighting effects?

I am working in Godot, but I could easily adapt techniques from Unity, if you know them, since Godot has similar resources.

I asked a version of this question in a Godot forum, but am also asking it here

# Answer
> 0 votes
One technique is the following.

# Answer
> 1 votes
Probably not the best method, but you could emit particles like a regular gun and draw a curved line between them, give them a certain lifespan and then apply shaders to the lines.

---
Tags: unity, 2d, godot, effect
---


# Question
Title: Position of Gameobject Changes When Hit Play Button
I have a 3D Humanoid model. When I press play button, suddenly position of model changes and collider doesn't match with model.

# Answer
This could be due to two things,
Animation
Start() Method

**Animation:**
You have an animation that offsets the character in the start. Try disabling animation/animator component on your player.

**Start Method:**
There is a script on your player that offsets the player in the start. Try disabling any scripts on your player and see if it works.

Noting the collider you have attached to the gameobject that doesn't move, it could be that a child of the main object is the one being moved. Parent is the one with the collider. If these solutions don't work, I think you will need to provide a little more detail.
> 1 votes

# Answer
Not sure if this may solve it, but try changing Update mode to Normal if it doesn't solve it try to desactivate Animator tab. if the latest solves your problems, that means that you should probably play with options in your currently used animations properties. That's all i can think of :)
> 0 votes

---
Tags: unity, collider
---


# Question
Title: Arranging points in a 2D grid so that successively added points approximate a square shape
So, I ran into a problem with placing points in a grid while always trying to fit them into a square. Here are some examples (the numbers represent the order of placement):

Placing 1 point:

```
0

```

Placing 2 points:

```
0 1

```

Placing 3 points:

```
0 1
2

```

Placing 7 points:

```
0 1 4
2 3 6
5

```

Placing 32 points:

```
0  1  4  9  16 25
2  3  6  11 18 27
5  7  8  13 20 29
10 12 14 15 22 31
17 19 21 23 24
26 28 30

```

Placing 36 points:

```
0  1  4  9  16 25
2  3  6  11 18 27
5  7  8  13 20 29
10 12 14 15 22 31
17 19 21 23 24 33
26 28 30 32 34 35

```

I need a way of finding the coordinates of a point from its index. For example:

```
f(0) = 0, 0
f(1) = 0, 1
f(2) = 1, 0
f(3) = 1, 1
f(4) = 2, 0
f(5) = 0, 2
f(6) = 2, 1
f(7) = 1, 2
f(8) = 2, 2
...

```

# Answer
You can use something like this:

```
Vector2Int GetCoordsOfPoint(int n) {
    int side = Mathf.FloorToInt(Mathf.Sqrt(n));

    int square = side*side;

    int difference = n - square;

    if (difference & 1 == 0) {
        return new Vector2Int(side, difference >> 1);
    } else {
        return new Vector2Int(difference >> 1, side);
    }
}

```

And the other way:

```
int GetNumberFromCoords(int x, int y) {
    int side = Mathf.Max(x, y);
    int min = x + y - side;

    return side * side + 2 * min + (y > x ? 1 : 0);
}

```

I've followed the convention of using x to number the columns and y to number the rows, which I think is opposite what you've shown in your last example, but you can exchange x & y if you need the opposite convention.
> 0 votes

---
Tags: mathematics, geometry, grid
---


# Question
Title: How to perform 2D vector graphics operations in Unity
I am currently working on a game that is drawn completely by 2d vector graphics operations like e.g.

* drawRoundedRectangle
* drawPolygon
* fillRect withBlur

**How can I perform such vector graphics operations in Unity?**

(The well documented things are bitmaps/sprites. For vector graphics operations, however, I don't have a clue)

# Answer
As far as Unity goes, it depends, & you may want to check out some 3rd Party assets to add the functionality you are looking for.

**Vectrosity** has been around for ages, it handles all kinds of line drawing and is easy to get going, very versatile, and robust.

For drawing vector-based scalable UI elements (like round rectangles and circles and so on) I have had good results with **Modern Procedural UI Kit**.

Both are on the Asset Store; not affiliated with either developer in any way.

MPUIKit on Asset Store Vectrosity on Asset Store
> 1 votes

---
Tags: unity, 2d, rendering, vector-art
---


# Question
Title: How to interact with inventory only and not the game
I have created an inventory in which you can select some objects that you can spawn. This is a button in a table in a inventory class. Spawning is done via left mouse button (just click on some position in the game screen). Another option is that you can also stop spawning by unselecting the selected object by clicking the same button as before (select/unselect). Issue is that when you click that button to unselect the object it also spawns it on the same position. Is there a way to ignore spawning when your click is inside the inventory ?

Here is inventory class. It is created in the main PlayScreen

```
private final Stage stage;
private final Label fpsCounter;
private ImageButton mineButton;
private ObjectSelector objectSelector;
private ClickListener mineButtonClickListener;

public Inventory(final SpriteBatch sb,
                 final InputMultiplexer inputMultiplexer,
                 final ObjectSelector objectSelector,
                 final float width,
                 final float height) {
    this.objectSelector = objectSelector;

    final Viewport viewport = new FitViewport(
            width,
            height,
            new OrthographicCamera()
    );
    stage = new Stage(viewport, sb);

    stage.addActor(buildObjectSelectionTable(width, height));
    inputMultiplexer.addProcessor(stage);
}

private Table buildObjectSelectionTable(final float width,
                                        final float height) {
    final Table table = new Table();
    table.center(); // Center table content
    table.setSize(width * 0.5f, height * 0.09f);
    table.setPosition(table.getWidth() / 2 , height * 0.01f);
    table.setZIndex(99);
    final Texture background = new Texture("menu.png");
    table.setBackground(new TextureRegionDrawable(new TextureRegion(background)));

    final Drawable over = new TextureRegionDrawable(
            new TextureRegion(new Texture("mine2_trans.png"))
    );

    final Drawable exit = new TextureRegionDrawable(
            new TextureRegion(new Texture("mine2.png"))
    );

    float v = table.getHeight() * 0.8f;
    over.setMinHeight(v);
    over.setMinWidth(v);

    exit.setMinHeight(v);
    exit.setMinWidth(v);

    ImageButton.ImageButtonStyle style = new ImageButton.ImageButtonStyle();
    style.imageOver = over;
    style.imageUp = over;
    style.imageDown = exit;
    style.imageCheckedOver = exit;
    style.imageCheckedDown = exit;
    style.imageDisabled = exit;

    mineButton = new ImageButton(style);
    mineButton.setSize(v, v);

    ImageButton imageButton2 = new ImageButton(over);
    mineButton.setSize(v, v);

    mineButtonClickListener = new ClickListener() {
        private boolean selected = false;

        @Override
        public void clicked(InputEvent inputEvent, float x, float y) {
            System.out.println("clicked " + System.currentTimeMillis());
            if (!selected) {
                selected = true;
                objectSelector.selectObject(
                        Gdx.input,
                        Mine.class,
                        Mine.getObjectWidth(),
                        Mine.getObjectHeight());
                mineButton.setDisabled(selected);
            } else {
                selected = false;
                mineButton.setDisabled(selected);
                objectSelector.unselectObject();
            }
        }
    };
    mineButton.addListener(mineButtonClickListener);

    table.add(mineButton).padLeft(10);
    table.add(imageButton2).padLeft(10);

    return table;
}

```

PlayScreen looks like this

```
public class PlayScreen implements Screen {
    .....
public PlayScreen(Game game) {
    this.game = game;
    camera = new OrthographicCamera();
    gamePort = new ScreenViewport(camera);

    // Create object selector
    objectSelection = new ObjectSelector<GameObject>(game.getBatch(), camera);

    // Set input listener
    inputListener = new InputListener(camera, objectSelection);
    inputMultiplexer.addProcessor(inputListener);

    // Create inventory scene
    inventory = new Inventory (
            game.getBatch(),
            inputMultiplexer,
            objectSelection,
            gamePort.getWorldWidth(),
            gamePort.getWorldHeight()
    );

    Gdx.input.setInputProcessor(inputMultiplexer);
}

@Override
public void render(float delta) {
    if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) {
        Vector2 position = PositionUtil.toUnProjectedVector2(camera, Gdx.input);
        objectSelection.spawn(position);
    }
}

```

# Answer
> 0 votes
**Update:**

Sorry, I did see your comment that the inventory is on screen at the same time, then forgot about it.

If they are both on screen at the same time, you are going to have to logically carve your screen up into a 'play area' and the 'inventory area', by knowing the `x` or `y` coordinates that each part occupies.

Then you will need to check that the cursor position generated by your input `Vector2` is inside the play area. If it is not, you simply ignore the click.

And if you haven't done so already, this is the time you really want to think about separating your game internal (logical) resolution from your screen (display) resolution.

**Original answer based on the wrong assumption that the inventory was an overlay:**

Personally, I would add some sort of flag to the `Playscreen` class, such as `boolean isInInventory = false;`, then flick it to `true` when the inventory is opened. Then you can

```
if (Gdx.input.isButtonPressed(Input.Buttons.LEFT && !isInInventory)) {

```

to ignore the click in the main screen. Set it back to `false` when you exit the inventory. If you have multiple non-play screens (score, etc), you might want to flick the logic and use the boolean to indicate the game is in play mode.

---
Tags: java, libgdx, scene2d, inventory
---


# Question
Title: Do games always use AI for defining behaviour of opponent players or is it just vector math?
I'm trying to learn how games implement tactics for opponents/enemy player.

In games like Street Fighter with maximum difficult, the opponent (computer) is too good at predicting and countering my moves. Do they use AI (like neural networks) for defining opponent behaviour or can it be achieved using vector math (linear algebra) and collision detection algorithms?

# Answer
"Real" AI in form of machine learning and neural networks still plays a niche role in game development. It is not unheard of, and considering that even mainstream engines like Unity add it to their tool belt, we might see more of it in the future. But it's usually not the default approach for implementing opponent behaviors.

When game developers talk about AI, then they usually mean techniques like:

I can't tell you which of these techniques the newest version of Street Fighter uses and how it uses them. But keep in mind that the Street Fighter franchise is over 30 years old now, its core gameplay formula did not change much over the decades and it always had pretty strong AI opponents which only evolved with every new iteration of the game. So I am certain that the AI code is really sophisticated by now, which might not make it the ideal study subject for a beginner in game AI programming.
> 2 votes

---
Tags: ai
---


# Question
Title: Which are the corresponding parameters for rect and pivot in exporting an editor defined sprite, to be re-created using Sprite.Create?
Which are the corresponding parameters for rect and pivot in exporting an editor defined sprite, to be re-created using Sprite.Create?

I've tried both .rect and .textureRect for storing the editor defined rect for a sprite and also .pivot, but it seems Sprite.Create is not able to re-create the sprite properly(?)

# Answer
> 1 votes
It appears that `Sprite.Create` takes a non-pixel based unit value for pivot and `sprite.pivot` is a pixel based unit.

For example, `sprite.pivot` for a (1000x500) image would be `(500,250)` but `Sprite.Create` wants `(0.5,0.5)`

---
Tags: unity, sprites
---


# Question
Title: How to disable motion blur in unity HDRP
This is probably a really simple question, but I just started trying to use Unity's HDRP, and was wondering if there was a way to remove the intense motion blur when moving the mouse.

Basically, is this what is needed to render the scene, or is it something that you can change?

Thanks!

# Answer
> 1 votes
**Yes you can disable it!**

Find a GameObject with a Post Process Volume attached (It will be probably be named "PostProcess" by default.)
There in the Post Process script, scroll and look for "Motion Blur", set its `Intensity` to 0.

---
Tags: unity, rendering, post-processing
---


# Question
Title: In the Unity editor, is there a setting to show every gizmo on a GameObject and its children when selecting that GameObject or one of its children?
I have a parent GameObject on which several colliders have been placed. I want to maneuver several children of this GameObject around these colliders, but I can't see the colliders if I don't have the parent selected. Is there a way for me to be able to always see the gizmos, such as the outlines of colliders, that are present on the parent GameObject and its children, while only selecting one of the child GameObjects?

I might be able to figure something out through script, but I'm specifically wondering if there's a setting built into Unity that can do this. If not, any script advice would also be appreciated.

# Answer
No built-in way of doing what you describe AFAIK.

Here's a quick-n-dirty script that will draw the parents' and all sibling's collider bounds when any child is selected:

public class Foo : MonoBehaviour
{

    void OnDrawGizmosSelected()
    {
     //GetComponentsInChildren also returns components on parent
        var colliders = transform.parent.GetComponentsInChildren<Collider>();

        Gizmos.color = Color.green;

        foreach(Collider col in colliders)
        {
            var points = GetBoundsPoints(col.bounds);
            DrawPoints(points);
        }
    }

    Vector3[] GetBoundsPoints(Bounds bounds)
    {

        Vector3[] points = {
            bounds.min,
            new Vector3(bounds.max.x,bounds.min.y, bounds.min.z),
            new Vector3(bounds.min.x,bounds.max.y, bounds.min.z),
            new Vector3(bounds.min.x,bounds.min.y, bounds.max.z),
            new Vector3(bounds.max.x,bounds.max.y, bounds.min.z),
            new Vector3(bounds.min.x,bounds.max.y, bounds.max.z),
            new Vector3(bounds.max.x,bounds.min.y, bounds.max.z),
            bounds.max
        };
        return points;
    }

    void DrawPoints(Vector3[] points)
    {
        Gizmos.DrawLine(points[0], points[1]);
        Gizmos.DrawLine(points[0], points[2]);
        Gizmos.DrawLine(points[0], points[3]);
        Gizmos.DrawLine(points[1], points[4]);
        Gizmos.DrawLine(points[2], points[5]);
        Gizmos.DrawLine(points[3], points[5]);
        Gizmos.DrawLine(points[4], points[7]);
        Gizmos.DrawLine(points[5], points[7]);
        Gizmos.DrawLine(points[6], points[7]);
        Gizmos.DrawLine(points[1], points[6]);
        Gizmos.DrawLine(points[2], points[4]);
        Gizmos.DrawLine(points[3], points[6]);

    }
}
```

> 1 votes

---
Tags: unity, editors
---


# Question
Title: How to move the shadow map with the camera?
I implemented a directional light and a shadow map for that light based on learnopengl.com tutorials. And it is working great, but I would like to move the shadow map with camera/player, so I have shadows all over the scene.

What I am trying to do is update the "look at" matrix every frame, based in the camera position, but is not working properly. Here is relevant peace of code, witch I am using to update the shadow map position:

```
    glm::mat4 lightProjection = glm::ortho(-20.0f, 20.0f, -20.0f, 20.0f, 1.0f, 7.5f);
    glm::mat4 lightView = glm::lookAt(light.position + camera.position, camera.position, glm::vec3(0.0f, 1.0f, 0.0f));

```

With the light at position x: -1.0f y: 4.0f z: -1.0f:

# Answer
> 1 votes
Calculate the view frustum boundary points, calculate the center of each of the near and far planes, and use vector add/subtract to define topleft, topright, bottomleft and bottomright.

Then, calculate the view frustum boundary points and construct an orthographic projection matrix that keeps all the points in view.

```
float ar = (float)SCR_WIDTH / (float)SCR_HEIGHT;
float fov = glm::radians(camera.Zoom);
float nearDist = 0.01f;
float farDist = 100.0f;
float Hnear = 2* tan(fov/2) * nearDist;
float Wnear = Hnear * ar;
float Hfar = 2* tan(fov/2) * farDist;
float Wfar = Hfar * ar;
vec3 centerFar = camera.position + camera.front * farDist;

vec3 topLeftFar = centerFar + (camera.up * Hfar/2) - (camera.right * Wfar/2);
vec3 topRightFar = centerFar + (camera.up * Hfar/2) + (camera.right * Wfar/2);
vec3 bottomLeftFar = centerFar - (camera.up  * Hfar/2) - (camera.right * Wfar/2);
vec3 bottomRightFar = centerFar - (camera.up * Hfar/2) + (camera.right * Wfar/2);

vec3 centerNear = camera.position + camera.front * nearDist;

vec3 topLeftNear = centerNear + (camera.up * Hnear/2) - (camera.right * Wnear/2);
vec3 topRightNear = centerNear + (camera.up * Hnear/2) + (camera.right * Wnear/2);
vec3 bottomLeftNear = centerNear - (camera.up * Hnear/2) - (camera.right * Wnear/2);
vec3 bottomRightNear = centerNear - (camera.up * Hnear/2) + (camera.right * Wnear/2);

vec3 frustumCenter = (centerFar- centerNear)*0.5f;

mat4 lightView = glm::lookAt(normalize(light.position), vec3(0,0,0), vec3(0,0,1));

std::array<vec3, 8> frustumToLightView
{
    lightView * vec4(bottomRightNear, 1.0f),
    lightView * vec4(topRightNear, 1.0f),
    lightView * vec4(bottomLeftNear, 1.0f),
    lightView * glm::vec4(topLeftNear, 1.0f),
    lightView * vec4(bottomRightFar, 1.0f),
    lightView * vec4(topRightFar, 1.0f),
    lightView * vec4(bottomLeftFar, 1.0f),
    lightView * vec4(topLeftFar, 1.0f)
};

// find max and min points to define a ortho matrix around
vec3 min{ INFINITY, INFINITY, INFINITY };
vec3 max{ -INFINITY, -INFINITY, -INFINITY };
for (unsigned int i = 0; i < frustumToLightView.size(); i++)
{
    if (frustumToLightView[i].x < min.x)
        min.x = frustumToLightView[i].x;
    if (frustumToLightView[i].y < min.y)
        min.y = frustumToLightView[i].y;
    if (frustumToLightView[i].z < min.z)
        min.z = frustumToLightView[i].z;

    if (frustumToLightView[i].x > max.x)
        max.x = frustumToLightView[i].x;
    if (frustumToLightView[i].y > max.y)
        max.y = frustumToLightView[i].y;
    if (frustumToLightView[i].z > max.z)
        max.z = frustumToLightView[i].z;
}

float l = min.x;
float r = max.x;
float b = min.y;
float t = max.y;
// because max.z is positive and in NDC the positive z axis is
// towards us so need to set it as the near plane flipped same for min.z.
float n = -max.z;
float f = -min.z;

// finally, set our ortho projection
// and create the light space view-projection matrix
mat4 lightProjection = ortho(l,r,b,t,n,f);
mat4 lightSpaceMatrix = lightProjection * lightView;

```

Sources:

http://www.lighthouse3d.com/tutorials/view-frustum-culling/geometric-approach-extracting-the-planes/

https://community.khronos.org/t/calculating-tight-ortho-projection-matrix-for-shadow-mapping/105588

---
Tags: opengl, shadow-mapping
---


# Question
Title: Creating dependent values in the Unity inspector
I want to create a few values which will be dependent on each other. Specifically, I want total sum of few values always be 100 In unity inspector no matter how I tweak them.

E.G.:

```
int total = 100;

int one = 20;
int two = 30;
int three = 45;
int four = 5;

```

How can I make other values adjust automatically if I tweak one of them in Unity Inspector?

# Answer
> 3 votes
You can provide an `OnValidate()` method, which gets called in the Editor when the user changes an Inspector value.

```
const int TOTAL = 100;
public int one, two, three, four;

#if UNITY_EDITOR
// Save their previous values so we can identify which one changed.
int _oneCache, _twoCache, _threeCache, _fourCache;
_oneCache = -1;

void OnValidate() {
    // Skip this if we haven't cached the values yet.
    if(_oneCache >= 0) {

        // Find which value the user changed, and update the rest from it.
        if(_oneCache != one) {
            DistributeProportionately(ref one, ref two, ref three, ref four);
        } else if (_twoCache != two) {
            DistributeProportionately(ref two, ref one, ref three, ref four);
        } else if()
            // ... repeat for three, four...
        }
    }

    // Cache the old values for the next edit.
    _oneCache = one;
    _twoCache = two;
    _threeCache = three;
    _fourCache = four;
}

void DistributeProportionately(ref changed, ref int a, ref int b, ref int c) {
    changed = Mathf.Clamp(changed, 0, TOTAL);
    int total = TOTAL - changed;

    int oldTotal = a + b + c;
    if(oldTotal > 0) {
        float fraction = 1f/oldTotal;
        a = Mathf.RoundToInt(total * a * fraction);
        b = Mathf.RoundToInt(total * b * fraction);
        c = Mathf.RoundToInt(total * c * fraction);
    } else {
        a = b = c = total / 3;
    }

    // Assign any rounding error to the last one, arbitrarily.
    // (Better rounding rules exist, so take this as an example only)
    c += total - a - b - c;
}

#endif

```

This can be done with a custom editor too without explicitly caching each value (instead you'd use an `EditorGUI.BeginChangeCheck` to identify the changed field), but for quick data validation I like to keep it in one file.

If you're using these to ensure a set of probabilities add up to 100%, then you might want to consider treating the user-facing values as *relative weights* instead, and keep the normalized values internal:

```
[SerializeField]
[HideInInspector]
float[] _normalizedProbabilities;

#if UNITY_EDITOR
[SerializeField]
float[] _probabilityWeights;

void OnValidate() {
    float totalWeight = 0f;
    foreach(var weight in _probabilityWeights)
        totalWeight += weight;

    if(totalWeight == 0f)
        return;

    _normalizedProbabilities = new float[_probabilityWeights.Length];
    for(int i = 0; i < _probabilityWeights.Length; i++)
        _normalizedProbabilities[i] = _probabilityWeights[i]/totalWeight;
}
#endif

```

This tends to be a lot simpler to manage.

# Answer
> 1 votes
Here is my solution for it, which also supports locking elements so that changing one, does not affect every other value.

```
private bool[] _lockStates;
public override void OnInspectorGUI()
{
    var data = (TrickChargeButtonsController) target;
    base.OnInspectorGUI();

    if (_lockStates == null || _lockStates.Length != data.normalizedValues.Length)
    {
        _lockStates = Enumerable.Range(0,data.normalizedValues.Length).Select( n=>false).ToArray();
    }

    if (GUILayout.Button("Normalize"))
    {
        for (int i = 0; i < data.normalizedValues.Length; i++)
        {
            data.normalizedValues[i] = (float)1.0f / (float)data.normalizedValues.Length;
        }
    }

    float totalLength = 1.0f;
    for (int i = 0; i < data.normalizedValues.Length;i++)
    {
        var lockedCount = _lockStates.Sum(isLocked => isLocked ? 1 : 0);
        var prior = data.normalizedValues[i];
        GUILayout.BeginHorizontal();
        var oldValue = data.normalizedValues[i];
        data.normalizedValues[i] = GUILayout.HorizontalSlider(data.normalizedValues[i],
                                                                             0f,
                                                                             totalLength);
        if (_lockStates[i] || lockedCount >= data.normalizedValues.Length-1)
        {
            data.normalizedValues[i] = oldValue;
        }
        if (GUILayout.Button(_lockStates[i] ? "unlock" : "lock"))
        {
            _lockStates[i] = !_lockStates[i];
        }
        GUILayout.EndHorizontal();
        var after  = data.normalizedValues[i];
        if (lockedCount < data.normalizedValues.Length-1)
        {
            var delta = (after - prior)/(data.normalizedValues.Length-lockedCount-1);
            for (int j = 0; j < data.normalizedValues.Length; j++)
            {
                if (i != j && !_lockStates[j])
                {
                    var test = data.normalizedValues[j] - delta;
                    var adjustedDelta = delta;
                    if (test < 0f)
                    { // we cant allow this to happen , backtrack previous value.

                        adjustedDelta -= -test;
                        data.normalizedValues[i] += test;
                    }
                    data.normalizedValues[j] -= adjustedDelta;
                }

            }
        }
        GUILayout.Space(12.0f);
    }

}

```

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


title: How can I modify Enchanting Rules?

text:
# Question
Title: How can I modify Enchanting Rules?
TL;DR is there a way to modify the enchantments that equipment can receive from an Enchanting Table?

* Working on a "lazy" addon that simplifies some things I do often.
* One big time waster is trying to get the right enchantments (i.e. keep getting the wrong type of Protection, or Bane of Arthropods instead of Sharpness).
* I'd like to remove some of those undesired enchantments from the logic so that only the ones I actually use will appear on the enchanting table.

I see a few ways to go about this, but none are very good...

1. Modify the game's internal rules for which enchantments apply to which equipment types. This isn't surfaced anywhere in the "Vanilla" packs, so it seems to be impossible.
2. Create a new option for `minecraft:enchantable` that has the enchantments I want (i.e. `"slot": "sword2"` which has Sharpness but not Smite). Would then modify each type of equipment to use the new "slots." This is also not present in the Vanilla packs and seems to be impossible.
3. Create a new type of table which uses some functions to apply some enchantments.

#3 seems like the only method that's possible in Bedrock. And yes, I know I can use command-blocks/NPCs to give me a sword with Sharpness level 9000 :). I'm just trying to smooth over the edges of the core gameplay (and learn a bit along the way), not completely reinvent it.

--- Edit ---

Well, I found a partial workaround

* Created an mcfunction that does the right stuff
    + Currently targeting all players (@a) while I troubleshoot.
* If I run it with /function it works
* If I run it via a command block, it works
* But if I tie it to a custom block via 'on\_interact' it only partially works. The sound and particle effects play, even my levels are drained, but the enchantment doesn't happen. It seems somehow tied to the context in which the block is executing. But I tried various methods to "target" any/all players and it doesn't work.

Any ideas?

# Answer
> 1 votes
For anyone who encounters this...

* I found no straight-forward way to modify enchanting rules in any way (create a new category, modify existing categories, etc).
* I also found no way to make a block target a player for enchantments. Everything else worked, just not enchantments.
* For enchantments, it seems you need a dialog, which lets you target `@initiator`. But this requires an NPC.
* There also seems to be no way to create an NPC with a pre-canned `dialog`. You must go into creative mode and set it in-game.
* So my solution uses a block which summons an NPC when you place it. When you interact with the block, it triggers a dialog (tied to the nearby NPC). Targeting the NPC results in an empty dialog (see previous bullet) so not ideal, but at least it "works."
* While I'm ultimately pleased with the result, it's a far cry from what I set out to do, and greatly deterred by the unnecessary limitations inherent to Bedrock. If you really want to make content, just target Java.

---
Tags: minecraft-bedrock-modding
---


# Question
Title: How do I "voxelize" an OBJ mesh that was created in a voxel editor?
I've been trying to find the right workflow to solve my problem for over a month now. Any tip/insight would be *greatly* appreciated.

**Scenario**: I create a voxel mesh in MagicaVoxel and then, instead of using MagicaVoxel's limited tools/shaders to texture my mesh, I export my voxel mesh as an OBJ in my 3D software (Cinema 4D in my case) to texture it with bitmap-based textures and brushes. After I'm done texturing said OBJ mesh, without any change to its position/scale/rotation, **I would like to export it back into MagicaVoxel (i.e. in its original voxel structure) for further sculpting/iterating**.

**What I've tried**: I must have tried every free/paid Voxelizer out there that support color data (QuBicle, BinVox, a myriad of tools found on Github, etc) and none of them have allowed me to have control over the voxel grid matrix. This means that every Voxelizer I've tried has given me a .VOX mesh (as desired), but with tons of offset/misplaced/missing/added voxels, so not an identical 1:1 recreation of the voxel mesh I originally created in MagicaVoxel. I imagine this is due to the Voxelizer not knowing where every voxels' center is on the OBJ mesh, hence giving me a very imprecise result.

**Potential lead**: Thankfully, amongst many other exporting formats, MagicaVoxel allows me to export my voxel mesh as "PLY mesh" or "point clouds" data. I see a potential solution here, as I feel like I could use (for example) the point cloud data as a reference for what the voxel grid matrix should be. The question is; what software am I pumping this point cloud data into?

**Conclusion**: The closest I've gotten so far is feeding MagicaVoxel's point cloud data into CloudCompare and then feeding whatever I attempted (without success) in CloudCompare into FileToVox. Still... despite it all, I cannot get my newly textured OBJ mesh to be translated back into its 1:1 voxel state as a .VOX file.

At this point, *any* glimpse of help or guidance would be *greatly* appreciated, as I feel quite lost currently, despite feeling "close" in some ways.

Thanks a million.

# Answer
> -1 votes
I'd leave a comment, but I haven't the reputation points yet.

Check out: https://github.com/sjhalayka/point\_to\_mesh/blob/0e28b41e47e4d4d0bf2b2178a17cb0ad0b8dfccb/main.h#L308

It first finds the x, y, z extents of the point cloud, and then it finds an integer index for each x, y, z, where the final index is

```
size_t index = z_index * res * res;
index += y_index * res;
index += x_index;

```

Does this help at all?

---
Tags: voxels, obj, point-cloud, cinema-4d, magicavoxel
---


title: Change Sprite's Position

text:
# Question
Title: Change Sprite's Position
I have a sprite attached to the player like an accessory and it flips along with the player when moving in the opposite direction. However, due to the player being a dog, when flipped, the accessory only flips and the position doesn't change. I want to move that sprite to a bit left every time the player flips.

```
if (Input.GetAxis("Horizontal") < 0)
    { spriteRnderer.flipX = true; bandanaRenderer.flipX = true; }
else if (Input.GetAxis("Horizontal") > 0)
    { spriteRnderer.flipX = false; bandanaRenderer.flipX = false; }
transform.position += new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime * speed, 0);
animator.SetFloat("Speed",Mathf.Abs(Input.GetAxis("Horizontal") * Time.deltaTime * speed));
jumpSpeed = 0;

```

# Answer
> 1 votes
When the horizontal axis is \< 0, just rotate the player instead of flipping like this:

```
if (Input.GetAxis("Horizontal") < 0)
{
    transform.eulerAngles = new Vector3(0,180,0);
}
else if (Input.GetAxis("Horizontal") > 0)
{
    transform.eulerAngles = new Vector3(0,0,0);
}

```

The same applies to any sprite.

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


# Question
Title: Why are people developing and publishing games online without charging money?
What's the incentive of sharing games one designs themselves for free online such as itch.io? I see people doing this and I don't understand.

# Answer
> 345 votes
There's a certain irony to asking this question on a site where people volunteer their time to help fellow gamedevs without compensation. ;)

It's okay to value a thing and find it fulfilling even if you don't get paid for it.

If I wanted to maximize my income, there are many fields I'd be better-advised to work in than game development. ;)

Instead, for me at least, I do it for the love of the challenge of gamedev itself, and for the love of play.

Seeing folks enjoy a game I've worked on is a huge win for me, even when there's not a penny attached to it:

By sharing this game freely, it's gotten more people playing & enjoying & sharing it than I expect it would have even at a miniscule price, which for me (since I have a full-time game development job to support my livelihood separate from these hobby games) is a worthwhile trade.

Of course, there are also capitalistic reasons to share stuff freely too:

* testing the waters to see if there's interest in the concept & gather feedback for a future commercial version
* offering a "free sample" as marketing for such a commercial version or expansion
* building a visible portfolio & reputation to demonstrate your skills to potential employers
* fostering & entertaining an audience of followers that you can leverage to access future opportunities

...but my point is that these aren't the only things that can make it satisfying and worthwhile.

Sharing content for free might not enrich my bank account, but I believe/hope, in some small way, it enriches the world.

# Answer
> 91 votes
Releasing your game for free is the best way to get it exposed to the largest number of people possible. There are several reasons why you would want to prefer reach over profit:

* Making money through **advertising**. A lot of game portals use advertisement. On some portals, game creators get a cut of the revenue of the advertisement which appears next to their game. You can also integrate ads directly into your game. Or someone might actually pay you to create a game which advertises their product (anyone remember Moorhuhn, that advertisement game for Johnny Walkers whiskey which broke the Internet in 2000? Or maybe it was just a German phenomenon...).
* **Grow first, think about monetization later**. Get as many players as you can for now, and when they are all addicted to your game, look for a way to make them pay to keep playing.
* **Making a name for yourself**. When you created that free web game everyone knows and a few years later you release a new game for $19.99 on Steam, you can market it as "The new game from that guy who created that awesomely addictive web game in 2019". Anyone who played your previous game will get curious about whether you were able to build on your success or not. In today's game market, it's all about exposure. A developer who already has a reputation for making a few good games has a much better chance to make it than someone who is completely unknown.
* **Building a portfolio**. When you are looking for a job in the game development industry, people will want to know if you have experience. A great way to convince people that you know your craft is to point them to a few games you created. When your games are free, they can play them right away.
* **Practicing your skills and collecting feedback**.

+ The only way to find out if your game design is good or bad is to let people play it and listen to their feedback. The more people play it, the more feedback you will get. Feedback also gets more honest for more popular games. You can read people publicly discussing your game who are unaware that you will read them. This allows you as a game designer to learn what works, what doesn't work and thus improve your design skills.
    + The most nerve-wracking part of game development is the release. But it becomes a much less serious endeavour when there is no money involved. Releasing your "practice game" for free is a valuable experience which will help you to become a bit less afraid of the release of your first "real game".
    + You can even use free web games as a medium for testing a new game idea. You create a simple prototype, upload it for free, see how people react to it and when people like it you use the game idea for a new full-price game with proper production values.
* **Doing it for the art**. Some people want to make games as a form of self-expression without commercial interests. Maybe you have something to say through your game. Maybe you just want to make people happy, and that's reward enough.

# Answer
> 38 votes
I've designed, built and released for "free" (see below) quite a few games in my life. From my perspective, these are the main reasons, in no particular order:

* The chance to make enough of a profit to actually justify the added effort and overhead of billing is not big enough. Most indie games don't make money in a quantity worth it, and the billing part is not fun, while making a game is.
* The line between amateur and commercial can only be crossed once, forever. For a free game, I can take it down, stop developing and supporting it, etc. at any time I feel like it. No obligations. Once people have paid for it, they are customers and have rights (moral and/or legal).
* Along the same line, I release many games in a half-finished state, basically once it is playable. They don't have the quality that I would expect from a finished, commercial game. For free, that is ok with me. For payment, I would feel myself to be a cheat.
* Money later - I make games for fun, my fun. Money is an afterthought. That is why I put "free" in quotation marks above. Some of my games have ways to pay me, usually optional, e.g. donations or cosmetic DLCs or other premium features. But the gameplay itself I keep free because I don't like to play bait & switch with my players.

These are my personal reasons, and other people have others.

Note also that "free" is not always entirely free. Some games have advertisement, or product-placement tie-ins, or follow a shareware model, or follow one of the many other routes to profit.

# Answer
> 25 votes
There's no single reason that covers all situations. Here are the ones that come to mind:

1. **Labor of love** \- Some developers make games purely for the enjoyment of creating them and want to share their results with others.
2. **Building a player base** \- In some instances, a developer may choose to release a game for free as an initial step toward building up a player base for a later game. In particular, crowd funding efforts are often more successful when they launch with a strong first day; giving a game away one way to build that day one audience.
3. **Building a portfolio** \- One of the best ways to demonstrate that you can make games is to demonstrate the games you've made. Some people start with releasing small free games to build personal experience & reputation.
4. **Reducing work** \- Unfortunately, as soon as money becomes in involved, some things become more complicated. User's expectations for support increase. There's often more paperwork & book keeping to deal with taxes, income, etc. Some developers just want to focus on development, not business.
5. **It's only free today** \- Not all games stay free. Some platforms give developers the option of changing the price. Some developers may release for free initially (for instance during early access) and charge for it at a later date.

# Answer
> 23 votes
I make not only games, also apps for free. I do it, because I enjoy it. None of my products has even ads included. Why? Because I do not like ads. I do not want to give away the screen space and every app looks better if there are no shiny blinkyblinky ads on the screen that catch your eye.

Even on my homepage I have these wordings:

> Success is not just making money. Success is happiness. Success is fulfillment; it's the ability to give. Adam Neumann

and my personal statement:

> I love coding. I love apps. And I hate ads. My apps do not contain ads, my main focus is not "making money". I don't care. Honestly. I write apps because I love to write apps.

I already have a (well paid) fulltime developer job and the things that I do at home, I do for me, for friends (but they all are published globally through play store) because I **want** to have that one specific feature, that one app that does exactly what I want.

I am always happy when I receive ratings on my apps or when someone drops me a mail. That's enough for my personal wellbeing.

I would **not** want to have to make a living out of things I write at home. I am not the freelancer type, I am not the business type. Just a geek that can't get enough code in his life :-)

That's why I do it. I can't think of a better reason. Cheers!

# Answer
> 7 votes
### The project you *want* to make might not be commercially viable

I'm a fan of some rather niche and/or oldschool genres, as well as quite complex mechanics in general. Finding games that scratch the right itch has become difficult. Of a handful of promising projects, most get canceled or turn out mediocre. There's also a general trend to simplify mechanics, presumably to appeal to more casual audiences or work with the more limited input options of consoles. Compare the original Deus Ex or Baldur's Gate to modern RPGs, for example.

My team's current project has been in the making for several years (it's complex), and I'm fairly certain that it will only appeal to a (relatively) niche audience. The only way I'd expect it to be commercially successful would be with a "big name" license like WH40k or Battletech, which we lack the funds for.

We're making the game because we think someone should, because we want this game to exist, and to share it with the people who appreciate the genre. And we'd rather make *this* game than something that makes more money but doesn't interest us.

### Selling your game comes with opportunity costs

You don't ~~make~~ earn money without some planning, marketing, managing. All that costs time, which is a limited resource. Any use of your time has to be weighed against what else you could be doing.

Now, I can justify spending time and money on creating something that has value to me (a great game), but *making* money selling games only makes sense if you can make more this way than you otherwise would. If you're good at (and like doing) more than one thing, why not pick the one that pays best as your job and do everything else as a hobby?

# Answer
> 7 votes
Some supporters of the **free software** and/or **open source** movements make games and release them for free purely to support those movements and increase the pool of free/open source games. For example, the Minecraft clone Minetest.

Personally I am not one of these people, but I know a handful of people who are.

---

Some people release their games for free because they want other people to benefit from those games somehow, e.g. by being able to learn programming techniques from them, or simply so they can enjoy them.

I'm actually a moderator on two programmable game console forums where every person who contributes a game does so free of charge. It's part of the culture - **the games exist purely for fun and education, not for profit**.

# Answer
> 2 votes
In addition to the non-monetary benefits covered in other answers, there can be significant and immediate monetary benefits to releasing your game for free and then asking for voluntary payment under a "pay-what-you-want" model (either directly or indirectly with a subscription using a tipping service).

As many developers of mobile games have figured out, a small number of whales account for a large portion of income. Thus, impeding any potential whale from discovering your game (say because of risk-aversion) may lose you more money than you gain from minimum-price sales.

You may think this is limited to mobile games with predatory monetization, but I have seen similar whale behaviour in video game crowdfunding campaigns and in gaming-related content like livestreams. I also know of some developers in... "niche" fields you do not speak about in pleasant company who release games for free and enjoy a respectable income in the form of tips and are doing better than their peers making games under a traditional fixed-price scheme. It should be noted that none of these cases goes to the extreme distribution seen by whales in mobile games nor have they undergone any rigorous analysis so such anecdotes should be taken with a grain of salt.

Psychology Today identifies three situations where a pay-what-you-want pricing scheme has worked:

1. Last minute sales to fill capacity (ex. in a theatre). For software, capacity isn't really a thing, but the idea is to generate some amount of sales when you would normally get none. This is the model used by various bundle sites: long after release some amount of money can be extracted by having customers pay something. Obviously, this is different from a game released for free from the get-go, but as other answers have noted for commercially unviable games, some amount of money can be extracted this way without having to go through market research and pricing analysis and other wonderful such things you might not care to do (or even dislike).
2. When customers have a personal relationship with the business owner. If you look less like a faceless company and more like a person people want to cheer on and succeed, it turns out people are more likely to give you money. If it feels like you care about them, listen to them, and address their concerns, people are more likely to give you tips.
3. When charity is given a cut. It's pretty unlikely you're a charity or will find an appropriate one to partner with. However, as far as I can tell if it feels like you're giving free contributions to a community, some members of that community will be inclined to give back to you, though I typically see it in the form of work-for-work (ex. improved art for a game) as opposed to money. (money isn't unseen, it just seems most value comes back in the form of other work)

# Answer
> 0 votes
Retrospectively by looking at your question, there is an implied connection between spending time on a game and monetary returns. **The same notion can apply to the consumer** \- there is the friction of parting your money to purchase a game. If you're new to the scene and you don't have much of a following it becomes hard to gain an audience. If the game is free, then you will attract more customers.

# Answer
> 0 votes
The advice for would-be game devs is to start small and ship.

Jumping through the hoops to actually sell a game rather than just distributing it takes time and therefore money. Games like this just don't sell anyway. If all you can hope for is experience and possibly feedback to make better, bigger games in the future, then free, friction-free distribution is exactly what you want. And exposure, if you are incredibly lucky and your basic games really catch on.

# Answer
> 0 votes
There are a lot of reasons for this

1. The publisher is attracting crowd to his website or his platform where he could potentially sell more stuffs that he has when he attracts enough interested people.
2. when you give away something like developed games or assets what you do is create a liking for you from the person who wants that thing and there are people who are desperate to have more resources to go forward.
3. when you gather enough people to your site or channel you eventually could make more things like those and probably sell those games and assets to people who liked your free stuffs and they would also share and make new things and do this themselves of sharing for free and voila you have created a chain of free assets and games.

also people just do it because they want to share things with people like shawn mentioned above...hope it helps :D

# Answer
> 0 votes
I would like to add

* you might have a vision you want to share
* you might have been annoyed that a certain game does not exist, so you create it and share it with other people to spare them from the same annoyance

# Answer
> -1 votes
People who release free games are are either **educated** or **uneducated** on the topic of game development `business` or `selling` their game as a product.

* **Uneducated:** Don't understand the value of their own product yet, don't know how to advertise it or who to advertise it to.
* **Educated:** Understand the potential value, know their niche and release a free demo.

There are also the exceptions from the rule:

* Concept validating
* Hackathon
* Open-source
* Demo for an engine

The above is triggered by the low barrier of **personal costs and time of developing and releasing** that game engines like Unreal, Unity, GameMaker, etc. have enabled. The cost and time is not perceived as something important by a large portion of **uneducated** **younger mass** of game makers who accesses these tooling.

Newcomers **can afford** to release free games or at least they are being fooled by the current market and culture that they can.

---
Tags: business
---


# Question
Title: How many database servers does an online game need to handle around 100000 users per day?
I don't need an exact number but I want to know roughly how many MySQL servers do I need to rent if I were to develop an online RPG game that has roughly 100000 users per day (assuming on average 1 hour per user-day)?

To clarify a little bit, I am asking for only the number of MySQL servers and this does not include other API servers. MySQL servers are used to save user data such as name, level, weapons, inventory .etc.

Also since master servers are more expensive than slave servers so I would like to know how many master servers are needed and how many slaves are needed per master. Again, I only need a rough estimation based on experience and feeling, not an exact number.

If anyone has experience about this number and are kind enough to share it I will really appreciate.

# Answer
> 5 votes
I'm sorry, but we can not even give you a rough estimate as long as we do not know anything about your game. We do not know how many SQL queries each player generates. It could be anything between one SELECT and one UPDATE per session (one when they log in and one when they log out) or they could be generating multiple queries per second. And we also don't know how complex those queries are. They could be simple ones which only take microseconds to answer, or very complex ones which keep your whole MySQL cluster busy for seconds.

So in order to get at least the order of magnitude correct, you won't get around making a load-test. Tell your development team\* to develop your gameserver to a level that it can access a database and send a couple queries which are similar to the usage patterns you would expect from the clients. Then spin up a small SQL server for load-testing. SQL queries will scale with the amount of data in the tables you query. So you also need to generate an appropriate amount of test data. Then simulate a couple thousand players on your server, check the load on the SQL server and extrapolate.

<sub>* You do have a team, right? MMORPGs are among the most complex and expensive games to develop and operate. They are not projects you can pull off as a solo developer.</sub>

---
Tags: mmo, server, mysql, scalability
---