# Question
Title: How can I implement an inventory that stores different types of items?
Let’s assume I want to create an RPG with collectible items my character can pick up and store in his inventory.

One item could be a sword, with an attack, defense, and level attributes.

Another item could be an apple, heal percentage, freshness, and servings attributes.

Both items are collectible items, and both objects can be stored in the players inventory, but they share separate sets of attributes.

I am trying to think of a way to set this up in the database. I originally looked to the EAV database model, so I could define a single collectible item entity, and bolt on separate attributes as I needed them, but I discovered EAV is slow because of multiple calls to the database to construct an entity, which wouldn't make it very suitable for a game in my eyes.

I also can't find any game development tutorials that use EAV, so there must be a more common solution I'm not aware of.

# Answer
> 40 votes
When you are comming from non-game application development, then you need to be aware of a couple things.

1. Relational databases have a niche role in game development. You really only need them when you have a massive multiplayer game where most of your players are offline most of the time. There are also some niche applications like online scoreboards or analytics. But it is pretty rare to handle any static game data like item attributes with them.

The usual method to handle data like that is to load all the data you need at game start from a flatfile and then keep it in RAM while the game is running. I don't know how many items you have in your game and how much data they have, but unless your item database is in the order of hundreds of MB (I would go up to a GB if I target PC exclusively), you really don't need a relational database for them.

When you *do* have the problem that your game needs to work with so much data that it doesn't all fit into RAM at the same time, then off-the-shelf SQL databases are not completely unheard of. But not only is this not actually a very common problem. If the problem *does* come up, then it is far more common to create home-brewed solutions for it.
2. A more game-appropriate solution for a situation where you would use the Entity-Attribute-Value architecture is often the Entity-Component architecture. The item entity "iron sword" has the components "Tradeable" and "Weapon". The item "Apple" has the components "Tradeable" and "Consumable". The item "Chocolate Sword" has the components "Tradeable", "Weapon" and "Consumable".

What kind of file format do you use to represent items with components? That's more of a religious question. But some data formats which are pretty suitable for hierarchical data like that are XML or JSON. I have an example for XML in this answer to a slightly different question.

# Answer
> 1 votes
As I understood it, i would make a table "Inventory" this table would contain just things like "ID", "Reference to the item" and then also additional columns like "durability", "attribute1", "attribute2".

# Answer
> 1 votes
While this depends a lot on the amount of your items and the data associated, I do not see much issue with using an EAV solution - anything currently in use will be stored in RAM as regular old objects, all the "heavy" database interaction happening only whenever inventory is loaded/unloaded as the player enters/leaves the game.

If you insist on more robust persistence and updating the "offline" inventory every time an item changes, normally that should still work quite well as databases tend to be quite quick at this sort of thing, even if every single item results in 10+ calls. This can be optimized, but by all means implement first and test performance later.

Another thing to keep in mind - you might want to keep a distinction between actual item instances (e.g. this specific Sword of Banishing that is enchanted for fire damage and has a gem socketed) versus item "templates" (e.g. "a Sword of Banishing can generate with 20-25 attack damage, randomly, sells for 300GP and can be recycled into Metal Scrap (Regular)").

A database would also integrate easily with other things, if your game would ever need a web interface or an item reference, for example.

