# Question
Title: Elongated and straight terrain perlin noise
Why am I getting this kind of results with my perlin noise ? The terrain is wide or elongated or straight at the variations of the noise function.

This is the way I generate terrain:

```
    public void GenTerrain()
    {
        for (int x = 0; x < this.size.x; x++)
        {
            for (int y = 0; y < this.size.y; y++)
            {
                float xCoord = (float)(x + offsetMirror + origin.x) / this.size.x * scale;
                float yCoord = (float)(y + offsetMirror + origin.y) / this.size.y * scale;
                float noise = Mathf.PerlinNoise(xCoord, yCoord);

                if (noise > 0.6f)
                {
                    this[x, y].terrainType = TerrainType.Grass;
                }
                else if(noise > 0.5f)
                {
                    this[x, y].terrainType = TerrainType.Sand;
                }
            }
        }
    }

```

This is the way I add chunks of terrain

```
    void Start()
    {
        maps = new Dictionary<Vector2Int, Map>();

        Res.LoadMaterials();

    }

    void AddNeighbours(Vector2Int position)
    {
        int length = 32;
        for(int x = -length; x <= length; x++)
        {
            for(int y = -length; y <= length; y++)
            {
                Vector2Int addPos = new Vector2Int((x * size) + position.x, (y * size) + position.y);
                CheckAndAddMap(addPos);
            }
        }

    }

    void CheckAndAddMap(Vector2Int addPos)
    {
        if (!maps.ContainsKey(addPos))
        {
            AddMap(addPos);
        }
    }

    void AddMap(Vector2Int origin)
    {
        Map map = new Map(new Vector2Int(size, size), origin);
        maps.Add(origin, map);
        MapMesh mapMesh = new MapMesh(map);

        foreach (KeyValuePair<TerrainType, MeshData> kv in mapMesh.meshes)
        {
            MeshData meshData = kv.Value;
            TerrainType terrainType = kv.Key;

            GameObject go = new GameObject("Mesh");
            go.transform.SetParent(this.transform);
            go.transform.localPosition = new Vector3(mapMesh.map.origin.x, mapMesh.map.origin.y, -(int)kv.Key);
            MeshFilter meshFilter = go.AddComponent<MeshFilter>();
            meshFilter.mesh = meshData.mesh;

            MeshRenderer mr = go.AddComponent<MeshRenderer>();
            mr.material = Res.mats[terrainType.ToString()];
        }
    }

    // Update is called once per frame
    void Update()
    {
        Vector2Int playerPosition = ConvertPlayerPositionToTiles(ShootBehaviour.PlayerInstance.transform.position);
        AddNeighbours(playerPosition * size);
    }

    private Vector2Int ConvertPlayerPositionToTiles(Vector3 position)
    {
        Vector2Int result = new Vector2Int();
        result.x = (int)position.x / size;
        result.y = (int)position.y / size;

        return result;
    }

```

# Answer
> 2 votes
That's what a single octave of Perlin Noise looks like.

In particular, you've chosen to highlight the ugliest part of this noise function with the thresholds you picked for the sand.

Perlin noise works by taking a grid of square cells, and computing a pseudo-random gradient from each corner, then blending those gradients along the edges/interiors of the cells. That means that Perlin noise *must* touch or cross 0 at every corner of the square grid, giving it a noticeable anisotropy - especially when slicing it along values very close to 0.

Unity's convenience method remaps that 0 value to 0.5, so it sits in the middle of the 0...1 range of the function. And that's exactly where you put your sand cutoff, so it highlights this ugly artifact of the noise algorithm.

You can ameliorate this a little my moving your threshold above or below 0.5 - but it'll still look like a single octave of Perlin Noise (ie. almost never what we actually want).

To get good-looking terrain, we usually sum together multiple octaves of noise at different frequencies and amplitudes. This masks the artifacts of any one layer of noise, and gives us a more complicated pattern with detail across multiple scales, better mimicking what we might see in natural phenomena.

If you need to use just a single octave, split exactly halfway through its range, then you can switch to another noise algorithm that's somewhat more isotropic, like simplex noise.

---
Tags: unity, procedural-generation, perlin-noise
---


# Question
Title: Unity Terrain Tools plants trees sideways
My tree is clearly straight, but painting trees result in sideways ones. What can cause this?

Tree is straight when placed manually as a prefab.

# Answer
> 1 votes
Looks like its a handedness issue, in 3d graphics the choice of which axis is called what is kind of arbitrary (to a point) and there are a couple of different common standards.

Unity uses the left-handed, Y up, but other software, particularly 3d modeling software like blender, use right-handed, Y or Z up.

Freya Holmér made this really great reference image

Realistically the fix is just to transform your model by rotating it, or scaling one dimension by -1, either in unity or in some 3d modeling software, until it looks correct.

---
Tags: unity, terrain, tree
---


# Question
Title: How to avoid destroying information when scaling
I'm in the progress of making a simple 3D editor, just for developing skills on 3d graphics.

After implementing some basic tools, I realize that scaling isn't working as I expected.

For example, when you scale down a model to a flat plane along some axis, how is it possible to restore that model when you scale up again on that axis?

Every vertex has been crunched to the same position, so they will all be scaling in the same way, so the model's vertex layout will be lost.

I assume that I need some metadata or "shadow copy" of the model, but I'm not sure.

How can I solve this problem in my editor?

# Answer
> 1 votes
Separate your notion of the model's source data, and the current display data of an instance of that model.

The source model is like a platonic ideal. Perfect, archetypal, and unchanging.

You do not sully this perfect ideal with every wiggle of a transform handle. You do not write to it at all, unless the user specifically asks you to "apply" or "bake" the transformation down into the source data.

You store the transformation components of an *instance* of the model separately, along with the positions of its transformed vertices. The instance stores a reference back to its source data, and many differently-transformed instances can refer back to the same source data.

When the transformation data changes (position, rotation, scale, or other more exotic transformations if you use them), you *read* the source data, run it through the transformation matrix, and *write* it into the transformed data. No data is lost this way because you do not overwrite the source data.

This also prevents rounding errors from accumulating and distorting your model.

If you want to apply changes the user makes to the transformed vertices back to the source model data, you can run the new vertex positions through the inverse transformation matrix to put them back in the source data's coordinate space. You'll just need a little special handling for the case where the user makes the matrix non-invertable, by flattening the model into a plane for instance - there they can still move the vertex in the two axes parallel to the plane, just not perpendicular to the plane, and you can still map those back to a corresponding position in the source model.

---
Tags: geometry, transformation, scale, editors, 3d-modeling
---


# Question
Title: How can I blend grass LOD's smoothly in unity, similar to the method in BOTW?
This is basically what I mean. I tried to imitate the LOD effect in unity using crossfade LOD but it's not nearly as seamless. I've done some research into the subject but can't seem to find anything about blending foliage in this way so I'm looking for advice. Thanks so much!

# Answer
One often-overlooked visual aspect of stuff like grass or hair (ie. tufts of stuff sprouting out of a surface) is how the normals affect lighting. Specifically, because the default normals stick straight out of the blades of grass, the grass has normals perpendicular to the ground and are lit very differently from the ground. Instead, point the grass normals straight up along with the ground so the grass is lit the same as the ground.

I discussed this same issue on my blog recently in the context of hair on a character I modeled. Meanwhile, this polycount article discusses the same issue/trick for foliage. In particular, check out these screenshots to see how the grass looks before and after aligning normals with the ground.

The actual mechanics of tweaking normals depends on your art tool. For example, here's an explanation of how to do it in Blender. Obviously generating appropriate normals is very straightforward if your grass geometry is created procedurally.
> 3 votes

---
Tags: unity, shaders, level-of-detail
---


# Question
Title: Has the Geometry Shader been abandonded?
Advice says to either limit use or not to use it at all.

---

Friday Facts #251 - A Fistful of Frames | Factorio:

> We tried it, and it worked great. We got some speedup due CPU needing to prepare less data, but when doing research how different APIs work with geometry shaders, we found out that Metal (and therefore MoltenVK) on macOS doesn’t support geometry shaders at all. After more digging, we found an article called Why Geometry Shaders Are Slow. So we tested using the geometry shader on a range of PCs in the office, and found that while it was faster on PCs with new graphics cards, the older machines took a noticeable performance hit. Due to the lack of support on macOS and the possible slowdown on slower machines, we decided to drop the idea.

---

Geometry Shader Debugger · Issue #2110 · baldurk/renderdoc · GitHub:

> Geometry shaders are inefficient especially when expansion is used like that and that's the case that GPU vendors explicitly recommend against.

> I just wanted to let you know that geometry shaders have been virtually abandoned, since with them still being in the API not everyone is aware of that.

---

GPU Programming Guide - GeForce 8 and 9 Series (Chapter 4):

> But in general, the potential for wasted work and performance penalties for using a GS makes it an often unused feature of Shader model 4.

---

OpenGL - geometry shaders

---

Can someone give me a list of geometry shader usages? : gamedev

> Geometry shaders *can* be used for Level-of-Detail subdivision of geometry, and people did expect to be able to use them for that. But AFAIK it turned out that their performance in that scenario is horrible, which is why we now have tesselation shaders for that purpose.

# Answer
**DirectX**
Geometry shaders haven't been abandoned conceptually, but in the D3D12\* pipeline Microsoft is replacing them with mesh shaders:

> The main goal of the Mesh shader is to increase the flexibility and performance of the geometry pipeline. Mesh shaders subsume most aspects of Vertex and Geometry shaders into one shader stage by processing batches of vertices and primitives before the rasterizer. They are additionally capable of amplifying and culling geometry.

**OpenGL**
Geometry shaders haven't been abandoned, at khronos.org geometry shaders are still listed as core in version 4.6\*.

\*The most recent version at the time of posting.

Note: my original answer mistakenly focused on OpenGL - I decided to leave that information incase it proves useful for users searching for geometry shaders without specifying the API.
> 2 votes

---
Tags: directx, directx11, geometry-shader
---