What I have tried as well was fully separating the templates from instances and serializing the instances (i.e. actual items that are in your character's inventory) to a database but storing the templates as flat files that refer to the same properties as the serialized items (ideally, these properties are defined elsewhere and the game also refers to these definitions for the purpose of actual game mechanics).

# Answer
> 0 votes
Games like Dark Souls save your inventory each time it changes. I don't know how they deal with app closing or crashing during a write, but I have tried randoms ALT+F4 and the system look robust to me. So the idea isn't new.

I, personally, prefer to keep everything in RAM and write to disk on save game, until that proves to be too inefficient (never happens). It has to be a really complex game to worry about that. And I prefer crude arrays or generic containers versus SQL apis.

Said all that, possible structures for tables in a data base:

You only need a table to save the status of your BAG, because item properties are classes definitions in your game code.

```
BAG Table
ID     SLOT     TYPE      COUNT_OR_HEALTH
1      0        Potion1   40
200    1        VorpalSw  98
3      2        Antidote  26

```

Explanation of the COUNT\_OR\_HEALTH column. Your game code knows that consumables like Potion1 and Antidote doesn't have health, so that field is used to save how many of those items do you have stacked into that slot. While Weapons aren't stackables, so that field means the health of the item (assuming game with repairable/breakable items). Add as many columns as you need. No need for EAV in my opinion, too complex.

Just note that tools exists to load most databases table files, like in the case of SQLite. Cheaters may find this and open the file to always have 99 potions. Obfuscation or another solution is required.

Definitions of items lives in your game code, as classes. You can use interfaces for the base types.

Very crude example:

```
interface Item
{
    string Type ();
}

interface Consumable
{
    bool Consume (Character target);
}

public class Potion : Item, Consumable
{
    protected string Name; // Name of the potion
    protected int    HP; // Recover of HP
    protected int    MP; // Recover of MP

    protected string [] ClearStatus; // Cure status like poison.
                                     // TODO: make status an enum

    public Potion (string name, int hp, int mp, string [] clear)
    {
        Name = name;
        HP = hp;
        MP = mp;
        ClearStatus = clear;
    }

    public string Type ()
    {
        return Name;
    }

    public bool Consume (Character target)
    {
        target.hp += HP;
        target.mp += MP;

        if (ClearStatus != null)
            for (int i = 0; i < ClearStatus.Length; i++)
        {
            target.RemoveStatus(ClearStatus[i]);
        }

        Simulation.instance.Changed();
        return true;
    }
}

public class BagSlot
{
    public string Type = "";
    public int    Count = 0;
    public int    Health = 0;
}

// Incomplete class, only an example
public class Simulation : ScriptableObject // or MonoBehavior attached to main camera if you need Update
{
    // All potions of the game
    protected Dictionary<string, Potion> Potions;
    protected void InitPotions ()
    {
        Potions = new Dictionary<string, Potion>();

        //          Name in map            Name       HP    MP    Clear Status
        Potions.Add("Potion1",  new Potion("Potion1",  200,   0,  null));
        Potions.Add("Potion2",  new Potion("Potion2", 1000,   0,  null));
        Potions.Add("Ether",    new Potion("Ether",      0, 100,  null));
        Potions.Add("Antidote", new Potion("Antidote",   0,   0,  new string [] {"Poison"}));
    }

    // All weapons of the game
    protected Dictionary<string, Weapon> Weapons;
    protected void InitWeapons ()
    {
        Weapons = new Dictionary<string, Weapon>();
    }

    // The BAG
    public List<BagSlot> Bag = new List<BagSlot>();

    // (...)
}

```

Many possible designs exist.

Different thing is if you want a way to describe items because you will have a growing itempedia. Doing that is a lot of trouble, and a better way would be to expand the itempedia with each game update, always including the new items as hardcoded lists/maps/arrays.

The BagSlot class can hold any type of item, an keep track of stacking and durability (if you want durability). We don't like complicate type casting here and there, we prefer a simple string telling us the name of the item in that slot.

Usually, games don't allow duplicated names, no matter if items are of different type. We use that to effortlessly find the correct item, no matter its type.

When player enter the consumable item menu, we iterate the Bag and only return consumables.

When player is in the equip menu, we iterate the bag and only return weapons, armors, etc.

---
Tags: unity, architecture, databases, inventory
---


# Question
Title: Authentication for LAN Multiplayer Games
I'm working on the authentication scheme for a multiplayer game using only C++ and SLD2.

It's an RPG with a kind of complicated character-group/permadeath scheme, and world-instances are intended to be hosted by the players. So it matters that players have exclusive access to controlling their characters. I want players to be allowed to save the current state of a multiplayer world instance, close it, and come back to it later, or set up their own dedicated world instance for them and their friends to join/quit/rejoin at will. Absent player characters will simply not be present in the world until their creator returns

Servers will be hosted by player-computers. I'm not planning to set this up with a dedicated hole-punching or identity server, so players will just be playing with people who they intentionally connect to. I don't want to deal with encryption, so I'm not planning to require passwords to log in. I figure since there's no formal identity server and no encryption, passwords might do more harm than good. Player character names will change over the course of the game, and I don't necessarily mind if two players have the same username.

Here's my current authentication strategy:

When a player creates an account on his/her game instance, the account will just consist of a username and an automatically generated (random) UUID. The username and UUID will be stored in a SQLite file that the user can copy onto any computer with this game installed, and access their unique account. The username and a naively hashed UUID will be stored in a connection log on every server that the player connects to (so the server can assign them to the right character when they log back in). I recognize this means that programmers who know what they're doing will be able to hack each other's accounts, but I'm not convinced that I should really be concerned about that in the case of this particular game.

Here are my questions:

* Is copying the file too much to expect from users who want to switch computers?
* Can you guys think of any potential issues with this, other than what I've already pointed out?
* Is there a better (common) way to achieve what I'm trying to do?

Thanks!

# Answer
> 1 votes
> Is copying the file too much to expect from users who want to switch computers?

Not really. Well, it could be for younger less tech savvy players. Regardless, you want to make it easy. The user might not know what files to copy or where to find them. Have an export and import feature.

If I understand correctly, this is not only for the world, but also for the characters. That is, I would move my character to a different machine.

It could be a hassle to set up a multiplayer session if it requires to get everybody's character files in the server. However, that has the advantage that it ensures that only those players can join.

---

> Can you guys think of any potential issues with this, other than what I've already pointed out?

Hmm... Let me be thorough.

From a game design stand point. If people are moving their character files around, and could tamper with them... could they set up some overpowered characters? Or perhaps they could bring tons of items and wreck the economy? I do not know what information is in those files or if there is an economy in your game. I suppose that if it is all cosmetic, there is no problem.

---

From an information security stand point, we want to – at least – protect the following properties of the information:

* Confidentiality: People who are not the right users should NOT have access.
* Availability: The right user should have access.
* Integrity: The information should not be corrupted.

On that framework, the first concern is integrity. One simple solution is to have backups. The export and import feature would help with that. Consider to auto backup when the world is loaded. You may also consider to have a checksum for the world, so you can detect when it was corrupted.

---

Beyond that, we would only have reason to worry about in the scenarion where they are playing on a public network (public as in public WiFi). *Probably not the intended use case.* I would warn the players not to do that.

---

Under the assumption of a public network. The second concern is confidenciality. Two problems:

* An uninvited player joins.

If we have to move the character files to the server, this is covered.

Aside from that, you could have *the option* to have a password. However, not a password for the users, but for the world. So that only players that input the world password can add their characted and join the game.

Yeah, of course, the password could be circumvented by having access to the machine. However, whoever has access to the machine has control over the game world. Thus, do not worry about that. *You may even store the password in plain text, you have my blessing.*
* A malicious user spies.

I'm thinking about in-game chat. Well, the solution is to not have chat. *Har har.*

Baring that, you could use symmetric cryptography. In fact, you can derive the key from the world password. On that note, see: Should I encrypt my multiplayer network traffic?.

There is a third concern: availability. You would be listening to some ports. On a public network somebody could try a denial of service attack by spamming those ports. You want some good defensive programming against network input. I'd suggest to soft ban IPs that are sending invalid traffic. *In fact, while we are at it, make sure you do not have any buffer overflow vulnerabilities. Hopefully not, nobody writes network code like that anymore, right? RIGHT?*

---

> Is there a better (common) way to achieve what I'm trying to do?

Password protected games and matches are very common.

Aside from password for the world/match, which the players input to join...

A less popular idea is asking the player who is acting as server to grant access to every player who wants to join. There would be no password, any body could request to join. The drawback is that if you allow them to join mid-play it would interrupt the player. So this is something you would do on a lobby for a match.

---

Moving a character from server to server is very rare. I do not have any more common or better way to do it that just moving the files.

You can consider to automate sending the files over the network from one game intance to another. *Then you open the possiblity of some rando in the public network sending you a character file.*

---
Tags: c++, sdl2, authentication
---


# Question
Title: What program was used in Kojima's Death Stranding to create the 3D scans of people?
I've been unable to find out what program Hideo Kojima used to create his 3D scans of people in his game Death Stranding and presumably Metal Gear V as well. Here is a video of the scanning in progrees (Starts at 4:45 https://www.youtube.com/watch?v=KlMpN26ts7s).

# Answer
Death Stranding was created wit the help of the Sony Playstation Visual Arts Services Group, located in San Diego. They did the body scans and motion capture for the game and the trailer.

The only thing I have been able to figure out about their photogrammetry and motion capture solution, aside from the rig shown in the linked video, is that they use a a proprietary software compatible with Autodesk Maya and Motion Builder.
> 1 votes

---
Tags: camera, 3d-meshes, motion-capture
---


# Question
Title: How to prevent top down sprite snapping during diagonal movement upon keyboard release
I have a sprite that faces 4 directions depending on input. This is all working well except for my keyboard input..

If I am pressing down-right at the same time on the keyboard and release both keys there is a moment where I am pressing only the right key. This creates a snapping of my sprite upon key release where now im suddenly facing right instead of down.

basically i would like to release both the x and y buttons at the same time but i dont have a good way of detecting this. its TOO sensitive.

```
    pressed_vector.x = int(directions.right) - int(directions.left)
    pressed_vector.y = int(directions.down) - int(directions.up)

    dpad_vector = pressed_vector.normalized()
    owner.direction_changed(dpad_vector)

```

its the standard input code you see everywhere.

I have the player mapped to a virtual joystick, dpad etc and i dont have this issue because on release you're going to be releasing your x and y keys at the same time. not sure how to handle this with the keyboard.

# Answer
> 1 votes
I can see two ways to avoid this problem:

* Base the player animation decision on the sprite's effective velocity (speed and direction), rather than pressed input keys. This can be a good idea if using movement with relatively low friction and acceleration.
* Add a Timer node set to Oneshot that will act as a *debounce* timer. Its wait time should be very low (0.05 seconds or less) and should be reset every time a movement key is pressed *or* released. Only apply movement animation changes when the timer node times out by connecting its `timeout` signal to a function in your player script.

---
Tags: vector, rpg, godot, adventure-games
---


title: What are spline input keys?

text:
# Question
Title: What are spline input keys?
There isn't a really adequate explanation of these anywhere on the internet, so I thought I'd ask this question here.

* What are spline input keys in Unreal?
* How are they represented in Unreal?

---

Also:

* FindInputKeyClosestToWorldLocation returns a float.
    + What is this return value?
    + Why is it a float?

# Answer
> 3 votes
A spline key input is a bit like an index into the spline. A spline is generally formed from control points, similar to a Bezier curve. My knowledge on this is rusty, but the idea seems to be that the starting point has the value of 0.0f, and is increased by 1.0f (by default) per point, so a minimal spline out of two points goes from 0.0f to 1.0f while one made of 4 points would go from 0.0f to 3.0f, with the intermediate points having the values 1.0f and 2.0f.

Why a float? So that you can point at somewhere between the control points and ask what the value there is. In the case of our simplest spline, "two-thirds through" would correspond to 0.67f. This value basically encodes two things in one in a way - the integer part selects the two points between which the interpolation happens (0.67f =\> points 0 and 1) and the fractional part selects the amount of interpolation (.67 =\> 33% of point 0, 67% of point 1).

FindInputKeyClosestToWorldLocation - this function takes a world location and finds the closest point on the selected spline to that location. It then determines the input key value and returns it.

Here's a mediocre visual drawn in Paint:

Here, a spline is drawn in green, with two points (0 and 1) being its control points. A point **A** is selected. What the function does is find the point **B** on the spline which is the *closest* to point **A**. Then it determines the *value of the key input* at the point **B**, which appears to be roughly halfway through, corresponding to around 0.5f.

If I understand it correctly, it is possible to specify your own values for key input on the points, so a 4-point spline can go from 0.0f to 1.0f with the two midway points being at 0.25f and 0.75f or even having their own custom values.

---
Tags: 3d, mathematics, rotation, unreal-4, splines
---


# Question
Title: Getting user id from one scene then to the next scene
I'm new to multiplayer and photon so pardon me if this question is somewhat frequent.

I have successfully set up my project to start from a main menu - waiting room - actual gameplay scene. However I couldn't search my way through getting a sort of user id from waiting room(ie; order of user joined to waiting room) then use it in the gameplay scene to manipulate sort by score / by hp / etc.

Perhaps I got the while concept of having to identify unique players via such variable? I'm not quite sure. I just got my foot in the multiplayer development realm, so please go easy on me.

// Edit

Sorry for my initial question being quite vague. Basically, I'm trying to replicate this with Photon. I've got various things set up but was stuck at where designating individual players to individual player info panels as if captured(Get WHAT to connect to those UI elements I've got set up).

It'd be simple enough even for me if this was a singleplayer, but since it's not I'm also refactoring a lot on the way as well. Thanks to both of the answers given so far I'm looking into Photon UtilityScripts(To a novice to anything simply directing where to look helps a ton, so thanks again), but since I'm not quite there yet I'll update my progress.

# Answer
If you're using Photon, you should be able to set each user id in one of the following ways:

> Once authenticated, a Photon client will keep the same UserID until disconnected. The UserID for a client can be set in three ways:
>
> 1. Client sends its UserID before connecting by setting AuthenticationValues.UserId. This option is useful when you do not use Custom Authentication and want to set a UserID.
> 2. An external authentication provider returns the UserID on successful authentication. See Custom Authentication. It will override any value sent by the client.
> 3. Photon Server will assign GUIDs as IDs for users that did not get UserIDs using 1 or 2. So even anonymous users will have UserIDs.

So basically, if you don't set it, it will set a userID for you.

You can then get the userID for each player to be published to each player in the room by setting RoomOptions.PublishUserID = true, and finally getting the UserId with PhotonPlayer.UserId

> Players can share their UserIDs with each other inside rooms. To enable this and make the UserID visible to everyone, set RoomOptions.PublishUserId to true, when you create a room. The server will then broadcast this information on each new join and you can access each player's UserID using PhotonPlayer.UserId.

Then using it across different scenes, you will want to store it in a script Component on a GameObject and use DontDestroyOnLoad(this.gameObject) in the Start() function for this script. This will cause the script to stick around between scenes. (Be careful with this though, you could end up with multiples, so make sure it's only created once) See the docs for DontDestoryOnLoad here: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

See the full detail here: https://doc.photonengine.com/en-us/pun/current/lobby-and-matchmaking/userids-and-friends
> 1 votes

# Answer
If you want to keep track of the order when users joined the room (which should actually not matter much) you just need to keep track of them when they join the room. Photon is providing the player with `OnPhotonPlayerConnected(PhotonPlayer newPlayer)`. You can set the time when they joined the room in the custom room property if needed with a time stamp. Let the masterclient handle it or let each client write it when they arrive. If you want to get a whole list of them at once, you can access them via `PhotonNetwork.playerList`.

PhotonNetwork persists between scenes and there are a few example tutorials provided directly by Photon. It's worth checking out both Pun and Pun2, since the examples they have are slightly different (Pun has for example a simple Rock-Paper-Scissor game which is missing in Pun2) but the code is almost the same.

And if you want to use something for displaying as scores, you should not use the userId but instead `PhotonNetwork.player.NickName`. The userId is unique, the Nickname is usually what the player is itself choosing and does not need to be unique.

I assume your game is round based (looks like auto chess or similar). Each player could just report his own stats after each round with `PhotonNetwork.RaiseEvent(TOKEN_UPDATE_SCORE, payload, true, new RaiseEventOptions() { CachingOption = EventCaching.AddToRoomCache });`. You need to subscribe to `PhotonNetwork.OnEventCall += OnEvent;` where `public void OnEvent(byte eventCode, object content, int senderId)`. All clients are getting that way an update of the score after each round (or whenever you call it)
> 1 votes

---
Tags: unity, multiplayer, photon
---


# Question
Title: How to make wall tiles overlap floor tiles a bit in Unity3D?
Currently my tiles are very strictly placed, there are wall tiles, and floor tiles, and they don't overlap at all.

What I want to achieve is to have **my walls overlap my floors a bit**.

So their **inner edges** doesn't have to be a **stright line, but a free shape**, with **"transparent holes"** which **show the floor below**. Resulting in a much better feeling.

My current approach is to have **multiple layers**. One for the floor and wall (single) tiles), and one above this, which will have the overlapping, decorative parts of the walls.

But this methods **feels slow and clunky**:

For **one wall tile** I have to **place 9 tiles/tileparts** to make it look nice. (the tile itself plus the neighbours).

**It would be better to place just one tile which got overlapping parts**

# Answer
Use a set of tiles that are specific for the place where the walls meet.
This is an example with 8 tiles. You can make more if you need.
In this example you see tiles for dirt and grass and areas where the grass and the dirt meet. This image was taken from the Constract 2 Manual.
> 1 votes

---
Tags: unity, tilemap
---


title: Unity3d Android - Fixed Resolution

text:
# Question
Title: Unity3d Android - Fixed Resolution
How can i set a fixed 720p resolution on any devices using unity3d android?

> unity3d version: 2018.4.5f1

# Answer
https://docs.unity3d.com/ScriptReference/Screen.SetResolution.html

Be careful with the aspect ratio of the screen, use something like this:

```
 Vector2Int newResolution = Vector2Int(720, Mathf.RoundToInt(Screen.height * 720 / Screen.width));
 Screen.SetResolution(newResolution.x,newResolution.y, true);

```
> 1 votes

---
Tags: unity
---


# Question
Title: dx11 Rendering to target texture shows only clearcolor(ImGUI-Custom Game Engine)
Im trying to create a game view for my game engine using **ImGui framework**,however when i try to render texture,there is only clear color displayed on the screen.

**My plan**

* Creating Render Target Texture(I think i done this part right(i think))
* Writing my scene into target texture(I presume this is where i failed,only clear color displayed on the screen,my test triangle not displayed)
* Crearting a shader resource view(I tested this and the next step via loading image from the disk,it shows no problem here)
* Display it on İmgui::Image()

Using render texture only clear color and Imgui Editor elements displayed on the screen when set back to normal rendering,my test triangle appears on the screen.

**My Render Texture Creation**

```
D3D11_TEXTURE2D_DESC textureDesc;
D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;

ZeroMemory(&textureDesc, sizeof(textureDesc));
textureDesc.Width = 1920;
textureDesc.Height = 1080;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
textureDesc.SampleDesc.Count = 1;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = 0;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;

renderTargetViewDesc.Format = textureDesc.Format;
renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
renderTargetViewDesc.Texture2D.MipSlice = 0;

DLE_Graphics::CurrentGraphics->pDevice->CreateTexture2D(&textureDesc, NULL, pTargetTexture.GetAddressOf());

shaderResourceViewDesc.Format = textureDesc.Format;
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
shaderResourceViewDesc.Texture2D.MipLevels = 1;

DLE_Graphics::CurrentGraphics->pDevice->CreateShaderResourceView(this->pTargetTexture.Get(), &shaderResourceViewDesc, this->pResourceView.GetAddressOf());

// (re)-create the render target view
DLE_Graphics::CurrentGraphics->pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(pTargetTexture.GetAddressOf()));
DLE_Graphics::CurrentGraphics->pDevice->CreateRenderTargetView(pTargetTexture.Get(), &renderTargetViewDesc, pRenderTargetView.GetAddressOf());

// create the depth and stencil buffer
D3D11_TEXTURE2D_DESC dsd;
pTargetTexture->GetDesc(&dsd);
dsd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
dsd.Usage = D3D11_USAGE_DEFAULT;
dsd.BindFlags = D3D11_BIND_DEPTH_STENCIL;

DLE_Graphics::CurrentGraphics->pDevice->CreateTexture2D(&dsd, NULL, pDepthTexture.GetAddressOf());
DLE_Graphics::CurrentGraphics->pDevice->CreateDepthStencilView(pDepthTexture.Get(), NULL, pDepthView.GetAddressOf());

// activate the depth and stencil buffer
DLE_Graphics::CurrentGraphics->pContext->OMSetRenderTargets(1, pRenderTargetView.GetAddressOf(), pDepthView.Get());

```

**My Rendering Code**

```
const FLOAT clr[] = { 0.0f, 0.5f, 0.5f, 0.0f };
    pContext->ClearRenderTargetView(pRenderTexture->GetRenderView().Get(), clr);
    pContext->ClearDepthStencilView(pRenderTexture->GetDepthView().Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 0u, 0u);
    pContext->OMSetRenderTargets(1u, pRenderTexture->GetRenderView().GetAddressOf(), pRenderTexture->GetDepthView().Get());
    pContext->DrawIndexed(size, 0u, 0u);

    pSwapChain->Present(0u, 0u);

```

**If anyone curious this is my swap chain description**

```
DXGI_SWAP_CHAIN_DESC description = {};
    description.BufferDesc.Width = 1920;
    description.BufferDesc.Height = 1080;
    description.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    description.BufferDesc.RefreshRate.Numerator = 60;
    description.BufferDesc.RefreshRate.Denominator = 1;
    description.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
    description.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    description.SampleDesc.Count = 1;
    description.SampleDesc.Quality = 0;
    description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT ;
    description.BufferCount = 1;
    description.OutputWindow = hWnd;
    description.Windowed = TRUE;
    description.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    description.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

```

When i use my render texture and create a resource view to be used for ImGui::Image to show,there is no image,not even **clear color** or **black color**.If i use my image on my **disk** for the ImGui::Image it displays the image,i dont know what im doing wrong here

Here's my imgui code

```
ImGui::Begin("Spectrum Observer");
    ImVec2 pos = ImGui::GetCursorScreenPos();
    //ImGui::Image(texture->GetResource(), ImVec2(512, 512)); // my image from the disk
    ImGui::Image(pGraphics->pRenderTexture->GetResourceView().Get(), ImVec2(512, 512)); // render texture
    ImGui::End();
    ImGui::Render();
    ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());

```

Every possible input is appreciated,thank you

# Answer
> 1 votes
I managed to solve the triangle rendering problem via changing ClearDepthStencilView() 0u to 1u

```
const FLOAT clr[] = { 0.0f, 0.5f, 0.5f, 0.0f };
    pContext->ClearRenderTargetView(pRenderTexture->GetRenderView().Get(), clr);
    pContext->ClearDepthStencilView(pRenderTexture->GetDepthView().Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1u, 0u);
    pContext->OMSetRenderTargets(1u, pRenderTexture->GetRenderView().GetAddressOf(), pRenderTexture->GetDepthView().Get());
    pContext->DrawIndexed(size, 0u, 0u);

    pSwapChain->Present(0u, 0u);

```

Appearently i was clearing the depth buffer to 0 which indicates all depth values nearest possiible which leads to failing ztest.

---
Tags: architecture, rendering, directx11, rendertexture
---


title: How to make a teleporter in unity3d?

text:
# Question
Title: How to make a teleporter in unity3d?
For my game, I need to teleport player (`GameObject`) to a position (`Vector3`) whenever it touches a cube with this script. I tried using this:

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

public class Teleporter : MonoBehaviour
{

    public GameObject player;
    public Vector3 target;

    void OnCollisionEnter(Collision collision)
    {
        player.transform.Translate(target);
    }
}

```

and passing player and position in the inspector:  but it does nothing, when player touches a cube with this script. Please tell me how to fix this, or a completely new idea to teleport the player, that works. Thanks

# Answer
> 1 votes
`transform.Translate()` takes a *relative* offset, ie. "How far do you want me to move from where I am?"

If you pass (0, 0, 0), as in your current inspector settings, you're saying "don't move anywhere at all" — so it's obeying, exactly as you asked.

Instead, you might have meant to write:

```
player.transform.position = target;

```

...to reposition the player to the point (0, 0, 0) in world space.

---
Tags: unity, collision-detection
---


# Question
Title: Unity performance issues when rendering items
I'm trying to get the position of items in the game world and render them onto the screen. I've managed to get this working, however I seem to be running into major performance issues when ever I enable this feature. I am losing about 40-50 fps. I have a feeling this is related to iterating through the array doing the transformation within the OnGUI() life cycle method which is called multiple times a frame, however I'm not entirely sure. Any pointers would be appreciated, I'm still very new to game development.

Code in question:

```
private void OnGUI()
{
    if (showItems)
    {
        DrawLoot();
    }

    if (showItems && Time.time >= itemNextUpdateTime)
    {
        lootItems = UnityEngine.Object.FindObjectsOfType<LootItem>();
        itemNextUpdateTime = Time.time + itemUpdateInterval;
    }
}

```

Draw Method:

```
public void DrawLoot()
{
    foreach (LootItem item in lootItems)
    {
        if (item == null || item.name == null || item.name == string.Empty)
        {
            continue;
        }

        var pos = Camera.main.WorldToScreenPoint(item.transform.position);
        float itemDistance = Vector3.Distance(Camera.main.transform.position, item.transform.position);
        Vector3 vector = new Vector3(pos.x, pos.y, pos.z);
        if (itemDistance <= maxLootDrawingDistance && vector.z > 0.01)
        {
            string itemLabel = $"{item.Item.ShortName.Localized()} - {itemDistance}";
            GUI.Label(new Rect(vector.x - 50f, Screen.height - vector.y, 100f, 50f), itemLabel);
        }
    }
}

```

# Answer
I think you should abandon **OnGUI** completely.

You can use unity's UI system to achieve your desired outcome.OnGuı is an **immediate** method which is not performance friendly.You can think of OnGui as an unity's debugging toolkit,its great to have quick setup and feedback yes but it should not be an endgame for your game/project's UI.

**Furthermore**,if your goal to only see items on the screen,you can use simple sprites, If its only text you want to show then you can use textmesh component in unity.

Plus when i look at your code above i think there is more room to increase your FPS.

**First**,avoid immediate context.Try avoid updating stuff every time.Use unity's framework as long as you can,creating your own custom script with your custom solutions is often costly than you'd expect.So if you want to display the related graphics(text,sprite) of your items on your screen,display them when you're sure it's in the canvas of the camara.To achieve this you can use unity's physics to detect whenever the object is inside the camera's view,or you can use **SpriteRenderer2D's** isVisible property which indicates if an item visible to the camare.(Beware this **isVisible** property will be marked as true if there is an **another camera** rendering your sprite)

**Second**,avoid immediate context again.I see you collect your items' data everytime before you display them.**UnityEngine.Object.FindObjectsOfType()** is an expensive solution to this.FindObjectsOfType iterates every object in your scene and checking each if the type you looking for matches with them thus its pretty expensive,and more expensive when you have large scene.To avoid this you can use a pool.Try saving your each item to this pool,this pool may have basic interface like,add new item to pool,remove item from the pool,with something like this you can avoid collecting your items each frame.
> 0 votes

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


title: Bounce with multiple collisions

text:
# Question
Title: Bounce with multiple collisions
Here's the problem: I'm writing an Arkanoid-like game in Unity 5.3. I'm using 3D physics and simply ignoring z-axis in computations. No gravity, 0 drag and velocity reset every bounce by script. My ball has sphere collider and rigidbody with continuous dynamic collision detection on it, and bricks have box colliders with continuous detection. They are set like tiles, one by one, without gaps.

The problem occurs when a ball collides with two bricks at once, which causes a wrong bounce angle. Smaller sphere colliders makes this situation occur less often, but causes the ball to ignore collisions sometimes and phase through a single brick.

I know the probable reason for this bug, I think a collision with two objects affects ball physics twice. The question is: how to avoid it?

# Answer
When you have a bunch of adjacent box-colliders and expect that they behave like a continuous wall, then unfortunately they won't. As of version 5.3.4, this is an edge-case the Unity physics engine does not handle correctly.

When a rigidbody collides with the edge between two box-colliders, Unity will register it as a collision with the edge of one collider and give you a bounce-angle which you would not expect.

How could you work around this problem?

Either you ditch the Rigidbody on the ball, turn all the colliders into trigger-colliders, and implement the ball-physics yourself. If you want to make an authentic Arcanoid clone, all the more complex nuances of the physics engine would be switched off anyway and all that's left to do is moving the ball by a constant velocity vector and changing that velocity vector on collisions.

If you want to use the Unity physics engine (maybe adding some more detailed physics might give an interesting new spin on the old Arcanoid concept), then you will have to work around that quirk in the physics engine by building your own colliders. When you have two or more adjacent blocks, you will need to merge them into one object with one collider. That would likely be a MeshCollider (when you use 3d physics) or a PolygonCollider2D (when you use 2d physics). You will have to generate the Mesh / Path yourself using a script. Also, you will have to write an own script to check which blocks are affected when the ball collides with the collider.
> 2 votes

# Answer
If you want to avoid writing your own physics, or you want to stick with Unity's physics, you can use some **averaging** with your collision data.

You collect each collision's data in **OnCollisionEnter** and average their position and direction to a final one.This will give you a very sloppy&unstable approximation of what you should expect.

I think there is another way to get over this. You said your bricks have box colliders, I assume you don't have jagged edges on your bricks. If these assumptions are correct then we will start by considering all the bricks are lines and compute the reflected direction of the ball by using the transform.right property of your bricks.

The **transform.right** property of your bricks will determine the virtual domain of the box collider. For example, if your ball falling 90 degrees downwards and your brick's transform.right is Vector3(1,0,0), then your ball will go upwards the exact way it came. If the transform.right property is Vector3(1,1,0) then your ball will go 45 degrees to the left.

And again it's a sloppy approximation and probably you will end up using your **boxcollider bounds** and maybe transform.up as well in order to achieve perfect collisions.
> 0 votes

---
Tags: unity, collision-detection, physics
---


# Question
Title: Problem with "only assignment, call, etc." while i was trying to make my 2D character not jump in the air
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class move2d : MonoBehaviour
{
    public float moveSpeed = 5f;
    public bool isGrounded = false;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Jump();
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }

    void Jump()
    {
        if (Input.GetButtonDown ("Jump") && isGrounded == true) {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
        }

    }
}

```

and another file for stopping my character from jumping in the air

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

public class Grounded : MonoBehaviour
{
    GameObject Character1;
    // Start is called before the first frame update
    void Start()
    {
        Character1 = gameObject.transform.parent.gameObject;
    }

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

    }

    private void OnCollisionEnter2D(Collision2D collision) {
        if (collision.collider.tag == "Ground")
        {
            Character1.GetComponent<move2d>().isGrounded == true;
        }
    }

    private void OnCollisionExit2D(Collision2D collision) {
        if (collision.collider.tag == "Ground")
        {
            Character1.GetComponent<move2d>().isGrounded == false;
        }
    }
}

```

# Answer
Firstly, whenever you get a compiler error, it's vital that you include both the *full* error message:

> Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

*and* the line that the error occurs on:

```
 Character1.GetComponent<move2d>().isGrounded == true;

```

Second, this type of error is called a syntax error. It's not a problem with your game-specific logic that you need a gamedev expert to solve. It means you got the fundamentals of the language wrong.

Here, it's because you used the equality comparison operator `==` when what you wanted was the assignment operator `=`.

`Character1.GetComponent<move2d>().isGrounded == true;` means "*Is* `move2d.isGrounded` currently true?" - ie. it's a conditional, something that only makes sense inside an expression like the inside of an `if (...)` check.

`Character1.GetComponent<move2d>().isGrounded = true;` means "*Set* `move2d.isGrounded` to be true." - ie. it's an assignment, which is one of the valid kinds of statement in C#.

The error message is saying that you can't use an expression (like "5" or "x + 3" or "Is y true?") on its own line as a statement (like "Make x true").

When you get a basic syntax error like this, you should always search our general programming sister site StackOverflow first. They have lots of examples of beginners making exactly this mistake, so you can easily find your solution in the existing answers:
> 1 votes

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


# Question
Title: Does playing sound effects have to be filtering enabled?
In roblox I made a sword that plays the unsheath sound when equipped. This works by using a local script tell a server script to play it when equipped. I made a whole new remote event in replicated storage just for playing this sound effect and nothing else.

Is it really true that simply playing sound effects required filtering enabled?

Is all that extra work of creating the equipted event in replicated storage actually necessary or can I just play it in a non local script in the sword?

# Answer
Yes, they should be. If they aren't, only the client that plays them will be able to hear them. So yes, if you want other players to be able to hear the sword coming out of the sheath, then they have to be filtering enabled.
> 0 votes

---
Tags: roblox
---


# Question
Title: How do you make a shape slide on a JFrame?
I have some simple code that draws a dot in one of 8 places on a screen. There is a higher chance the dot will appear in some locations more than others. The code works and all, but it feels kind of weird that the dot is teleporting from one location to the other. I would like for the dots to slide in a circle that I have drawn, can someone please help me out?

**Here is my code:**

```
  package com.company;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Main extends JPanel {

    private static JFrame frame = new JFrame();
    private static int random = 1;

    public static void main(String[] args) {

        //Time -= 5 every time used
        Runnable number = () -> random = (int) (Math.random() * 100) + 1;
        ScheduledExecutorService executor1 = Executors.newScheduledThreadPool(1);
        executor1.scheduleWithFixedDelay(number, 0, 1, TimeUnit.SECONDS);
        frame.getContentPane().add(new Main());
        frame.setSize(2000, 1080);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.WHITE);
        frame.setVisible(true);
        frame.setResizable(true);
    }

    public void paint(Graphics g2) {
        Graphics2D g = (Graphics2D) g2;
        if (random > 0 && random <= 15) {
            g.fillOval(920, 3, 100, 100);

        } else if (random > 15 && random <= 20) {
            g.fillOval(920, 797, 100, 100);

        } else if (random > 20 && random <= 35) {
            g.fillOval(523, 400, 100, 100);

        } else if (random > 35 && random <= 50) {
            g.fillOval(1317, 400, 100, 100);

        } else if (random > 50 && random <= 65) {
            g.fillOval(620, 143, 100, 100);

        } else if (random > 65 && random <= 80) {
            g.fillOval(1220, 143, 100, 100);

        } else if (random > 80 && random <= 90) {
            g.fillOval(620, 657, 100, 100);

        } else if (random > 90 && random <= 100) {
            g.fillOval(1220, 657, 100, 100);
        }
        g.drawOval(570, 50, 800, 800);
        frame.repaint();
    }
}

```

# Answer
> 1 votes
## Your Situation

You have created a `Runnable` that is executed with the freuqency of one/second.

This runnable does nothing else but setting a new value for your `int random` and redraws that value.

## Solution

What you have to do is to change your `Runnable` so that is does the animation for you. (I would suggest to make a method that creates the `Runnable` for you.) Your new `Runnable` should split the time for the animation into proper pieces and draw each of it.

Let's do some math first:

> time for animation: 1s
> framerate: 25 f/s
> frameDuration: 40ms

using this result you create a new `Runnable`:

```
public static Runnable createAnimationRunnable(){
    return () -> {

        setTarget();//see text below
        for(int i = 0; i < 25; i++){ //25 frames within that second duration runnable

            double percentage = i/25d; //percentage - alias progress
            drawAnimation(percentage);
            try {
                Thread.sleep(40); //frame duration
            } catch (InterruptedException e) {
                //please handle properly!!!
            }
        }

    };
}

```

this `Runnable` will now call `static void drawAnimation(double percentage){}` 25 time within that one second of runtime.

Now you have to use this drawAnimation to move your spot from one location to the other. To achieve this you have to store the previous location and the target location. I have already inserted the code that creates the data required for that, it's the method `setTarget()` in your Runnable. Note: i strongly advise you to use proper data type as for now i will introduce a `Point` to represent your spot

```
private static Point previous = new Point(0,0);
private static Point target = new Point(0,0);
private static Point animationPoint = new Point(0,0); //see text below