# Question
Title: How can I fill the white color image to fill within that border in a shape of a glass?
I'm using this in 2D canvas. Because I'm doing a health bar and it suppose to fill from the bottom to up but I don't know where to start from here.

# Answer
> 0 votes
There are a few ways on how you can do it. One way I could think of would be along the lines of:

1. First prepare your glass. The outer part of your image should be transparent. The inner part of your glass should be a seperate image.
2. Place them back on your canvas, you should see now just the glass with a white content.
3. You can assign a color for the inner glass.
4. The trick for filling your health (vertically I assume) is via the scale of the inner part. You need to change the anchor and pivot to bottom/ center (shift + lk in the rect transform)

Example code could look like this

```
transform.localScale = new Vector3(1f, currentHitpoints / maxHitpoints, 1f);

```

Every time you have a change in your currentHitpoints, you would update the localScale of your inner glass. If you can have more HP than maxHp (some temporary or other mechanics) you need to clamp the value to 1f else it will overflow.

---
Tags: unity
---


# Question
Title: How can I incorporate subsurface scattering into a custom shader graph?
I'm working on some 3D grass in Unity with HDRP (the grass is not a 2D asset on a plane, it's a mesh).

I did a shader to make it move following a tutorial, it works great. I would like to add Subsurface Scattering (SSS), but I can't find any node or tutorial helping me in that way.

If I could somehow inject the output of this SSS material into my base colour pin, that would solve the problem.

How can I achieve this subsurface scattering look?

# Answer
See unity boat attack demo with urp it has integrated SSS with shader graph using custom function node
> -1 votes

---
Tags: unity, shaders, materials, unity-shader-graph
---


# Question
Title: Health zone heals player but I have a problem
Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this?

Here is the health zone script.

```
{
    public PlayerHealth playerHealth;
    public float healthGain = 2f;

    void OnTriggerStay2D(Collider2D other)
    {
        if (playerHealth.currentHealth < playerHealth.maxHealth)
        {
            playerHealth.currentHealth += (int)healthGain;
            playerHealth.healthBar.SetHealth(playerHealth.currentHealth);
        }

        if (playerHealth.currentHealth >= playerHealth.maxHealth)
        {
            playerHealth.currentHealth = playerHealth.maxHealth;
            playerHealth.healthBar.SetHealth(playerHealth.currentHealth);
        }
    }
}

```

# Answer
I personally like to handle health not as `int` but as `float` internally. Because this would allow me to just write this:

```
currentHealth += healthGain * Time.deltaTime;

```

But that does not work with integers, because unless you are dealing with very high values for healthGain, the multiplication with Time.deltaTime will always round it down to 0. So when you want to still use integers for health, then you have to find a different solution. Don't give health on every single FixedUpdate (collision events happen on FixedUpdate, not on Update, by the way). Only give health at regular intervals. Untested code:

```
public PlayerHealth playerHealth;
public float healthInterval = 1f; // one healing action every 1 second
public int healthGain = 2; // 2 HP per healing action
private float healthIntervalLeft = 0f; // time left until next healing action
private bool doHealing = false; // are we on a tick where a healing action should happen?

void FixedUpdate() {
     healthIntervalLeft -= Time.fixedDeltaTime;
     if (healthIntervalLeft <= 0f) {
         doHealing = true;
         healthIntervalLeft += healthInterval;
     } else {
         doHealing = false;
     }
}

void OnTriggerStay2D(Collider2D other)
{
     if (doHealing) {
          currentHealth += healthGain;
          //...code to clamp the health in the allowed range...
     }
}

```
> 1 votes

# Answer
Right now, you are adding the full amount every frame and not taking the actual elapsed time. You need to multiply the health gain per tick by the elapsed frame time before adding it to the player's health. I'm not familiar with unity but I believe it is something like Time.DeltaTime. A search of the unity docs should bring it up.

Also, because you are converting to an int before adding it, you likely won't see any changes at all because the frame time will make the value very small, thus causing the increment value to be rounded to zero. For this reason, you may want to have your player health be a float and only convert it to an int when needed e.g. for displaying in a menu, determining if player is alive, etc.
> 1 votes

---
Tags: unity
---


title: Assigning script to multiple objects

text:
# Question
Title: Assigning script to multiple objects
So I have multiple gameobjects that needs to be interactable and I've put them all in one gameobject container. But the thing is I still have to attach the script into each of the gameobjects that needs to be interactable for it to work and that seems kinda iffy when a scenario comes that I have to add more gameObjects.

Is it possible to just put the script in the container object? I tried this on my container object and I'm pretty sure I'm doing something wrong.

```
public GameObject spriteHandler;
GameObject sprite1;
GameObject sprite2;
GameObject sprite3;
private void Start()
{
    sprite1 = spriteHandler.transform.GetChild(0).gameObject;
    sprite2 = spriteHandler.transform.GetChild(1).gameObject;
    sprite3 = spriteHandler.transform.GetChild(2).gameObject;
}
void OnMouseDown()
{
    Debug.Log("Clicked");

}

```

# Answer
It depends on your overall goals for what the gameobject is doing. But from what you have said - the preferred method would be to make the Gameobjects prefabs - and attach the interactable script to the prefabs (so as you Instantiate them - each one will have the script attached.).

Here is the documentation on Prefabs & Instantiating Prefabs:

https://docs.unity3d.com/Manual/Prefabs.html https://docs.unity3d.com/Manual/InstantiatingPrefabs.html
> 1 votes

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


# Question
Title: JoyStick::GetInfo(JoyStick::id1).dwButtonNumber always returns 0x1
I am using an XBox 360 gamepad for Windows. I am having an issue with the following legacy code base, which relies on `JOYINFOEX`, `JOYCAPS` and `MMRESULT`:

`ji.dwButtonNumber` returns `0x1` no matter what button is selected (I suspect this is deprecated.) `Update()` is called in the Message Dispatch loop of my application. I am able to get the gamepad count, device driver name, its capabilities, etc. but am unable to get unique values for each button when it is selected, thoughts?

class JoyStick
{
public:

    enum JOYSTICK {id1, id2};
    JOYCAPS&          GetCaps      ( enum JOYSTICK id );
    static JOYINFOEX& GetInfo(enum JOYSTICK id);
    static UINT       GetStickCount( void );

//...

void Scene1::Update()
{
    JOYINFOEX ji;
    WPARAM key;

    ji = JoyStick::GetInfo(JoyStick::id1);
    key = theapp->GetKey();

    switch (ji.dwButtonNumber)
    {
        case GP_A :
        {
            TRACE("Button Number %i pressed\n", ji.dwButtonNumber);   // ji.dwButtonNumber == 0x1
            break;
        }
        case GP_B :
        {
            TRACE("Button Number %i pressed\n", ji.dwButtonNumber);     // ji.dwButtonNumber == 0x1
            break;
        }
        case GP_X :
//...
```
</code></pre>

# Answer
> 1 votes
After a little work I was able to come up with the following C++ framework, which uses the article found here https://docs.microsoft.com/en-us/windows/win32/xinput/getting-started-with-xinput. I found this to work with my XBox gamepad controller. Compiled on Visual Studio 2019

**GamePad.h**

```
#incldude <xinput.h>
class GamePad
{
public:
    GamePad();
    virtual ~GamePad();

    static BOOL is_vibrating;

    enum XIUSER { id0 = 0, id1 = 1, id2 = 2, id3 = 3 };

    typedef struct CONNECTED_CONTROLLERS {
        BOOL id0_connected = FALSE;
        BOOL id1_connected = FALSE;
        BOOL id2_connected = FALSE;
        BOOL id3_connected = FALSE;
    } CONTROLLER_STATE, *PCONTROLLER_STATE;

    typedef struct LAST_VK {
        DWORD id0_vk = VK_PAD_START;
        DWORD id1_vk = VK_PAD_START;
        DWORD id2_vk = VK_PAD_START;
        DWORD id3_vk = VK_PAD_START;
    } LAST_VK, *PLAST_VK;

    static PXINPUT_CAPABILITIES pCapabilities;
    static PXINPUT_KEYSTROKE pKeystroke;
    static PCONTROLLER_STATE pControllerState;
    static PLAST_VK pLast_VK;

    void XIGetState(void);
    void XISetState(enum XIUSER Index);
    void XIGetCaps(void);               // get the gamepad capabilities
    DWORD XIGetVKey(void);              // get the gamepad virtualkey needed by Scene

    static void XISetVibration(enum XIUSER Index);

};

```

**GamePad.cpp**

```
#include "gamepad.h"

PXINPUT_CAPABILITIES GamePad::pCapabilities;
PXINPUT_KEYSTROKE GamePad::pKeystroke;
GamePad::PCONTROLLER_STATE GamePad::pControllerState;
GamePad::PLAST_VK GamePad::pLast_VK;
BOOL GamePad::is_vibrating;

//#define XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE  7849
//#define XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE 8689
//#define XINPUT_GAMEPAD_TRIGGER_THRESHOLD    30

GamePad::GamePad()
{

    TRACE("GamePad::GamePad invoked\n");

    // allocate memory for the data structure
    pCapabilities = new XINPUT_CAPABILITIES;
    pKeystroke = new XINPUT_KEYSTROKE;
    pControllerState = new CONTROLLER_STATE;
    pLast_VK = new LAST_VK;

    pKeystroke->Unicode = 0;
    pKeystroke->Flags = XINPUT_KEYSTROKE_KEYUP;
    pKeystroke->UserIndex = XUSER_INDEX_ANY;
    pKeystroke->HidCode = 0;
    pKeystroke->VirtualKey = VK_PAD_START;

    GamePad::is_vibrating = FALSE;

    XIGetState();

    if (GamePad::pCapabilities != NULL)
    {
        for (DWORD i = 0; i < XUSER_MAX_COUNT; i++)
        {
            DWORD dwResult = XInputGetCapabilities(i, XINPUT_FLAG_GAMEPAD, GamePad::pCapabilities);
            if (dwResult == ERROR_SUCCESS)
            {
                TRACE("XInputGetCapabilities returned Controller IS connected, on %ld\n", i);
                switch (i)
                {
                case 0:
                    pControllerState->id0_connected = TRUE; // id0 was initialized with FALSE, here we see that there is a controller present on id0
                    break;
                case 1:
                    pControllerState->id1_connected = TRUE; // id1 was initialized with FALSE, here we see that there is a controller present on id1
                    break;
                case 2:
                    pControllerState->id2_connected = TRUE; // id2 was initialized with FALSE, here we see that there is a controller present on id2
                    break;
                case 3:
                    pControllerState->id3_connected = TRUE; // id3 was initialized with FALSE, here we see that there is a controller present on id3
                    break;
                }

                // Controller is connected
            }
            else
            {
                TRACE("XInputGetCapabilities returned Controller is NOT connected on %ld\n", i);

                switch (i)
                {
                case 0:
                    pControllerState->id0_connected = FALSE; // id0 was initialized with FALSE, here we see that there is no controller present on id0
                    break;
                case 1:
                    pControllerState->id1_connected = FALSE; // id1 was initialized with FALSE, here we see that there is no controller present on id1
                    break;
                case 2:
                    pControllerState->id2_connected = FALSE; // id2 was initialized with FALSE, here we see that there is no controller present on id2
                    break;
                case 3:
                    pControllerState->id3_connected = FALSE; // id3 was initialized with FALSE, here we see that there is no controller present on id3
                    break;
                }
                // Controller is not connected
            }

        }
    }

}

GamePad::~GamePad()
{
    TRACE("GamePad::~GamePad invoked\n");

    delete(pCapabilities);
    delete(pKeystroke);
    delete(pControllerState);
    delete(pLast_VK);

}

void GamePad::XIGetState(void)
{

    TRACE("GamePad::XIGetState invoked\n");

    DWORD dwResult;
    for (DWORD i = 0; i < XUSER_MAX_COUNT; i++)
    {
        XINPUT_STATE state;
        ZeroMemory(&state, sizeof(XINPUT_STATE));

        // Simply get the state of the controller from XInput.
        dwResult = XInputGetState(i, &state);
        if (dwResult == ERROR_SUCCESS)
        {
            TRACE("XInputGetState returned Controller IS connected, on %ld\n", i);
            switch (i)
            {
            case 0:
                pControllerState->id0_connected = TRUE; // id0 was initialized with FALSE, here we see that there is a controller present on id0
                break;
            case 1:
                pControllerState->id1_connected = TRUE; // id1 was initialized with FALSE, here we see that there is a controller present on id1
                break;
            case 2:
                pControllerState->id2_connected = TRUE; // id2 was initialized with FALSE, here we see that there is a controller present on id2
                break;
            case 3:
                pControllerState->id3_connected = TRUE; // id3 was initialized with FALSE, here we see that there is a controller present on id3
                break;
            }

            // Controller is connected
        }
        else
        {
            TRACE("XInputGetState returned Controller is NOT connected on %ld\n", i);

            switch (i)
            {
            case 0:
                pControllerState->id0_connected = FALSE; // id0 was initialized with FALSE, here we see that there is no controller present on id0
                break;
            case 1:
                pControllerState->id1_connected = FALSE; // id1 was initialized with FALSE, here we see that there is no controller present on id1
                break;
            case 2:
                pControllerState->id2_connected = FALSE; // id2 was initialized with FALSE, here we see that there is no controller present on id2
                break;
            case 3:
                pControllerState->id3_connected = FALSE; // id3 was initialized with FALSE, here we see that there is no controller present on id3
                break;
            }
            // Controller is not connected
        }

    }

}

//
// currently only support for controller 0 or Index == id0
// Vibration starts easily but does not shut down so easily
void GamePad::XISetVibration(enum XIUSER Index)
{
    TRACE("GamePad::XISetVibration invoked\n");

    if (pControllerState->id0_connected == TRUE)
    {
        DWORD dwResult;

        XINPUT_VIBRATION vibration;
        vibration.wLeftMotorSpeed = 0; // use any value between 0-65535 here
        vibration.wRightMotorSpeed = 0; // use any value between 0-65535 here

        if (!GamePad::is_vibrating)                 // turn off the vibration
        {
            ZeroMemory(&vibration, sizeof(XINPUT_VIBRATION));
            vibration.wLeftMotorSpeed = 32000; // use any value between 0-65535 here
            vibration.wRightMotorSpeed = 16000; // use any value between 0-65535 here
            dwResult = XInputSetState(Index, &vibration);
            if (dwResult == ERROR_SUCCESS)
            {
                GamePad::is_vibrating = TRUE;
                // Controller is connected
            }
            else
            {
                // Controller is not connected
            }

        }
        else {                                                                      // turn on the vibration

            ZeroMemory(&vibration, sizeof(XINPUT_VIBRATION));
            vibration.wLeftMotorSpeed = 0; // use any value between 0-65535 here
            vibration.wRightMotorSpeed = 0; // use any value between 0-65535 here
            dwResult = XInputSetState(Index, &vibration);
            if (dwResult == ERROR_SUCCESS)
            {
                GamePad::is_vibrating = FALSE;
                // Controller is connected
            }
            else
            {
                // Controller is not connected
            }
        }

    }
}

void GamePad::XISetState(enum XIUSER Index)
{
    TRACE("GamePad::XISetState invoked\n");

    PXINPUT_VIBRATION pVibration;
    DWORD dwResult;

    pVibration = new XINPUT_VIBRATION;
    pVibration->wRightMotorSpeed = 32000;
    pVibration->wLeftMotorSpeed = 16000;

    dwResult = XInputSetState(Index, pVibration);
    if (dwResult == ERROR_SUCCESS)
    {
        // Controller is connected
    }
    else
    {
        // Controller is not connected
    }

}

void GamePad::XIGetCaps(void)
{
    TRACE("GamePad::XIGetCaps invoked\n");

    DWORD dwResult;
    for (DWORD i = 0; i < XUSER_MAX_COUNT; i++)
    {

        if (GamePad::pCapabilities != NULL)
        {
            dwResult = XInputGetCapabilities(i, XINPUT_FLAG_GAMEPAD, GamePad::pCapabilities);
            if (dwResult == ERROR_SUCCESS)
            {
                TRACE("XInputGetCapabilities returned Controller IS connected, on %ld\n", i);
                switch (i)
                {
                case 0:
                    pControllerState->id0_connected = TRUE; // id0 was initialized with FALSE, here we see that there is a controller present on id0
                    break;
                case 1:
                    pControllerState->id1_connected = TRUE; // id1 was initialized with FALSE, here we see that there is a controller present on id1
                    break;
                case 2:
                    pControllerState->id2_connected = TRUE; // id2 was initialized with FALSE, here we see that there is a controller present on id2
                    break;
                case 3:
                    pControllerState->id3_connected = TRUE; // id3 was initialized with FALSE, here we see that there is a controller present on id3
                    break;
                }

                // Controller is connected
            }
            else
            {
                TRACE("XInputGetCapabilities returned Controller is NOT connected on %ld\n", i);

                switch (i)
                {
                case 0:
                    pControllerState->id0_connected = FALSE; // id0 was initialized with FALSE, here we see that there is no controller present on id0
                    break;
                case 1:
                    pControllerState->id1_connected = FALSE; // id1 was initialized with FALSE, here we see that there is no controller present on id1
                    break;
                case 2:
                    pControllerState->id2_connected = FALSE; // id2 was initialized with FALSE, here we see that there is no controller present on id2
                    break;
                case 3:
                    pControllerState->id3_connected = FALSE; // id3 was initialized with FALSE, here we see that there is no controller present on id3
                    break;
                }
                // Controller is not connected
            }

        }
    }
}

DWORD GamePad::XIGetVKey(void)
{

    DWORD dwResult;
    for (DWORD i = 0; i < XUSER_MAX_COUNT; i++)
    {

        dwResult = XInputGetKeystroke(i, 0, GamePad::pKeystroke);
        if (dwResult == ERROR_SUCCESS)
        {
            TRACE("XInputGetKeyStroke returned Controller IS connected, on %ld\n", i);
            switch (i)
            {
            case 0:
                pControllerState->id0_connected = TRUE; // id0 was initialized with FALSE, here we see that there is a controller present on id0
                pLast_VK->id0_vk = GamePad::pKeystroke->VirtualKey;
                return pLast_VK->id0_vk;
                break;
            case 1:
                pControllerState->id1_connected = TRUE; // id1 was initialized with FALSE, here we see that there is a controller present on id1
                pLast_VK->id1_vk = GamePad::pKeystroke->VirtualKey;
                return pLast_VK->id1_vk;
                break;
            case 2:
                pControllerState->id2_connected = TRUE; // id2 was initialized with FALSE, here we see that there is a controller present on id2
                pLast_VK->id2_vk = GamePad::pKeystroke->VirtualKey;
                return pLast_VK->id2_vk;
                break;
            case 3:
                pControllerState->id3_connected = TRUE; // id3 was initialized with FALSE, here we see that there is a controller present on id3
                pLast_VK->id3_vk = GamePad::pKeystroke->VirtualKey;
                return pLast_VK->id3_vk;
                break;
            }

            // Controller is connected
        }
        else
        {
            TRACE("XInputGetKeyStroke returned Controller is NOT connected on %ld\n", i);

            switch (i)
            {
            case 0:
                pControllerState->id0_connected = FALSE; // id0 was initialized with FALSE, here we see that there is no controller present on id0
                return pLast_VK->id0_vk;
                break;
            case 1:
                pControllerState->id1_connected = FALSE; // id1 was initialized with FALSE, here we see that there is no controller present on id1
                return pLast_VK->id1_vk;
                break;
            case 2:
                pControllerState->id2_connected = FALSE; // id2 was initialized with FALSE, here we see that there is no controller present on id2
                return pLast_VK->id2_vk;
                break;
            case 3:
                pControllerState->id3_connected = FALSE; // id3 was initialized with FALSE, here we see that there is no controller present on id3
                return pLast_VK->id3_vk;
                break;
            }
            // Controller is not connected

        }

    }

    return -1; // no other control path was satisfied. Could be here if all controllers were unplugged
}

```

---
Tags: c++, input, joystick, gamepad
---


# Question
Title: How do you register two or more keys properly?
I am experimenting with `KeyListeners` and I thought about how do I register two or more keys, this is my code so far:

```
package engine.listeners;

import engine.Frame;
import engine.KeyCodes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import javax.swing.*;

public class Key extends KeyAdapter implements KeyCodes, ActionListener {

    private static HashSet<Integer> keyMap = new HashSet<>();
    private Timer tm;

    public Key() {
        tm = new Timer(0, this);
        tm.start();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (!keyMap.contains(e.getKeyCode())) keyMap.add(e.getKeyCode());
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keyMap.remove(e.getKeyCode());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int x = Frame.moveMe.getX();
        int y = Frame.moveMe.getY();
        if (keyMap.contains(arrowLeft)) Frame.moveMe.setXY(--x, y);
        if (keyMap.contains(arrowUp)) Frame.moveMe.setXY(x, --y);
        if (keyMap.contains(arrowRight)) Frame.moveMe.setXY(++x, y);
        if (keyMap.contains(arrowDown)) Frame.moveMe.setXY(x, ++y);
    }
}

```

Right here, it's doing 2 registered keys properly, for example `arrow left` and `arrow top` goes diagonal left top.
But one thing I noticed, sometimes when I registered 3 or more keys, it's not working properly for example: `arrow left`, `arrow right`, and `arrow up` should just go up, but what happened is it ignored the key 'right', and so it continues going diagonal top left.

Is there a way to improve this? or should I implement another type of listener that is not buggy as `KeyListener`?

# Answer
> 0 votes
There is a small issue with the logic in the `actionPefromed` function: you use "stale" data. You currently have this:

```
public void actionPerformed(ActionEvent e) {
    int x = Frame.moveMe.getX();
    int y = Frame.moveMe.getY();
    if (keyMap.contains(arrowLeft)) Frame.moveMe.setXY(--x, y);
    if (keyMap.contains(arrowUp)) Frame.moveMe.setXY(x, --y);
    if (keyMap.contains(arrowRight)) Frame.moveMe.setXY(++x, y);
    if (keyMap.contains(arrowDown)) Frame.moveMe.setXY(x, ++y);
}

```

What you need is this:

```
public void actionPerformed(ActionEvent e) {
    int x = Frame.moveMe.getX();
    int y = Frame.moveMe.getY();
    if (keyMap.contains(arrowLeft)) --x;
    if (keyMap.contains(arrowUp)) --y;
    if (keyMap.contains(arrowRight)) ++x;
    if (keyMap.contains(arrowDown)) ++y;

    Frame.moveMe.setXY(x,y);
}

```

Essentially, you update the temporary values, then when you're done, you update the position with the updated temporary values.

---
Tags: java, game-mechanics, keyboard
---


# Question
Title: Should I get an official content rating, like from the ESRB, or just rate my game myself?
I'm developing a game out of my garage basically with the intention of selling it on my own website and hopefully on Steam, and I've been wondering if I should try to get it rated by an official ratings agency, like the ESRB, or just display my own content rating? As I see it, rating the contents of your game has three purposes.

1. Let the player know the type of any potentially objectionable content they are about to experience.
2. Access certain marketplaces that require a content rating.
3. Fulfill legal requirements in certain countries that do not allow minors to be exposed to certain content.

Purpose #1 is the most important, and you certainly don't need any official ratings body to do that. Purpose #2 doesn't seem to be necessary for Steam. As for #3, I'm in the United States but I don't know how exactly any such laws would apply.

I looked into getting an official ESRB rating for a digital-download-only game, and it seems to be a hassle. It used to be that you could send them a letter in the mail with your company information, then they would create an account for you to log in to their website where you could fill out a questionnaire to have your game rated for free. They discontinued that in 2018 I think. Now they say you still can get a free rating through the IARC through participating storefronts, like the Windows Store, but it seems all of them require you to pay for a developers account before you can access the rating form.

So if I just make my own content rating, I don't want to create a new system that nobody is familiar with. Would I still be able to use "M for Mature" without the ESRB's blessing? Do they have a copyright on that phrase? I was thinking of using a similar color scheme (black with white text) to make it look similar to an official ESRB rating and using the content descriptors they use, but without mentioning the ESRB. Does that seem like a good idea?

# Answer
> 3 votes
If I were you, I wouldn't bother with ratings at all unless your video game is something only appropriate for adults. Virtually nobody cares about age ratings in the PC gaming community. Also, ESRB doesn't require you to get an official age rating unless you're releasing to console.

# Answer
> 1 votes
Digital storefronts require you to add an age rating. If you're not going to publish on Steam, Nintendo eSHop, Nvidia, Play Store, etc, you will not fill out the IARC questionnaire. It's not recommended to self-rate your game as others have some have other concepts of what would be a specific rating.
TL;DR: Only rate your game for online shops or hard copies. Do not self rate.

---
Tags: legal, content-rating, esrb
---


# Question
Title: ScriptableObject's custom objects begin reset to default?
I'm using `ScriptableObject`s as a way to serialize objects that I work with in an editor script. I save them as assets using `AssetDatabase.CreateAsset` and get them resetted It is saving correctly native c# class objects like strings, primitives and arrays of primitives.

The problem is that my `ScriptableObject` also contains objects of custom classes and structs of my code. These custom objects are being set to `default()` (ie. value types being set to `0` and reference types to `null`) every time the code is recompiled and when the editor is restarted (while the primitive variables still have the right saved value). Even with blittable structs the problem persists.

Is that expected?

**Edit with some code to contextualize**:

```
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MeshHeader
{
    public int numBones;
    public int numVerts;
}

public class MyClass
{
    public string s1 { get; set; }
    public string s2 { get; set; }
}

public class MySO : ScriptableObject
{
    public int myInt; // OK
    public int[] myArr; // OK

    // These 2 variables will have their value reset after any recompilation of the code
    public MeshHeader meshHeader; // This will become 0;0
    public MyClass myClass; // This will become null

    public static void SaveMySO(MeshHeader h, MyClass c)
    {
        var mySO = ScriptableObject.CreateInstance<MySO>();
        mySO.myInt = 10;
        mySO.myArr = new int[2] { 9, 8 };
        mySO.meshHeader = h;
        mySO.myClass = c;

        AssetDatabase.CreateAsset(mySO, "Assets/foo.asset");
    }

    public static MySO LoadMySO()
    {
        return AssetDatabase.LoadAssetAtPath<MySO>("Assets/foo.asset");
    }
}

```

When I call `MySO.SaveMySO` it will save the `ScriptableObject`. However if I run `MySO.LoadMySO` after any code recompilation between these two calls, it will have both `meshHeader` and `myClass` values set to default, which will be `0` and `null` respectively while still holding the right values for `myInt` and `myArr`.

# Answer
> 1 votes
Two mistakes in your code sample:

1. You're missing `[System.Serializable]` attributes above your custom types. This flags the type to be serialized so that its data can be saved to disc or preserved and restored after an assembly reload.
2. You're using C# auto-properties, which are not supported by Unity's serializer. Add a serialized backing field for them.

Here's an example with these fixes applied:

```
[System.Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MeshHeader
{
    public int numBones;
    public int numVerts;
}

[System.Serializable]
public class MyClass
{
    [SerializeField]
    string _s1;
    public string s1 { get {return _s1;} set {_s1 = value;} }

    [SerializeField]
    string _s2;
    public string s2 { get {return _s2;} set {_s2 = value;} }
}

```

---
Tags: unity, scriptable-object
---


# Question
Title: Need help with rotating sword around player (Unity 2D)
I'm having an issue with rotating an object around another object in my top-down roguelike in Unity 2D. My goal is to rotate a sword around a player based on joystick input from a controller (as shown in this image).

I have looked around online for any answers, but nothing has helped. All I have so far that is remotely close to what I want is code that keeps the sword attached to the box even when the box moves.

```
void Update()
{
    transform.localPosition = new Vector3(0, 1.5f, 0);
}

```

It might be necessary to note that the sword object is a child of the box object. I would appreciate it if anyone could point me in the right direction. Thanks!

# Answer
Here's a very simple example:

```
public class SwordPointer : MonoBehaviour {

    [SerializeField] private float distance = 1;
    [SerializeField] private Transform sword;

    private void Update() {
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        //convert the input into an angle in radians, and convert that into degrees
        float rads = Mathf.Atan2(y, x);
        float degrees = rads * Mathf.Rad2Deg;

        //use trig to position sword
        sword.localPosition = new Vector3(Mathf.Cos(rads) * distance, 0, Mathf.Sin(rads) * distance);
        //rotate to face away from center. note that the angle atan gives us is
        //oriented differently than unity's rotation, so we have to reverse it
        //and add 90.
        sword.localEulerAngles = new Vector3(0, -degrees + 90, 0);
    }
}

```

This uses simple trig to position the sword according to the player input. We convert the input into an angle and apply that angle to the sword's *local* position and rotation. You would make the sword a child of the hero.

This is using the default horizontal and vertical axes to aim the sword, but you are probably actually using those axes for movement, in which case you'll need separate axes for the sword.

This example code positions the sword relative to its parent; this means that if the hero turns, the sword orientation will change. E.g. if the hero is facing to the right, pressing up on the sword controls will actually point the sword to the right. If the hero can turn, you'll probably need to make some tweaks so that the sword orientation remains relative to the screen instead of the hero.
> 1 votes

# Answer
I had to tweak a few things from @Kevin 's contribution to change rotation axes, but this is what I ended up with! Many thanks to @Kevin for providing 99% of the framework I needed!

```
[SerializeField] private float distance = 1;
[SerializeField] private Transform sword;

public void Update()
{
    float x = Input.GetAxis("ControllerAimX");
    float y = -Input.GetAxis("ControllerAimY");

    //convert the input into an angle in radians, and convert that into degrees
    float rads = Mathf.Atan2(y, x);
    float degrees = rads * Mathf.Rad2Deg;

    //use trig to position sword
    sword.localPosition = new Vector3(Mathf.Cos(rads) * distance, Mathf.Sin(rads) * distance, 0);
    //rotate to face away from center. note that the angle atan gives us is
    //oriented differently than unity's rotation, so we have to reverse it
    //and add 90.
    sword.localEulerAngles = new Vector3(0, 0, degrees - 90); }

```
> 0 votes

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


# Question
Title: How can I fix problems caused by "ForceMode2D.Force"?
I'm making a 2D platformer with Unity. I used `transform.position` for movement but it caused some problems like vibration, so I decided to use `AddForce.ForceMode2D.Force` instead. Since this uses mass for moving the player, it makes the player either so heavy and hard to control (even when the mass is 1) or so quick and fast. I tried changing the mass and speed but I haven't found the setting that makes a smooth movement. Also, the jumping has a problem. The player will be suspended in the air for a few seconds after the jumping. I'm just looking for a way to make `AddForce`smoother and solve these problems.

Here's my code:

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

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float jumpSpeed;

    public float maxSpeed = 5f;
    public float maxAcceleration = 50f;
    public float maxDeceleration = 100f;

    [SerializeField] private LayerMask ground;
    private PlayerActionControls playerActionControls;
    private Rigidbody2D rb;
    private PolygonCollider2D pol;
    private Animator animator;
    private Vector2 movementInput;

    private void Awake()
    {
        playerActionControls = new PlayerActionControls();
        rb = GetComponent<Rigidbody2D>();
        pol = GetComponent<PolygonCollider2D>();
        animator = GetComponent<Animator>();
    }

    private void OnEnable()
    {

        playerActionControls.Enable();

    }

    private void OnDisable()
    {

        playerActionControls.Disable();
    }

    void Start()
    {
        playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue<float>());

    }

    private void Jump(float val)
    {
        if (val == 1 && IsGrounded())
        {
            rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);

        }
    }
    private bool IsGrounded()
    {

        Vector2 topLeftPoint = transform.position;
        topLeftPoint.x -= pol.bounds.extents.x;
        topLeftPoint.y += pol.bounds.extents.y;

        Vector2 bottomRightPoint = transform.position;
        bottomRightPoint.x += pol.bounds.extents.x;
        bottomRightPoint.y -= pol.bounds.extents.y;

        return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
    }
    void FixedUpdate()
    {

     Vector2 movementInput = playerActionControls.Land.Move.ReadValue<Vector2>();

     movementInput = Vector2.ClampMagnitude(movementInput, 1f);
     Vector2 desiredVelocity = movementInput * maxSpeed;
     AccelerateTo(desiredVelocity);

    var scale = transform.localScale;
    if(scale.x * rb.velocity.x < 0) {
        scale.x *= -1;
        transform.localScale = scale;
    }

    void AccelerateTo(Vector2 DesiredVelocity) {

    var deltaV = desiredVelocity - rb.velocity;
    var acceleration = deltaV / Time.deltaTime;

    float limit = maxAcceleration;
    if (Vector3.Dot(rb.velocity, desiredVelocity) <= 0f)
        limit = maxDeceleration;
    acceleration = Vector2.ClampMagnitude(acceleration, limit);

    Vector2 force = rb.mass * acceleration;
    rb.AddForce(force);
   }
 }
}

```

# Answer
It doesn't sound like these problems are caused by `ForceMode2D.Force` at all. It sounds like they're caused by how you're choosing to use it.

You're treating the player character like they're a spaceship, firing a thruster with a certain force vector and accelerating endlessly in that direction. That's not really how a biped moves. But treat a biped like a spaceship, and they'll handle like a spaceship (ie. floaty - not feeling like a tight, snappy, platformer character)

Unlike a spaceship, a platformer character usually has a fixed max speed. They'll accelerate up to that max speed quite quickly, and decelerate from their max speed to a stop even faster when the player lets go of the stick or tries to turn around.

Here's a way you can get this kind of behaviour:

```
public float maxSpeed = 5f;

// Tune this quite high, until the character feels nicely responsive.
public float maxAcceleration = 50f;

// Tune this even higher, so the character stops quickly when you let go.
public float maxDeceleration = 100f;

// Handle continuous motions in FixedUpdate, not Update.
void FixedUpdate()
{
    Vector2 movementInput = playerActionControls.Land.Move.ReadValue<Vector2>();

    // Ensure our movement input never exceeds a radius of 1.
    movementInput = Vector2.ClampMagnitude(movementInput, 1f);

    // Accelerate up to, but not past, our max speed.
    Vector2 desiredVelocity = movementInput * maxSpeed;
    AccelerateTo(desiredVelocity);

    // Handle flipping. (Doesn't need to be a separate function call)
    var scale = transform.localScale;
    if(scale.x * rb.velocity.x < 0) {
        scale.x *= -1;
        transform.localScale = scale;
    }
}

void AccelerateTo(Vector2 desiredVelocity) {
    // Compute the acceleration we'd need to reach our desired velocity in this time step.
    var deltaV = desiredVelocity - rb.velocity;
    var acceleration = deltaV / Time.deltaTime;

    // Enforce our maximum acceleration limits when speeding up or slowing down.
    float limit = maxAcceleration;
    if (Vector3.Dot(rb.velocity, desiredVelocity) <= 0f)
        limit = maxDeceleration;
    acceleration = Vector2.ClampMagnitude(acceleration, limit);

    // Compute and apply a force that gets us this acceleration.
    Vector2 force = rb.mass * acceleration;
    rb.AddForce(force);
}

```

Note that your current code applies the player's movement exactly the same on the ground as in the air, and allows analog stick input to push the character vertically. I'm assuming that's what you want, so I've preserved that in the code I've shown here.

However, a more typical platformer behaviour would be to check if you're on the ground, and if so, apply your analog stick acceleration only perpendicular to the ground normal. Or if not, apply your acceleration only along the x axis, with reduced acceleration limits (depending on how much air steering you want to allow).
> 0 votes

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


# Question
Title: How best to detect device performance capabilities and set quality setting accordingly when using Unity
I am developing a Mobile game for Android and iOS on Unity.

Currently Im in the optimisation stage of development and trying to work out what is the best way to detect device capabilities, with the aim of then setting an appropriate quality setting.

OS/platform detection is simple, but how can I detect between a high performance android device and a low or medium performance device at runtime?

I did find this question that is similar https://stackoverflow.com/q/21565468/4148676 but the question is old, the answers not great and hoping there's a better way in the last 4 years of solving the problem.

The only other solution I have is monitor the average FPS and adjust the quality based on the frame rate.

Any advice would be appreciated.

# Answer
I cannot give "the best practice" because it really depends on your situation. But I can give two real world examples from games I worked on.

In Love & Hip Hop, we checked the RAM of the device. At the time, 2GB devices could definitely render a lot more than 1GB devices. So we tried to target the lowest 2GB devices with high-resolution assets, and others with low-resolution assets.

Dead by Daylight has a resolution changer that drops resolution if the framerate is crap for too many frames. Then it bumps it back up later if it's smooth for long enough. Though this game is made with Unreal 4, there's no reason Unity couldn't use this tactic. DbD also has user-selected quality settings for graphics since PC hardware is so varied.
> 1 votes

# Answer
This is 2 years old, but still quite relevant and as the answers are somewhat lacking (in my opinion), I'll share my experience and solution to the question for anyone who might be or still be looking for some tips and answers.

The first thing about mobile (Android especially) is that there's no flat ground nor standards, regardless of what anyone tells you. iOS makes things a bit easier because there's only 1 source (Apple) and they usually follow their own set of rules, but even iOS gets modified now and then in a way that break things.

As such, it's always best to not get too deep into the search for the perfect solution as any solution will become usually obsolete at some point in time, be it from an update to Unity (the engine) or the newest generation of Android or iOS released and applied/used by the manufacturers.

Still, it's normal to wish for a good approach and one of such would be to use 2 methods that works hands in hands and to which Unity has full support (or at least offer good access to).

The first method is to use some hard coded system stats.

SystemInfo.systemMemorySize

This is a good way to get an "idea" of the average memory available for the app. The one thing to remember is that, on mobile, this will NOT return the full value of the available memory of the device, but will return what memory the OS allows the App to use when it's being used in Foreground. For example, if a mobile device has 1.5GB of RAM and the version of Android uses 1GB of RAM to run in average, systemMemorySize will return around 500-512MB. Due to that, it's not a "work-best-and-always" trick, but it does help you know how much memory the user's device might have in general. (For example, even if a mobile device with 4GB of RAM, if the user is leaving the Facebook App, a web browser with a few tabs, chat via Skype and play the game at the same time, the game might be able to get access to only 0.5GB-1GB memory. Some app used by many people every day are real memory hungry and there's nothing you can do about.)

Keeping track of the FPS within the game can also be a good gauge. By using a coroutine, you can check the FPS every now and then. There's no need to check it every frame though. The trick is to check the average within an acceptable amount of time and drop a few things if the FPS average gets under a certain threshold. But this is assuming that you have already profiled your game so that it remains constant and fixed in its FPS at all time. If you know some part of your game might have some heavy impact on the FPS and wishes to be safe during those moments from having fake drop in the FPS, you can always set the threshold on the fly as needed.

Another thing that can be useful is this function:

Application.lowMemory

While the example in the link is useful, one good example of use of the lowMemory function is to do a memory sweep and load a "safe scene" which allow the memory usage of the App to drop. An important point to remember is that, whenever lowMemory is being called, it's not that the FPS is just low, but it's that the OS struggle to maintain the App integrity and might close it soon if nothing is done.

A last thing would be to consider checking the version of Android or iOS that is being used. There's a few way of looking it up (like this ). Knowing the version won't give you a clear answer, but the API version (OS version) gives an idea of what kind of compatible or incompatible thing comes around from the OS itself. You might be able or forced to turn off some features or graphics effects if the device runs on an API below 23, for example, like AR/VR or physics-based particles. If a device API is 20 or below, you should consider, by default, that it's a low-end device (in today's and Unity's mobile standards) 23 is low-average with compatibility with enough memory. 24 to 27 is low-medium-high and are the most used in the World right now. 28 or more are high and should, generally speaking, run well unless systemMemorySize returns a low value.

Remember that "high" models, in what I wrote above, are NOT the best available, but more like the best available in a big part of the World. When it comes to testing your App with multiple devices, it's best to do the simple, yet most common thing: Go to a popular store around your area and speak with the store clerk. Explains your position and ask him what's the worse phone (or tablet) he has in his opinion, which one is the most popular outside of the newest models and, if your budget allows you to, which one is the most popular (which is usually one expensive). You might know more about mobile device than him or her, but he's the one who actually sell the devices and you might be surprised about what models will comes to your hands. If you explain your position as a mobile game app developer, not only the store clerk might be interested in your own story (and game), but he or she might be more willing to help you with honesty. (And he or she knows you might return for another testing device in the future.) Obviously, some store clerk might attempt to mislead you in one of the devices, but remember that if he tries to mislead you, he'll mislead others and that's a common thing which makes it so that your "average every-day's Joe" will usually buy that thing because the store clerk sells it to him (or her).

Also, last tip, don't purchase device below your minimal standard just for the sake of, maybe, be able to downgrade your project below your expectations. If you set your goal for the App to run on devices with at least 1GB of RAM, don't buy devices with 512MB of RAM. Remember that both the Google Play store and iOS iTunes store (for games/app) allow you to set a "minimum" level of compatibility which will make your App visible not compatible and downloadable with device below your target. Don't fall into the rabbit hole of over-optimization for the sake of reaching a lower device as this will often result in breaking something in the app for higher/better devices.
> 1 votes

# Answer
The first step is to determine the list of devices you'd like to target/support. To construct this list, simply go to each major phone manufacturer and go backwards from their most recent models until you find a device that you no longer want to support. The simpler or more light-weight your game is to run, the farther back in the model history you can go.

Once you think you have your list of supported devices, compare the specs of the lowest ranking ones. The ideas is for the minimum specs to be similar. You may support the 7 most recent iPhone models but only the 4 most recent Samsungs for example.

Then make your game work for the least powerful supported device. In initialization there's a whole list of device properties you can check to see what the particular active device can support. Since you know the specs of the lowest tier devices that you will support, you have your checks verify these minimums and adjust accordingly.

While device hardware is *technically* what limits framerate, using the raw framerate to estimate device specs can be deceiving because there other factors that can bottleneck performance such as unoptimized code or heavy art assets. When in doubt, add graphics options to your game so the user can lower quality when they know their device is not up to par.
> 0 votes

---
Tags: unity, android, ios, performance
---


# Question
Title: Unity: How to get the visible bounds of an object, i.e. as it is seen from the camera?
Imagine you'd like to highlight a 3D GameObject by drawing a (translucent) UI panel above it. The UI panel should cover the object exactly. Therefore the object's bounds, as it is seen from the camera, are needed. How do you get these bounds? (In word space, or screen, viewport or canvas space, any way's fine).

My problem is that \[Collider|Renderer|Mesh\].bounds does not take the camera's position into account. Hence, depending on the camera's location and the object's dimensions, the bounds are more or less off. Do you know how this can be fixed?

Any advise is very much appreciated. Thank you!

# Answer
> 2 votes
As DMGregory pointed out, the solution is quite simple: Just iterate through the vertices of a mesh, convert them from world to screen coordinates and store the min and max values of both x and y axis. In code it looks like this:

```
private List<Vector3> vertices = new List<Vector3>();

public Rect GetBoundingBoxOnScreen(Mesh mesh, Camera camera) {
    mesh.GetVertices(vertices);
    Rect retVal = Rect.MinMaxRect(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue);

    for (int i = 0; i < vertices.Count; i++) {
        Vector3 v = camera.WorldToScreenPoint(vertices[i]);
        if (v.x < retVal.xMin) {
            retVal.xMin = v.x;
        }

        if (v.y < retVal.yMin) {
            retVal.yMin = v.y;
        }

        if (v.x > retVal.xMax) {
            retVal.xMax = v.x;
        }

        if (v.y > retVal.yMax) {
            retVal.yMax = v.y;
        }
    }

    return retVal;
}

```

The min and max corners of the returned rectangle are them passed to `RectTransformUtility.ScreenPointToLocalPointInRectangle()` to convert them from screen to canvas coordinates. And that's it. @DMGregory, again, thank you for your advice.

---
Tags: unity, unity-ui
---


title: Animating from json file in pygame?

text:
# Question
Title: Animating from json file in pygame?
I have got a json file and I am trying to load the single sprites from that file but I gives this error after a few loops and also the animation is not smooth(gets stuck) error:

```
Traceback (most recent call last):
  File "test.py", line 18, in <module>
    screen.blit(image, (0, 50))
TypeError: argument 1 must be pygame.Surface, not None

```

This is the json file I am using:

```
{
  "textureAtlas": {
    "texture": "Run (32x32).png",
    "regionWidth": 32,
    "regionHeight": 32
  },
  "cycles": {
    "animation0": {
      "frames": [0,1,2,3,4,5,6,7,8,9,10,11]
    }
  }
}

```

The script for the animation:

```
import json

pygame.init()

clock=pygame.time.Clock()
c=0
def lcAnim(sfile):
    global c
    with open(sfile) as f:
        data=json.load(f)
        img=pygame.image.load(data['textureAtlas']['texture'])

        while c<len(data['cycles']['animation0']['frames']):
            img.set_clip(pygame.Rect(data['cycles']['animation0']['frames'][c-1]*32,0,32,32))  # Locate the sprite you want
            draw_me = img.subsurface(img.get_clip())  # Extract the sprite you want
            c =c+1
            print(c)
            return draw_me
    c=0

```

and the main script:

```
import pygame
import lcanim #name of the animation script
(width,height)=(300,200)
clock=pygame.time.Clock()
screen=pygame.display.set_mode((width,height))
pygame.display.flip()
running=True

while running:

    image = lcanim.lcAnim('run.sf') #name of json file
    for event in pygame.event.get():
        if event.type==pygame.QUIT:

            running=False

        screen.blit(image, (0, 50))
        #screen.blit(alimg,(-10,10))
        pygame.display.update()
        screen.fill((255,255,255))
    clock.tick(10)
pygame.quit()

```

Here's a video showing the problem:

https://youtu.be/8IeaqVCxvms (sorry other video sharing services were not working)

# Answer
> 0 votes
I found out the problem:

The functions in python return `None` by default, so when the while loop turned `False` it returned `None` thus throwing an error.

```
import pygame
import json
pygame.init()

c=0
def lcAnim(sfile):
    global c
    with open(sfile) as f:
        data=json.load(f)

    width=data['textureAtlas']['regionWidth']
    height = data['textureAtlas']['regionHeight']

    img=pygame.image.load(data['textureAtlas']['texture'])
    if c>=len(data['cycles']['animation0']['frames']):
        c=0
    if c<len(data['cycles']['animation0']['frames']):
        img.set_clip(pygame.Rect(data['cycles']['animation0']['frames'][c-1]*width,animpos*height,width,height))  # Locate the sprite you want
        draw_me = img.subsurface(img.get_clip())  # Extract the sprite you want
        c+=1
        return draw_me

```

---
Tags: animation, software-engineering, python, pygame, spritesheet
---


# Question
Title: Difference between shader input element classification between D3D12 and Vulkan
I'm confused about the difference between the shader input element classifications in D3D12 and Vulkan. For example, in Vulkan I could have the following declarations:

```
struct vertex
{
    glm::vec3 pos;
    glm::vec3 col;
};

VkVertexInputBindingDescription input_binding_description
{
    .binding = 0,
    .stride = sizeof(vertex),
    .inputRate = VK_VERTEX_INPUT_RATE_VERTEX
};

std::array<VkVertexInputAttributeDescription, 2> input_attribute_descriptions {
    VkVertexInputAttributeDescription{
        .location = 0,
        .format = VK_FORMAT_R32G32B32_SFLOAT,
        .offset = offsetof(vertex, pos)
    },
        VkVertexInputAttributeDescription{
        .location = 1,
        .format = VK_FORMAT_R32G32B32_SFLOAT,
        .offset = offsetof(vertex, col)
    }
};

```

Here the input rate is specified *per vertex* and not *per attribute*. On the other hand, in D3D12, we would have

```
struct Vertex
{
    XMFLOAT3 pos;
    XMFLOAT3 col;
};

std::array<D3D12_INPUT_ELEMENT_DESC, 2> input_element_descs =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
    D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
    { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12,
    D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
};

```

And as you can see, the input rate is specified *per attribute*. Why is that? Is there a difference between the meaning of the input classification in D3d12 and Vulkan that I'm missing? I'm not familiar with D3D12, but at first glance, it doesn't make sense to me to have different input classifications for the attributes of a vertex.

# Answer
That's because in case of the D3D12 API, there is no separation between "binding slots" and their corresponding declarations.

In Vulkan, you first specify the input bindings (eg. binding = 0 -\> vertex data, binding = 1 -\> instance data) and then specify the corresponding layout (attribute descriptors) per bindings.

```
binding = 0 -> vertex data, rate = per vertex
    attributes: [ position(location=0), texcoord(location=1), ... ]

binding = 1 -> instance data, rate = per instance
    attributes: [ ... ]

```

In contrast, with the D3D API you don't have this separation and you must define the whole input state in a single array. So if you have more than one "binding slots", you still have a single array describing all of the elements from all of the slots.

```
elements: [
    position(binding=0, semantic=POSITION0, rate=vertex)
    texcoord(binding=0, semantic=TEXCOORD0, rate=vertex)
    something(binding=1, semantic=TEXCOORD1, rate=instance)
]

```

This `D3D12_INPUT_ELEMENT_DESC` array is then used in the `D3D12_INPUT_LAYOUT_DESC` to describe all of the elements for a vertex shader.

See D3D12\_INPUT\_ELEMENT\_DESC and D3D12\_INPUT\_LAYOUT\_DESC and this guide.
> 0 votes

---
Tags: c++, directx, graphics-programming, vulkan, directx12
---


# Question
Title: Restrict A* pathfinding to overlapping "safe zones" within map
I've been bashing my head against this idea for a few days without luck, I'm hoping someone sees something I don't.

So I have a 2D map containing walls and obstacles, and I have a unit that navigates through it (A\* and funnel algorithm). So far so good. Now, for gameplay purposes, I need to limit the movement of this unit to circular safe zones that I can place on the map. Think of them like cell towers, the unit has to stay within range of at least one tower, with the max range dictated by the tower (possibly different for each tower). Effectively, imagine drawing a set of interlocking circles over the map, and the unit must remain within that.

Now for the complicated part. The map is a constrained Delaunay triangulation, not a grid, so the triangles that A\* is using can vary in size and shape. With a grid, I could imagine limiting individual grid cells by circle distances, but in my case these triangles could be larger than any one circle. There could even be cases where the start and end points of a path are within the same triangle, but because of the network of circles, an indirect path would have to be chosen to stay within the circles.

The **only** option I can think of involves adding these circles into the triangulation as additional edges, altering the map. This would mean rebuilding the map triangulation each time a player adds or removes these circles, and would require that I maintain a separate copy of that triangulation per player. And since these circles don't care about map walls, I'd have to alter my triangulation method to allow edge splitting and removal, to prevent overlapping lines from rendering the triangulation invalid.

I feel like there has to be another way to do this. I've considered:

* Running A\* purely on the circles first, then placing that intermediate path on the map and re-pathing it to avoid obstacles.
* Finding all of the circle intersections between the start and end points, and treat those lines as portals that I must pass through, somehow altering the A\* pathing to prioritize passing through them.
* Performing a regular path search on the triangulation, but forcing a dead-end whenever entering a triangle that is too far from a circle. Then refining that path to conform to the circles themselves.

Each of these have issues, or scenarios where they fall apart.

Has this been done before? Any input on how this might possibly be achieved would be appreciated.

**Edit:** Adding an image to show what I'm trying to accomplish. The red lines show the path that A\* would generate using just the map triangulation. The green lines show the desired path, taking the circle bounds into account.

# Answer
> 3 votes
Your nodes in A\* can be anything you want them to be. So you don't have to use either the circles or the triangles as your nodes. Each node can contain information about *both*:

```
Node(C, T) = portion of {circle C} overlapping {triangle T}

```

Now when you want to enumerate the neighbours of a given node, you search for...

* circles that overlap circle C in the same triangle:

`CircleNeighbours(C, T) = portion of {circle B} overlapping {triangle T}`
`...for each {circle B} overlapping {circle C}`
* OR, edge neighours of triangle T that also overlap circle C:

`TriangleNeighbours(C, T) = portion of {circle C} overlapping {triangle R}`
`...for each {triangle R} overlapping {circle C}`

By swapping just one member of the pair at a time like this, you're guaranteed that your path never leaves the safe circles, nor passes through an obstacle, nor contains a discontinuous jump.

Note that the nodes defined this way are always unique (a circle can never overlap a triangle in two disjoint places) and convex in shape, so they're still quite convenient to use as stepping stones of pathfinding.

And as a bonus, you don't have to do a bunch of complex spline math to construct the exact contours of all these nodes. Just computing that there *is* an overlap between these two circles (sum of radii vs distance) or this circle and that triangle (radius vs distance from triangle) is enough for the pathfinding algorithm to navigate the graph.

You can run A\* on this pair-based node graph to find a sequence of neighbouring circle/triangle swaps connecting your origin and destination node.

Here's a visualization of that at work on your example image, where I've coloured each circle-triangle-pair node differently from its neighbours (but note that nodes can overlap, so that purple lens shape where a blue and pink circle meet is not a third node, just a region that's a valid part of either node)

Because each of these nodes is still convex, you can make an initial path by drawing a straight line from your current point to...

* The closest point on/in the neighbouring circle that's inside the same triangle (no-op if we're already inside that circle)
* The closest point on the segment of the neighbouring triangle edge overlapping our current circle

Granted, you'll need to modify your funnel algorithm to then pull this path straight. That part will be "left as an exercise for the reader" for now.

---
Tags: path-finding, maps, delaunay-triangulation
---


# Question
Title: How can I make a chest that can be opened and shut in SteamVR?
I'm working in Unity with SteamVR for a school project. I'm trying to have a chest that can be opened and shut. I tried using a hinge joint but it would break if the attached body was static which is what I want.

I'm now trying to use a circular drive which works better but the lid to the box will move away from the intended position when colliding with the body of the box which is set to static and kinematic.

I can fix this by setting the lid to kinematic but it won't collide with the body anymore. Both the lid and body are properly colliding with the hand and with a sphere I added to help test collisions.

I'm assuming the issue is that two kinematic objects can't collide with each other but I don't know how else to approach this.

# Answer
> 0 votes
I decided the answer I was looking for was a lot simpler than I was making the challenge out to be. instead of actually needing the lid and the body to collide I just needed to make sure they never clipped through each other. the circular drive lets me set limits for how far the drive can rotate, I set the min angle to -90 and the max angle to 0, this way the lid cant go far enough to ever go through the body.

# Answer
> 1 votes
There's two different parts to your chest: The bottom part and the top part which would open up like so

One thing to understand is that 'static' objects are expected to never move throughout the scene e.g. a bridge, or a building

Sounds like in your case, the base of the chest would not move, so indeed it should be static, but if the top part can open, then it should not be static.

What about kinematic? From unity docs: If the object is kinematic, "Forces, collisions or joints will not affect the rigidbody anymore." i.e. you will not be able to grab onto the chest's top part and open it up. This means that the top part should not be kinematic either.

What about the actual implementation? I think you were on the right track adding hinge joints between the bottom and the top part of the chest. You'll probably need to tweak the values of hinge joints until you find what works for you. A good way to test if the hinge joints are working is to add the 'Constant Force' component onto the top part of the chest.

Once you know that the hinges are working, the next step would be to make the VR hands be able to grab the top part (either the whole thing or just a handle). Here what you could do is once the player's hand is close enough to the top part of the chest, if he grabs it, create a joint between the top part of the chest and the player's hand. Then the top part of the chest will follow the player's hand.

Here's a video that shows how to do that, except he's doing it with a door. Same concept applies to your chest though. https://www.youtube.com/watch?v=3cJ\_uq1m-dg

---
Tags: unity, steam-vr
---


# Question
Title: Character Jump (AddForce) unusual behavior near objects in unity 2D
My character object has a single jump mechanics and I just noticed the whenever I press the jump button many times quickly in which the character is near a "Platforms like staircase, boxes or even sometime near the edge of a platform (while also being up in the air and pressing jump many times when colliding)" it starts to fly off beyond my jump force. Can anyone help me to fix the physics? Thanks!

My Jump system code sample:

```
Rigidbody2D mybody;
public float jumpforce;
public bool isGrounded = false;
public Transform feet;
public LayerMask groundlayers;
public float groundradius = 1f;
bool Jumprequest;

void Start () {
    mybody = GetComponent<Rigidbidy2D>();
}

void Update () {
    JumpRequest();
}

void FixedUpdate() {
    Jump();
    JumpOptimization();
    isGrounded = Physics2D.OverlapCircle(feet.position, groundradius, groundlayers);
}

public void JumpRequest() {
    if (CrossPlatformInputManager.GetButtonDown("Jump") && isGrounded) {
        isGrounded = false;
        Jumprequest = true;
    }
}

void Jump() {
    if (Jumprequest) {
        mybody.AddForce(new Vector2(0, jumpforce) , ForceMode2D.Impulse);
    }

    Jumprequest = false;
}

void JumpOptimization() {
    if (mybody.velocity.y < 0) {
        mybody.gravityScale = Fallmultiplier;
    }
    else {
        mybody.gravityScale = 1;
    }
}

```

Here is a sample picture that might help: The red line shows when character collided with an object while `addforce` is added upwards and pressing Jump button repeatedly at the same time, the character flies off beyond my jump force.

# Answer
**This should ensure you have no preexisting upwards momentum when you jump**:

```
void Jump()
{
    if (Jumprequest)
    {
        mybody.velocity = Vector3.zero;    // <======= ADD THIS LINE
        mybody.AddForce(new Vector2(0, jumpforce) , ForceMode2D.Impulse);
...

```
> 0 votes

---
Tags: unity, 2d
---


# Question
Title: Using ID3D11DeviceContext::Map to update a dynamic texture results in offset or incomplete data
**Background**

I'm generating a memory texture at load time to store the offsets into a texture atlas for a tilemap as described here Any way to combine instantiated sprite renderers into one texture so I can apply into a plane at runtime? (but in DirectX, not Unity.)

I then read that texture at runtime in the geometry shader to generate a tile mesh from each tile. This works for static tiles. Animated tiles require that the tile indicies be updated in the texture every frame.

**Problem**

This is where I'm stuck. The data loaded into the texture is not the same when it is retrieved via a call to `ID3D11DeviceContext::Map`. The stride, pitch, or even the format is different such that the texture does not get fully updated or the wrong pixels are generated.

**Question**

Given the implementation of `UpdateTileIndexTexture` below, what am I doing wrong in order to fully overwrite the initial texture data with the correct pixel data?

**Implementation**

Initial generation of the dynamic texture. This step works.

```
void Map::GenerateTileIndexTexture() noexcept {
    const auto dims = CalcMaxDimensions();
    const auto width = static_cast<std::size_t>(dims.x);
    const auto height = static_cast<std::size_t>(dims.y);
    std::vector<Rgba> data(width * height, Rgba::Black);
    auto data_iter = std::begin(data);
    for(auto& layer : _layers) {
        for(auto& tile : *layer) {
            const auto* def = tile.GetDefinition();
            const auto coords = def->GetSprite()->GetCurrentSpriteCoords();
            data_iter->r = static_cast<unsigned char>(coords.x);
            data_iter->g = static_cast<unsigned char>(coords.y);
            ++data_iter;
        }
    }
    _tile_index_texture = _renderer.Create2DTextureFromMemory(data, static_cast<unsigned int>(width), static_cast<unsigned int>(height), BufferUsage::Dynamic);
    auto* mat = GetTileMaterial();
    mat->SetTextureSlot(Material::TextureID::Normal, _tile_index_texture.get());
}

```

Implementation of `Create2DTextureFromMemory` for reference:

```
std::unique_ptr<Texture> Renderer::Create2DTextureFromMemory(const std::vector<Rgba>& data, unsigned int width /*= 1*/, unsigned int height /*= 1*/, const BufferUsage& bufferUsage /*= BufferUsage::STATIC*/, const BufferBindUsage& bindUsage /*= BufferBindUsage::SHADER_RESOURCE*/, const ImageFormat& imageFormat /*= ImageFormat::R8G8B8A8_UNORM*/) const noexcept {
    D3D11_TEXTURE2D_DESC tex_desc{};

    //...Snip

    // Setup Initial Data
    D3D11_SUBRESOURCE_DATA subresource_data = {};

    subresource_data.pSysMem = data.data();
    subresource_data.SysMemPitch = width * sizeof(Rgba);
    subresource_data.SysMemSlicePitch = width * height * sizeof(Rgba);

    Microsoft::WRL::ComPtr<ID3D11Texture2D> dx_tex{};

    //If IMMUTABLE or not multi-sampled, must use initial data.
    bool isMultiSampled = tex_desc.SampleDesc.Count != 1 || tex_desc.SampleDesc.Quality != 0;
    bool isImmutable = bufferUsage == BufferUsage::Static;
    bool mustUseInitialData = isImmutable || !isMultiSampled;

    HRESULT hr = _rhi_device->GetDxDevice()->CreateTexture2D(&tex_desc, (mustUseInitialData ? &subresource_data : nullptr), &dx_tex);
    bool succeeded = SUCCEEDED(hr);
    if(succeeded) {
        return std::make_unique<Texture2D>(*_rhi_device, dx_tex);
    } else {
        return nullptr;
    }
}

```

Attempt at updating the dynamic texture at runtime:

void Map::UpdateTileIndexTexture() noexcept {
    const auto dims = CalcMaxDimensions();
    const auto width = static_cast<std::size_t>(dims.x);
    const auto height = static_cast<std::size_t>(dims.y);
    std::vector<Rgba> data(width * height, Rgba::Black);
    auto data_iter = std::begin(data);
    for(auto& layer : _layers) {
        for(auto& tile : *layer) {
            if(const auto* def = tile.GetDefinition(); def != nullptr) {
                const auto spriteCoords = Vector2{def->GetSprite()->GetCurrentSpriteCoords()};
                data_iter->r = static_cast<unsigned char>(spriteCoords.x);
                data_iter->g = static_cast<unsigned char>(spriteCoords.y);
                ++data_iter;
            }
        }
    }

    D3D11_MAPPED_SUBRESOURCE resource{};
    auto* dx_context = _renderer.GetDeviceContext()->GetDxContext();
    auto* dx_resource = _tile_index_texture->GetDxResource();
    if(HRESULT hr = dx_context->Map(dx_resource, 0, D3D11_MAP_WRITE_DISCARD, 0U, &resource); SUCCEEDED(hr)) {
        std::memcpy(resource.pData, data.data(), data.size() * sizeof(Rgba));
        dx_context->Unmap(dx_resource, 0);
    }
}
```
</code></pre>

# Answer
> 2 votes
Check the returned pitch from your map call - you're assuming it's width * 4 (for 32-bit RGBA) but it may not be (particularly if your texture is not a power of 2 or it's width is not a multiple of 4).

You can only memcpy the entire block in one operation if pitch is equal to width * number of bytes in the format. Otherwise you must memcpy one row at a time.

Sample code, excuse C-isms:

```
// assumes that src and dst are 32-bit RGBA data
unsigned *src; // this comes from whatever your input is
unsigned *dst = (unsigned *) msr.pData; // msr is a D3D11_MAPPED_SUBRESOURCE derived from ID3D11DeviceContext::Map

// width and height come from ID3D11Texture2D::GetDesc
for (int i = 0; i < height; i++)
{
    memcpy (dst, src, width * 4); // copy one row at a time because msr.RowPitch may be != (width * 4)
    dst += msr.RowPitch >> 2; // msr.RowPitch is in bytes so for 32-bit data we divide by 4 (or downshift by 2, same thing)
    src += width; // assumes pitch of source data is equal to width * 4
}

```

You can, of course, also include a test for `if (msr.RowPitch == width * 4)` and do a single memcpy of the entire thing if it's true.

---
Tags: directx, directx11, tilemap, texture-atlas
---


title: Public Relations for Game Developers

text:
# Question
Title: Public Relations for Game Developers
What is the most important thing to know about PR for indie developers?

I'm considering spending some time learning about PR in general, but it seems that the indie field is quite different than other fields in general.

What should most indie developers know about PR in general? Are PR-managers usually worth the money (and time?)?

# Answer
Hiring somebody to do your PR sounds very "non-indie." And it's certainly not likely to be good from a budgetary standpoint -- most indie games do not sell nearly as well as, say, Minecraft has.

For an indie developer with a small (or nonexistent) budget, you probably have to work the grass roots angle more than anything else. Promoting your game on Twitter/Facebook/whatever is an option but probably will not see great results unless you already have a ton of followers or friends or connections, et cetera, from previous successes. Otherwise the handful of people who follow you on Twitter are probably the ones who are pretty likely to buy your game anyhow.

First, make sure your game is reasonably stable and polished (at least in some areas) and then assemble some marketing material -- good, interesting screenshots and some compelling descriptive text to go along with them. Check out what other indie developers, like Jeff Vogel of Spiderweb Software do for their game splash pages.

Then start trying to talk to people -- basically cold-calling them. Useful demographics to target are smaller-scale publications that have a track record of dealing with or promoting indie titles (TIGSource is great, but IGN, not so much for example). See if you can entice them to review your game, or do a preview feature. You might consider suggesting that in exchange for a preview you could offer some promotional codes for the game that the site could give away, and then you have something of a cross-promotion that could be mutually beneficial.

Other indie game developers are a good market to focus on as well: some of them are actually professionals by day, and most of them will have a higher tolerance for some of the rougher edges indie games usually sport and be more willing to give the game a shot and discover its potential. Many game development sites focusing on indies, such as GameDev.Net, also have showcase and announcement forums where you can promote your project.

Set up Google alerts for your products and reach out to people who promote your product without you actually asking them too -- the random bloggers who stumble across it and post about some cool game they found (or about some bug they found with it). This doesn't have to involve offering them registration codes or anything, just a simple email with a thanks or an assurance that the bug has been fixed or is being looked in to -- that can go pretty far in terms of making an impact on people. Hopefully it will be an impact they tell their friends about.

This should go without saying, but make sure your game is easy to get, install, and get into. Struggling to even be able to launch a game is probably the biggest reason many indie games go untouched. It's difficult, not having as many resources, but try to get as many testers for your game as possible so you can ensure it's as rock-solid as possible. No amount of marketing savvy will save a broken product.
> 10 votes

# Answer
Shout out to http://www.showmethegames.com/, which aims to promote indie games and the people who make them.
> 3 votes

# Answer
Cliffski of Positech fame has a bunch of useful blogposts on marketing and PR. His blog tags are too broad for easy browsing, but almost everything in Business is worth reading: http://positech.co.uk/cliffsblog/?cat=3
> 2 votes

# Answer
I don't really have any good advice, but I have some examples. Most indie developers have a hard enough time selling *games*, let alone doing real PR.

Tale of Tales pushes a pretty consistent message about who they are and what they do, to the point of an explicit manifesto.

Wolfire has gotten a terrific amount of attention through publishing technical articles about their games. "Behind the scenes" stuff does a good job of personalizing the developers and can correct the (many) misconceptions gamers have about game development.

Eskil Steenberg, and Jason Rohrer, both of whom acquired small cults of personality, were presented consistently as outsiders who were going to stick it to the man with their new approaches to making games. Whether that's because they wanted that, or because the media loves to tell underdog stories, is anybody's guess.

(CW - this is too long for a comment, but not a real answer to the question, and maybe other people can add good examples.)
> 1 votes

# Answer
First off, I think that the best example in recent time is Minecraft. It's not (all) coincidence that Minecraft has grown to be as successful as it has.

The developer has put out a game from very very early on in the development life-cycle (pre-pre-pre alpha? anyway, it's only in beta now). From that we get a few principles:

* Get the game out there for people early. Even if it turns out that people who try it hate it, better you learn that early, when you can still change direction or try a different game prototype.
* Get the word out as soon as you can, so you can start building link power for your website (and you pretty much always want a website).

In addition, it seems that early user-created-content helps: Make the basic game mechanic something that people can pour their heart & soul into, and they will be more likely to spread it via word of mouth on their own.

---

From my own personal experience, google adwords is a (relative) very cheap PR method, you can get a lot of coverage, and get "testers/players/viewers" at quite a cheap rate.
> 0 votes

# Answer
From my experience the concept of PR for indie developers apply in other fields as well.

When it comes to PR you must have good understanding of what you want to get out of your PR campaign before you begin with it.

The costs for PR campaign are usually high which and the KPI are mainly brand awareness, all of these make launching PR campaign as a indie developer not so worthy.

BUT, I think your approach should be a bit different.

Creating high quality content which gives value to your target audience and sharing it in forums/channels (where your target audience is) can drive free PR for your project.

I know this because I work for a blockchain company.

The company is relatively small therefore we have a strict marketing budget.

We wanted to run a PR campaign few months ago and met with few marketing agencies but we decided to run a PR campaign in house (mainly because a solid PR campaign can cost 20,000$ per month and above which we don't have).

Your focus should be: **creating high quality content around your focus keywords**. Only after you wrote great articles (can take up to few weeks per article) and got the article indexed, you should consider running a link building/PR campaign. I actually recommend waiting few months-year before approaching a PR agency (as indie developer).

There are few articles and resources I'm using as cornerstone content. I'll share some of them with you:
> 0 votes

---
Tags: marketing, publishing, outsourcing
---