public static void setTarget(){
    previous = target;
    target = new Point(Math.random()*100, Math.random()*100));
}

```

At this point we know where to start the animation and we know where to stop the Animation, we have now already the time slots to draw. what's left is to create the animation steps:

```
static void drawAnimation(double percentage){
    double dx = percentage * (end.x-start.x); //x-way to target, in percent
    double dy = percentage * (end.y-start.y);
    animationPoint = new Point(start.x + dx, start.y + dy); //a small step for a man
    frame.repaint(); //i'll get in hell for this
}

```

When you paint you just have to draw the `Point animationPoint` and you have to no longer to the math during painting - it is already done before drawing.

## Unsolved problems

I am not sure what you understand by draw a *CIRCLE ANIMATION* and hence i displayed a **line animation**. it's up to you to change this animation into the code that does, what you want.

---
Tags: java, swing, jframe
---


# Question
Title: How to clip cut-off using different frustrum than that of original camera? How to cut plane by pyramid shape?
SOURCE : http://amd-dev.wpengine.netdna-cdn.com/wordpress/media/2012/10/Mitchell\_LightShafts.pdf

This process is part of creating light draft effect. And I am suggested to do the described process in order to enhance performance and I really want to do it.

However I am clueless on how I can apply "frustrum perspective matrix" from other camera to my camera perspective to chop off that square plane into shapes that fit into the "frustrum perspective matrix".

I am guessing I need to do this on CPU side first? But that's as far as my wild guess goes

# Answer
For a simple way of doing it, you’ll need two things:

First, you’re looking for the Sutherland-Hodgman Clipping algorithm, or some other type of clipping algorithm. Sutherland-Hodgman is very easy to understand and implement, and it is used in some physics engines for this even today. This will clip your shapes given a clipping volume.

The second thing you’re looking for is some background on projection matrices and how the frustum is formed.

Matrices are used by multiplying them with coordinates to produce a transformed set of points. A typical example would be mapping the vertices of the unit cube to the canonical view frustum. Now treat your new frustum as the clipping object from the first step and viola. A decent way of doing it on the CPU.

There are lots of optimizations you can make as well and different approaches such as taking the 6 faces of a box, and instead of transforming their vertices, use the matrix to transform their homogeneous half-space representation for frustum culling
> 1 votes

---
Tags: mathematics, matrix, frustum, projection-matrix, directxmath
---


# Question
Title: Reducing total file size of multiple Unity games
Our product consists of many small stand-alone games, some made in Unity and some made in other languages. These games can be launched from a hub. The file size of the Unity games is quite large, since each game is being build to work as a stand-alone game. When looking inside the folders, I can see that many of the files, folders and dlls are the same, so I thought that it would be possible to re-use these across all the games to reduce the file size of our installer.

So far I have successfully moved the games' exe and \_Data folders into one folder so they can re-use the MonoBleedingEdge and UnityPlayer.dll, but I was hoping to be able to share even more resources than this. All the games are built using Unity 2019.1 and all of them are using many of the same libraries and dlls.

Does anyone have experience bundling many Unity games like this? Is there some configuration for Unity that will help with allowing shared resources?

# Answer
One option could be to merge all these Unity games into one game with multiple scenes. That way you will only have one copy of the Unity runtime environment and of any shared assets.

When that game is launched, then it does of course need some way to tell which scene the player actually wants to play. One way to do that is to have the hub application start the Unity game executable with different command line arguments. Like `unity_games.exe tetris` to play Tetris or `unity_games.exe pong` to play Pong.

The game itself would then have a start scene which just uses the method `System.Environment.CommandLineArgs()` from the .NET standard library to detect the argument and then switches to the appropriate scene. Unfortunately that method won't be available on every target platform. So please verify that this method actually works on all the platforms you want to target.

Oh, and do **not** just do

```
SceneManager.LoadScene(System.Environment.CommandLineArgs()[0])

```

Your players might figure out that this allows them to go directly into scenes they aren't supposed to reach directly. Use a switch-statement instead which maps known game names to scenes:

```
switch (System.Environment.CommandLineArgs()[0]) {
    "pong":
        SceneManager.LoadScene("pong_titlescreen");
        break;
    "tetris":
        SceneManager.LoadScene("tetris");
        break;
    "fifa20":
        SceneManager.LoadScene("fifa19");
        break;
    default:
         Debug.LogError("unknown game: " + System.Environment.CommandLineArgs()[0]);
}

```
> 2 votes

---
Tags: unity, build-process
---


# Question
Title: Need help with making number system for idle game
So, I want to create a new game. I have problems with how to store large numbers in the game and how to output them. I have written a small pseudo code that contains everything I need to play the game (Did I forget anything?).

```
# represent  our number
struct BigNumber {
    double base; # (or mantissa)
    double exponent;
}

# create new number
function NewBigNumber(double b, double exp) {
    return BigNumber{
        base = b;
        exponent = exp;
    }
}

# now if we have to BigNumbers we want add operation (+)
# and other operations (-), (*), (/)
# +
function adding(BigNumber n, BigNumber m){
    # if numbers have same exponent part
    if (n.exponent = m.exponent) {
        # adding base here
        double new_base = n.base + m.base;

        #create new BigNumber with new base
        return NewBigNumber(new_base, n.exponent);

    } else {
        #?????????
    }
}

# -
function subtraction(BigNumber n, BigNumber m){

}

# *
function multiplication(BigNumber n, BigNumber m){

}

# /
function division(BigNumber n, BigNumber m){

}

```

As you can see, I will use **Scientific notation**

I have a problem with the addition operation (and other), what if the exponent part of numbers are different?

Next I have this code.

```
# If we have achievement systems
# we need function equals of two numbers
function equals(BigNumber n, BigNumber m){
    if (n.base = m.base && n.exponent = m.exponent){
        return True;
    } else {
         return false;
    }
}

```

And finally, I need the function to output numbers nicely.

```
suffices = [
    'K', 'M', 'B', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No', 'Dc', 'Ud',
    'Dd', 'Td', 'Qad', 'Qid', 'Sxd', 'Spd', 'Od', 'Nd', 'V', 'Uv', 'Dv',
    'Tv', 'Qav', 'Qiv', 'Sxv', 'Spv', 'Ov', 'Nv', 'Tt'
];
# now we need "good view numbers" function
# for exapmle
# 1000 - 1000
# 1000000 - 1Million
function(BigNumber n) {
    #????????
}

```

# Answer
This code appears to be JavaScript. Since ECMA-262, JavaScript has a native BigInt class.

* It works with all the basic math operators `+`, `-`, `*`, `/`, `%` and `**` (division will round to 0).
* It also works with the comparison operators like `==`, `>`, `<=` etc.
* It can be expressed as a literal by using the suffix `n`. (`const ONE_NONILLION = 1000000000000000000000000000000n`).

Using this class will likely give you better performance with a much smaller code footprint and most importantly less bugs than inventing your own.

Unfortunately this class is not yet supported on Edge and Safari. If you want to support these browsers, then you will need a polyfill.
> 1 votes

---
Tags: game-design, architecture, game-mechanics
---


title: Wrong Second position of LineRenderer

text:
# Question
Title: Wrong Second position of LineRenderer
I'm drawing some kind of bullet trace effect with LineRenderer in my 2D Game Project with Unity. At some position, setting position of LineRender result weird:

In the above screenshot, you can see two types of lines are exists. Pure red lines are result of Debug.DrawRay which is only renders in Scene view, not actual game play, and another lines which has yellow to red gradient are actual line renders I want to draw.

I used exactly same code for rendering both two, Debug.DrawRay() and LineRenderer.SetPosition(), but as you can see only DrawRay works as I expected and LineRenderers are cutted and pointing wrong direction.

Here's the code I'm trying:

```
void Fire() {
    Vector3 shootDirection = m_ShootPoint.right;

    RaycastHit2D hit = Physics2D.Raycast(m_ShootPoint.position, shootDirection, m_Range);
    Debug.DrawRay(m_ShootPoint.position, shootDirection.normalized * m_Range, Color.red, 20);

    // On Hit, set end position where it hits
    if (hit) {
        CreateBulletTrace(m_ShootPoint.position, hit.point);
    }
    // Otherwise, render straight until it's range
    else {
        CreateBulletTrace(m_ShootPoint.position, shootDirection.normalized * m_Range);
    }
}

void CreateBulletTrace(Vector3 startPos, Vector3 endPos) {
    GameObject bulletTraceObj = Instantiate(m_BulletTraceLineRendererPrefab);
    LineRenderer bulletTraceLineRenderer = bulletTraceObj.GetComponent<LineRenderer>();
    bulletTraceLineRenderer.useWorldSpace = true;

    bulletTraceLineRenderer.SetPosition(0, startPos);
    bulletTraceLineRenderer.SetPosition(1, endPos);

    // Destroy(bulletTraceObj, 0.1f);
}

```

Note that LineRenderer checked use world space to true. What am I missing?

Using Unity 2019.1.0f2.

# Answer
The second argument in DrawRay is an offset.

The argument you provide to a LineRenderer is a position.

`shootDirection.normailized * m_Range` is an offset from zero — you want to add your start point to get an absolute position.
> 2 votes

---
Tags: unity, rendering
---


# Question
Title: How do I get the Oculus Rift's position and rotation?
I'm looking for the functions to get the position and rotation data of the rift headset itself in Unity.

I have the Oculus integration SDK installed and want to avoid using any pre-fabs.

# Answer
> 2 votes
you have an **OVRCameraRig** prefab in the scene then you can get the **centerEyeAnchor** transform as follows:

```
public OVRCameraRig cameraRig;

Vector3 headsetPosition = cameraRig.centerEyeAnchor.position;
Quaternion headsetRotation = cameraRig.centerEyeAnchor.rotation;

```

This holds the current position and rotation of the headset, and it always coincides with the average of the left and right eye poses.

If you don't want to use the default OVRCameraRig prefab you are gonna have to manually assign that property to the proper camera.

I hope this will help you!!

---
Tags: unity, virtual-reality, oculus
---


# Question
Title: How can I make a solitaire game that can be solved?
It was not difficult to mix the cards and make them in solitaire format.

But sometimes there are games that can't be solved. (For example in 3 turn mode)

How can I make sure that the game can be solved?

# Answer
Backtracking.

Start with a solved game. Then perform random valid moves in reverse until the game is in the initial state.

This usually works with any puzzle game.
> 10 votes

---
Tags: procedural-generation, card-game
---


# Question
Title: THREE.JS - How to know the shortest rotation direction an object must do to look at other?
I am trying to understand a way in THREE.JS (and the mathematical foundation) to get the direction an object should rotate to lookAt other but without actually rotate it. I've tried to use `lookAt` but that rotates the object completely.

I want to apply a small custom parameterized rotation on that direction. So I don't want all the rotation, just the direction of that shortest to look at rotation.

So, basically I have 2 object positions and I want the shortest rotation direction of one of them so that one looks at the second object position, independently of the second object rotation. And limit the axis so it works on a over the top 2d game setting (although the graphics are 3d)..

The rotation must be around Z for example.

And relative to the current object heading as this will be computed on each game loop iteration depending on the player position.

This is intended for a game where enemies try to follow the player but turn slow to look at him.

Thank you in advance

# Answer
> 1 votes
Solved using this:

```

// player world position
const vPlayerPositionRelativeToWorld = new THREE.Vector3().copy(player.transform.position);

// player position relative to enemy transform - includes rotation of the transform
const vPlayerPositionRelativeToLocalEnemyPositionAndRotation = enemy.transform.worldToLocal(vPlayerPositionRelativeToWorld);
vPlayerPositionRelativeToLocalEnemyPositionAndRotation.normalize();

// get angle to rotate
const maxRotateValue = .05;
const rotationToLookAtPlayer = Math.asin(vPlayerPositionRelativeToLocalEnemyPositionAndRotation.x);
const rotateAbsoluteValue = Math.min(Math.abs(rotationToLookAtPlayer), maxRotateValue);
const orientedRotationValue =  -Math.sign(rotationToLookAtPlayer) * rotateAbsoluteValue

enemy.transform.rotateZ( orientedRotationValue );

```

Not sure if there is a more efficient method but it works for this case.

---
Tags: mathematics, matrix, linear-algebra, three.js
---


# Question
Title: Godot 3.1: procedurally generating TileMap with AutoTiles
I'm making a start on a 2d top-down game in Godot, using a TileMap and OpenSimplex Noise to generate the terrain. It works pretty well, creating decent contiguous regions of different types of terrain. So far I have been using a simple "one tile per terrain type" but now want to extend it to use AutoTiles, so that I can have it look better, however I don't know how to get the procedural generation to use more than just the first tile in the AutoTile set.

I have got it so that I can hand-draw the AutoTiles in the editor and they work, but is there a way to get a programmatically-set tile to obey the AutoTile layout? Or do I have to check all 8 surrounding tiles for every instance where this type of tile appears and set to the appropriate tile index? Surely there is a better way...?

Thanks in advance. :-)

# Answer
> 4 votes
This can be achieved with the update\_bitmask\_region() function in the `TileMap` class. Calling it with no parameters will update the whole tilemap, which is probably what you want.

# Answer
> 2 votes
There are roughly two ways of doing autotiling - either the autotiles are counted as separate tiles and are then edited/inserted "offline", with the game rendering the required pieces straight off the map, or the tiles are stored without the information and it is only calculated and stored in memory (think how Minecraft fences work - the level files only store the fact that a block is a fence, not what is connected to).

The editor likely does the autotiling which is then rendered as is in the actual game.

So you either want your autotiling happen at generation, or afterwards when the map is loaded.

It is a lot simpler for the generator to place the "dumb" tiles - that way it is not concerned about all these details, not to mention if it screws up the generation (that happens a lot) it won't look horribly out of place.

Here's more or less the step-by-step approach:

First, you generate/load/otherwise create your map with "dumb" tiles. In addition, each tile has an extra field associated with it (whether it is an extra field in a Tile struct or just an extra \[x,y\] array is an implementation detail and is not important). Call this field the AutoTile code. It needs at most a byte of space, technically fitting into 48 distinct values.

Afterwards, once you need to render the map, you iterate over every tile and check each of its 8 neigbours whether it should "link up" to that tile or not. It might only link up to itself (wall tiles connecting to other walls) or to any tile your game considers "solid" (like fences in Minecraft).

This is the algorithm I use in a project of mine, while it is specific to my platform/framework (C#, Windows, MonoGame), it should give the general idea:

```
public void DoAutoTile(int X,int Y)
        {
            //bounds checking
            if (X >= this.Width || X < 0 || Y >= this.Height || Y < 0)
                return;
                int code = 0;

            int left, right, top, bottom, tl, tr, bl, br;
            left = GetWall(X - 1, Y);
            right = GetWall(X + 1, Y);
            top = GetWall(X, Y-1);
            bottom = GetWall(X,Y+1);

            tl=GetWall(X-1,Y-1);
            tr = GetWall(X + 1, Y-1);
            bl = GetWall(X - 1, Y+1);
            br = GetWall(X + 1, Y+1);
        //some cases look identical, ignore these
            if (top == 0)
            {
                tl = 0; tr = 0;
            }
            if (bottom == 0)
            {
                bl = 0; br = 0;
            }
            if (right == 0)
            {
                br = 0; tr = 0;
            }
            if (left == 0)
            {
                tl = 0; bl = 0;
            }

            code = tl + top * 2 + tr * 4 + left *8 + right * 16 + bl * 32 + bottom * 64 + br * 128;
            //not part of algorithm
            Tiles[X, Y].WallAutoTileCode = code;

        }

```

In my case the GetWall function returns a 0 or a 1 answering the question whether the tile at that spot is a "wall" (solid).

The AutoTileCode now uniquely refers to a sprite in a spritesheet corresponding to how the tile is supposed to look like.

For the purpose of this being a self-contained answer, I will also include the Dictionary (associative array) that maps the AutoTileCodes to offsets into a spritesheet (before multiplication by whatever actual sprite width is in pixels), the spritesheet being 10 sprites wide and 5 sprites tall (nearly optimal packing for 48 states while still being "readable").

```
public static Dictionary<int, Vector2> BlobIndices=new Dictionary<int, Vector2>()
        {
            #region BlobMappings
            {0, new Vector2(5,1)},
            {2, new Vector2(0,2)},
            {8, new Vector2(3,3)},
            {10, new Vector2(6,2)},
            {11, new Vector2(3,2)},
            {16, new Vector2(1,3)},
            {18, new Vector2(4,2)},
            {22, new Vector2(1,2)},
            {24, new Vector2(2,3)},
            {26, new Vector2(5,2)},
            {27, new Vector2(6,4)},
            {30, new Vector2(5,4)},
            {31, new Vector2(2,2)},
            {64, new Vector2(0,0)},
            {66, new Vector2(0,1)},
            {72, new Vector2(6,0)},
            {74, new Vector2(6,1)},
            {75, new Vector2(5,3)},
            {80, new Vector2(4,0)},
            {82, new Vector2(4,1)},
            {86, new Vector2(6,3)},
            {88, new Vector2(5,0)},
            {90, new Vector2(8,1)},
            {91, new Vector2(8,3)},
            {94, new Vector2(9,3)},
            {95, new Vector2(8,0)},
            {104, new Vector2(3,0)},
            {106, new Vector2(7,4)},
            {107, new Vector2(3,1)},
            {120, new Vector2(4,3)},
            {122, new Vector2(8,4)},
            {123, new Vector2(7,1)},
            {126, new Vector2(3,4)},
            {127, new Vector2(7,0)},
            {208, new Vector2(1,0)},
            {210, new Vector2(4,4)},
            {214, new Vector2(1,1)},
            {216, new Vector2(7,3)},
            {218, new Vector2(9,4)},
            {219, new Vector2(2,4)},
            {222, new Vector2(9,1)},
            {223, new Vector2(9,0)},
            {248, new Vector2(2,0)},
            {250, new Vector2(8,2)},
            {251, new Vector2(7,2)},
            {254, new Vector2(9,2)},
            {255, new Vector2(2,1)}
#endregion
        };

```

A simple Search and Replace is likely sufficient to convert this to whatever data types your framework would prefer.

These values map to a spritesheet with this layout:

(feel free to use this image as a placeholder or to check implementation or even in your finished game, it's very simplistic and zero effort went into it).

The last step is to tell the renderer to use this data when drawing the tiles - have it refer to the tile's AutoTileCode, consult BlobIndices (the Dictionary from earlier) for the corresponding X,Y offset, multiply to get actual pixel values if needed (or straight UVs or whatever), perhaps some other offsets if you combine multiple AutoTiles in one sheet, and render the resulting tile.

For example, the value 0 (nothing connected) will correspond to sprite \[5,1\] in the sheet, which is indeed an "isolated" single wall. The value 2 (only the top connected) corresponds to \[0,2\], which indeed looks like a wall connected to something at the top, and so on.

If you want more information on this, check out the articles on "Tile Bitmasking" (not super technically correct, but the name stuck) that got me in the right direction a while ago, and the first one even contains a version of the Dictionary I created, but with numerical indices instead).

How To Use Tile Bitmasking to Autotile Your Level Layouts

Adventures In Bitmasking - Angry Fish Game Studios

This link contains another explanation, and I think that's where the layout I am using came from originally, it also shows the simpler sets when you don't need arbitrary shapes.

Mechanic #166 - PGC: View-Tile Rulesets

This code file on one of my projects contains the autotiling code as well as rendering code, so it can be seen in action:

Map.cs on GitHub

# Answer
> 0 votes
I have the exact same question! The only thing I can find about it is in the docs for the tilemap class:

https://godot.readthedocs.io/en/3.2/classes/class\_tilemap.html

Under the description for set\_tile it reads:

"Optionally, the tile can also be flipped over the X and Y coordinates, transposed, or be given autotile coordinates."

I'm not sure what it means by giving a tile autotile coordinates but maybe it's relevant?

Let me know if you ever figure it out.

---
Tags: procedural-generation, tilemap, godot
---


# Question
Title: Reconstructing Position from Depth - Inverted Y?
I am currently trying to understand the following wierd result. This is basically from deferred shading in monogame/XNA. For Comparison I also write the ViewSpace Position in a Buffer and the ViewSpace Depth in another buffer like so:

```
float4 viewPosition = mul(input.Position, WorldView);
depth = viewPosition.z;

```

(the depth value is sent to a rendertarget with surfaceformat vector2 = 2x32bit float), the position-buffer now looks like so:

(this is basically just a quad with a cube in the middle and some elevation in top left)

What I do now is I calculate the CornerFrustum on the CPU:

```
Vector3 cfrust = Vector3.Zero;
cfrust.Y = camera.FarClip * (float)Math.Tan(camera.FOV * 0.5f);
cfrust.X = cfrust.Y * camera.AspectRatio;
cfrust.Z = camera.FarClip;

```

The Fullscreen-quad is aligned with that frustum in mind:

```
new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1)),
new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1)),
new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0)),
new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0))

```

now in the VS I get the ViewRay / ViewDirection like this

```
output.ViewDirection = float3(-CornerFrustum.x * input.Position.x, CornerFrustum.y * input.Position.y, CornerFrustum.z);

```

in PS I now try to reconstruct the ViewPosition from ViewRay/Depth

```
float3 ViewRay = normalize(input.ViewDirection);
float Depth = tex2D(sampler_depth, input.UV).r;
float3 ViewPosition = Depth * ViewRay;

```

I should now have the ViewPosition of that pixel, right?

I am now converting this back to screen by

```
float4 ScreenPosition = mul(float4(ViewPosition, 1.0),Projection);
float2 ScreenUV = 0.5 * (ScreenPosition.xy / ScreenPosition.w) + float2(0.5,0.5);

```

if I now output that position to the screen I get this:

as the colors suggests, the Y-Axis is inverted? (It's negative now, so the corresponding channel is clamped to 0 in the output, basically inverting the colors)

This gives me trouble now, because as a consequence (this is used in a SSAO shader) the SSAO samples (hemisphere) are moved along the inverted y-axis as well.

I fear I am missing something, because the generated UVs are actually correct. As they sample the correct piece. If I use those "ScreenUV" to sample from the PositionBuffer I do get the correct result (the exact same as the first image). I just cannot understand, why the position is inverted in the y-axis (it's now pointing down instead of up.

# Answer
> 1 votes
There is a coordinate system change between DX and GL since monogame can use either under the hood. This is normally taken care of internally however there are some things that the user must deal with such as passing static or global shader variables. Any thing that monogame cannot know the intended use of, so they fall thru the cracks into the default behavior.

That can result in what is seen in your example.

The positional realignment is as follows and will not be required on the converse platform gl vs dx.

y = GraphicsDevice.Viewport.Height - y;

---
Tags: shaders, monogame, hlsl, ssao
---


# Question
Title: Shaders and Distortion Effect (Monogame)
I am building a top down 2D space shooter game with sandbox elements. I am working on the shield for the spaceship now and am not having luck. I am attempting to make a distortion effect shader, but things are not working right.

I either:

* do not get my spaceship to draw on the screen,
* spaceship draws but no distortion, or
* getting random null reference exceptions with the `effects.Parameters` when setting a value.

Here is my current shader:

```
sampler inputTexture : register(s0);

float2 DisplacementScroll;
float2 displacement;

texture2D distortion;
sampler2D distortionSampler = sampler_state
{
    Texture = <distortion>;
    MagFilter = Point;
};

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 coords: TEXCOORD0) : COLOR0
{
    // Look up the displacement amount.
    displacement = tex2D(distortionSampler, DisplacementScroll + coords / 3);

    // Offset the main texture coordinates.
    coords += displacement * 0.2 - 0.15;

    // Look up into the main texture.
    return tex2D(inputTexture, coords);
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

```

And my C# code:

```
public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private Texture2D battlecruiserTexture2D, fighterTexture2D, normalTexture2D;
        private Effect effect;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.GraphicsProfile = GraphicsProfile.HiDef;
            graphics.PreferredBackBufferWidth = 1920;
            graphics.PreferredBackBufferHeight = 1080;

            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            battlecruiserTexture2D = Content.Load<Texture2D>("Battlecruiser_1");
            fighterTexture2D = Content.Load<Texture2D>("Fighter2-shootSm");
            normalTexture2D = Content.Load<Texture2D>("Normal1");
            effect = Content.Load<Effect>("ShipShader");

            effect.Parameters["distortion"].SetValue(normalTexture2D);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            float timeInSeconds = (float) gameTime.ElapsedGameTime.TotalSeconds;

            // TODO: Add your update logic here
            effect.Parameters["DisplacementScroll"].SetValue(MoveInCircle(gameTime, 0.1f));

            base.Update(gameTime);
        }

        private Vector2 MoveInCircle(GameTime gameTime, float speed)
        {
            double time = gameTime.TotalGameTime.TotalSeconds * speed;

            float x = (float)Math.Cos(time);
            float y = (float)Math.Sin(time);

            return new Vector2(x, y);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, effect:effect);
            spriteBatch.Draw(battlecruiserTexture2D, new Vector2(500, 500), Color.White);
            //spriteBatch.Draw(fighterTexture2D, new Vector2(650, 650), Color.Black * 0.5f);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }

```

For those that have played Terraria, I am essentially looking for a distortion effect and shield effect like the Celestial Pillars.

https://www.youtube.com/watch?v=hL3x33CIf5Y

Go to 30 seconds in to see the shield around the pillar for an example. Terraria is in XNA so I know this would be possible.

Does anyone know why this is not working properly? Also, why I am getting a null reference exception on the following line even though I use the variable in the shader file?

```
effect.Parameters["distortion"].SetValue(normalTexture2D);

```

# Answer
> 1 votes
Just a quick update: With the help of a few people in the MonoGame Discord and MonoGame forums, my issue has been resolved. It appears that you must create a sampler of the texture passed to the shader before creating a sampler for any other textures, and all textures must have a sampler. There is a line used at the top of the main function to use the TextureSampler. If that line is removed, it will also break the shader. You can check out the post here: http://community.monogame.net/t/shader-that-works-in-xna-4-0-is-broken-in-monogame/11896

To prevent issues with the possibility of the link dying, the Shader file changed to:

```
float2 DisplacementScroll;

Texture2D Texture;
sampler TextureSampler
{
    Texture = <Texture>;
};

Texture2D Displacement;
sampler DisplacementSampler
{
    Texture = <Displacement>;
};

struct vsOutput
{
    float4 position : SV_Position;
    float4 color : COLOR0;
    float2 texCoord : TEXCOORD0;
};

float4 main(vsOutput input) : COLOR0
{
    // Comment this line out to break the shader!!!
    float4 v =  tex2D(TextureSampler, input.texCoord);

    // Look up the displacement amount.
    float2 displacement = tex2D(DisplacementSampler, DisplacementScroll + input.texCoord / 3).xy;

    // Offset the main texture coordinates.
    input.texCoord += displacement * 0.2 - 0.15;

    // Look up into the main texture.
    return tex2D(TextureSampler, input.texCoord) * input.color;
}

technique Refraction
{
    pass Pass1
    {
        PixelShader = compile ps_4_0 main();
    }
}

```

# Answer
> 1 votes
Lord need 50 rep to comment. I will answer here even though it is answered. For posterity so others who may come across this question in search of answers may find a decent set of examples.

With a link to a post on the monogame site with multiple refraction shaders i made.

http://community.monogame.net/t/2d-refraction-shader-example-for-spritebatch/11902

---
Tags: c#, monogame, hlsl
---


# Question
Title: Monogame/XNA - How do you resize a Texture2D and then scale it?
Problem: It seems like the Draw() call allows us to use either Destination Rectangle for resizing (5of8) or Scale (6of8/7of8) but not both.

Purpose: I would like to resize a button from 567x634 to 400x480 and then using scale to further reduce it by 0.8 to 320x400.

# Answer
You can make a RenderTarget of any width and height. You can optional set up that render target to be persistant by sending in PreserveContents as the final parameter when you create the render target. You can set the render target to the GraphicsDevice in the Game1.Draw method. You can then draw your current texture to that render target with Spritebatch.Draw

SpriteBatch.Draw has a parameter that you will see by the name of 'destination'.

That rectangle should have the same size as the render target its location should be 0,0.

Once drawn to the desired new size you then have the option to use the render target as if it were a texture.

This means you can call save on it, in order to write it to file. You can use it as a texture and draw it to the back buffer. You can draw it with SpriteBatch.Draw using the scale parameter or by destination again.

If you made your render target persistent you can keep it around. However this would be frowned upon by many as well as re-scaling and not pre-scaling the texture before loading. In addition this may not be supported on older hardware and on new hardware may incur a performance penalty. However i digress.

I believe the above answers to this part of the question generally.

> Purpose: I would like to resize a button from 567x634 to 400x480 and then using scale to further reduce it

While the below is not exactly a clear question, i surmise you are asking why?

> Problem: It seems like the Draw() call allows us to use either Destination Rectangle for resizing (5of8) or Scale (6of8/7of8) but not both.

The act of setting a destination Rectangle means that scaling is implicit. E.G. i have a texture of width and height 100,100 and i set it to a destination rectangle on screen of new Rectangle(0,0,80,80); That is equivillent to performing a scaling of .8f,.8f on the width and height of the texture. i.e. 100 \*.8 = 80.

Therefor it would be first of all confusing, additionally it would be open to alternate interpretations to the operational precedence of what scaling operation happens in what order, finally it would be pointless to have both the destination and scaling parameter in the same overload.
> 1 votes

---
Tags: xna, monogame
---


# Question
Title: How to avoid units with different destinations blocking each other in corridors?
I'm making a roguelike in which enemies wander around the map until they're detected by the player. They each have random destinations, so sometimes their destinations conflict and they block each other in corridors.

Enemies can't go through each other

Is there any approach that can avoid this issue? Only idea I have right now would be to detect which ones are at the end of the "trafic block" and made them change destination until their path is free... But maybe there's a better design solution for this problem?

# Answer
Just have the units consider each other an obstacle with regards to whatever pathfinding algorithm you use. As it is a roguelike and not a real-time game, the performance hit is barely noticeable. As units will be processed one by one, they will simply "see" a "closed" corridor and decide to go elsewhere.
> 1 votes

# Answer
The solution I ended up choosing is a simplistic one:

* If monsters get blocked at any point, they try to find a free spot around them
* Then they set that as their new destination, overriding the previous one
* Then when they reach that point, the game will choose a new destination as usual, so eventually they will just go somewhere else

It ends up making it look like monsters wander around, and when roads are blocked they just go somewhere else, which is what I wanted.

Note that this doesn't happen when they have a specific objective like chasing the player, but only when they're roaming.
> 0 votes

---
Tags: ai, roguelikes
---


title: Collider null using LayerMask

text:
# Question
Title: Collider null using LayerMask
I am trying to implement jumping in my game. I am casting a ray to know if the player is grounded, and using a Layermask to make it only react with the floor. The code:

```
groundLayer = LayerMask.NameToLayer("Ground");
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 1.0f, groundLayer.value);
Debug.DrawRay(transform.position, Vector2.down * 1.0f, Color.green);
if (hit.collider != null)
    {
        print(collider.name);
        bounds = collider.bounds;

        if (distance < 0.2f)
        {
            grounded = true;
            return true;
        }
        else
        {
            print(collider.name);
            grounded = false;
            return false;
        }
    }
    else
    {
        print("Collider null");
        return false;
    }

```

I am receiving collider null always. What am I doing wrong?

EDIT:

In case it helps, this is a screenshot of my Unity editor:

# Answer
The problem is in line:

```
groundLayer = LayerMask.NameToLayer("Ground");

```

You need to use a bit mask which turns on only the bit associated with that layer:

```
groundLayer = 1 << LayerMask.NameToLayer("Ground");

```

Also, if you want to allow more than one layers, you can do so:

```
groundLayer = (1 << LayerMask.NameToLayer("Ground")) | (1 << LayerMask.NameToLayer("other layer"));

```
> 0 votes

---
Tags: unity, raycasting
---


# Question
Title: Monogame pipeline couldn't load Xamarin.Mac
I Try to use my ContentProcessor, which I wrote on a Linux machine, on a Mac but it crashes with an unexpected failure.

The Pipeline Tool gives me the following

It seems to be a problem with the FontDescription class. In the constructor of my FontDescription class, I create a file if it does not exist. The File is never created, so I assume that the line is never called and the problem is in the base constructor. Since I couldn't find anyone else with this problem I must assume that I am doing something wrong.

My classes look as follows:

```
using System;
using System.IO;
using System.Xml;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;

namespace CH.LocalisationPipeline
{
    [ContentProcessor(DisplayName = "LocalizedFontProcessor of CH")]
    public class LocalisedFontProcessor : ContentProcessor<LocalisedFontDescription, SpriteFontContent>
    {
        public override SpriteFontContent Process(LocalisedFontDescription input, ContentProcessorContext context)
        {
            SpriteFontContent returnValue = null;
            if (!File.Exists(@"outputPipeLine.txt"))
            {
                File.Create(@"outputPipeLine.txt");
            }
            else
            {
                File.AppendAllText(@"outputPipeLine.txt", Environment.NewLine);
            }
            try
            {
                GetLocalisedResx(input, context);
                File.AppendAllText(@"outputPipeLine.txt", "Input is null? "+(input==null).ToString()+ Environment.NewLine);
                File.AppendAllText(@"outputPipeLine.txt", " " + Environment.NewLine+"INPUT:   " + input + Environment.NewLine + Environment.NewLine);
                returnValue = context.Convert<FontDescription, SpriteFontContent>(input, "FontDescriptionProcessor");
            }
            catch (Exception ex)
            {
                File.AppendAllText(@"outputPipeLine.txt", ex.Message+" "+ex.StackTrace+ Environment.NewLine);
                throw;
            }

            return returnValue;
        }

        private static void GetLocalisedResx(LocalisedFontDescription input, ContentProcessorContext context)
        {
            foreach (String resourceFile in input.ResourceFiles)
            {
                String absolutPath = Path.GetFullPath(resourceFile);
                if (File.Exists(absolutPath))
                {
                    ReadResource(input, absolutPath);
                    context.AddDependency(absolutPath);
                }
                else
                {
                    File.AppendAllText(@"outputPipeLine.txt", "File doesnt exists "+absolutPath+ Environment.NewLine);
                }
            }
            foreach (String stringsXml in input.StringsXML)
            {
                String absolutPath = Path.GetFullPath(stringsXml);
                if (File.Exists(absolutPath))
                {
                    ReadStrings(input, absolutPath);
                    context.AddDependency(absolutPath);
                }
                else
                {
                    File.AppendAllText(@"outputPipeLine.txt", "File doesnt exists " + absolutPath+ Environment.NewLine);
                }
            }
        }

        private static void ReadResource(LocalisedFontDescription input, String absolutPath)
        {
            input.Characters.Add('a');
            return;

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(absolutPath);

            foreach (XmlNode xmlNode in xmlDocument.SelectNodes("root/data/value"))
            {
                String resourceString = xmlNode.InnerText;
                foreach (char usedCharacter in resourceString)
                {
                    input.Characters.Add(usedCharacter);
                    File.AppendAllText(@"outputPipeLine.txt", usedCharacter + " ");
                }
            }
            File.AppendAllText(@"outputPipeLine.txt", Environment.NewLine);
        }

        private static void ReadStrings(LocalisedFontDescription input, String absolutPath)
        {
            input.Characters.Add('a');
            return;

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(absolutPath);

            foreach (XmlNode xmlNode in xmlDocument.SelectNodes("resources/string"))
            {
                String resourceString = xmlNode.InnerText;
                foreach (char usedCharacter in resourceString)
                {
                    input.Characters.Add(usedCharacter);
                    File.AppendAllText(@"outputPipeLine.txt", usedCharacter+" ");
                }
            }
            File.AppendAllText(@"outputPipeLine.txt", Environment.NewLine);
        }
    }
}

```

and

```
 using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;

namespace CH.LocalisationPipeline
{
    public class LocalisedFontDescription : FontDescription
    {

        public LocalisedFontDescription() : base("Arial",14,1)
        {
            if (!File.Exists(@"outputPipeLine.txt"))
            {
                File.Create(@"outputPipeLine.txt");
            }
        }

        [ContentSerializer(Optional=true, CollectionItemName="Resx")]
        public List<String> ResourceFiles
        {
            get;
            private set;
        }

        [ContentSerializer(Optional = true, CollectionItemName = "xml")]
        public List<String> StringsXML
        {
            get
            {
                List<String> returnValue = new List<string>();
                try
                {
                    String cwd = System.IO.Directory.GetCurrentDirectory();
                    var workingDir = new System.IO.DirectoryInfo(cwd);
                    var resourcesDir = System.IO.Path.Combine(workingDir.Parent.FullName, "Resources");
                    if (!System.IO.Directory.Exists(resourcesDir))
                    {
                        return returnValue;
                    }

                    var resources = new System.IO.DirectoryInfo(resourcesDir);
                    foreach (var subDir in resources.GetDirectories())
                    {
                        if (subDir.Name.StartsWith("Values"))
                        {
                            foreach (var item in subDir.GetFiles())
                            {
                                if (item.Name.StartsWith("Strings"))
                                {
                                    returnValue.Add(item.FullName);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    File.AppendAllText(@"outputPipeLine.txt", ex.Message + " " + ex.StackTrace + Environment.NewLine);
                    throw;
                }
                return returnValue;
            }
            private set
            {
                ;
            }
        }

    }
}

```

From Rider and Visual Studio2019 I get the following message

LabelText.spritefont: \[\] Importer 'FontDescriptionImporter' had unexpected failure!

the spritefont is this

```
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="CH.LocalisationPipeline.LocalisedFontDescription">

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Fipps</FontName>

    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    <Size>10</Size>

    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    <Spacing>0</Spacing>

    <!--
    UseKerning controls the layout of the font. If this value is true, kerning information
    will be used when placing characters.
    -->
    <UseKerning>true</UseKerning>

    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    <Style>Regular</Style>

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->

    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    -->
    <CharacterRegions>
      <CharacterRegion>
        <Start> </Start>
        <End>~</End>
      </CharacterRegion>
    </CharacterRegions>

    <ResourceFiles>
      <Resx>../Properties/Resources.resx</Resx>
      <Resx>../Properties/Resources.de-DE.resx</Resx>
    </ResourceFiles>
  </Asset>
</XnaContent>

```

How can I resolve this issue? I tried it with MonoGame 3.6 and 3.7.1, with both I wasn't able to process my files. I tried it with a simple character 'a' to be sure that it isn't a problem of my files but the files were read correctly.

# Answer
At this time and with that error ... you should post this as a issue on github for monogame which is probably the correct place and maybe the only place to get attention from someone capable of giving a answer to this question.

https://github.com/MonoGame/MonoGame/issues Follow the instructions on the issue submission, if possible make a simplified example to go along with the issue. There are lots of people contributing and lots of work is being done all the time but no one gets paid to create monogame it is completely open source. In many ways it still isn't quite up to par with xna and in many ways it has completely surpassed it.

I would post this as a comment as it is not a true answer. However i am denied that option due to lack of reputation. This is ironic as one would think comments would be for people who open new accounts, not answers.

Regardless i believe this is the correct answer atm. Beyond a useless short obvious answer that will be of no real help.
> 2 votes

---
Tags: c#, monogame, xna-content-pipeline, macos
---