# Question
Title: Thin lines appear differently even though they are the same height
I have an issue that is driving me crazy. All these lines are 2 in height, but when moving around the screen they change thickness. As you can see the top line is thinner.

What can be done to make sure thin lines always keep the same height/width?

Canvas settings:

EDIT: This is not unique to thin lines, basically due to scaling any element can be the same height/width but appear differently, but Im assuming this can be fixed since several games have pixel perfect UI.

# Answer
You can draw lines with a height of exactly 2 pixels by using a **Canvas** with *Constant Pixel Size*.

* Create an **Image** UI object in the Hierarchy
* Select the **Canvas** parent object
    + In the `Canvas` Component:
        - Set Render Mode to *Screen Space - Overlay*
        - Enable the Pixel Perfect tickbox
    + In the `Canvas Scaler` Component:
        - Set UI Scale Mode to *Constant Pixel Size*

* Select the **Image** child object
    + In the `Rect Transform` Component:
        - Change the Height value to `2`
        - Change all other settings according to your needs
    + In the `Image` Component:
        - Set the Source Image to *None*
        - Set the Color for the horizontal bar to render
        - Disable the Raycast Target tickbox

The result is a horizontal line with a given height and colour (width can be defined as a value or adjusted by using anchors), and its size never glitches when moved around the screen.

On the other hand, you are working with explicit pixel dimensions rather than a reference screen and autoscaling; thus, different screen sizes may result in the same UI element having a different ratio with respect to other elements.
> 1 votes

# Answer
The issue, as other folks have pointed out, is that Unity is doing ~the best it can with the information it has. Because the reference size of your UI and the actual size of the screen are different, Unity must either squish or expand lines of pixels to make them fit. It's functionally impossible to guarantee your reference resolution is always a clean multiple of the screen resolution because people have essentially every screen resolution imaginable and you gotta pick one reference resolution to author your game in (unless you have a LOT of time on your hands ;) So, if there's no clean scaling factor, Unity must either anti-alias (which makes things blurry; generally bad for UI) or make some pixel lines thicker and some thinner (the problem outlined in the original post).

All that said, I think there *is* a better answer; we just need to be able to express the intent. I think what you actually want here is two things:

1. To have all the lines *agree* on how thick they should be
2. To be able to assert a minimum size, so thin lines never vanish

It turns out, achieving both of those things isn't that hard. So, for instance, we can go from this (note that those lines are the same 'width' in my reference resolution, but I got unlucky with their scaling):

to this (if I just say 'be the same size')

to this (if I say 'be the same size and never less than 4 pixels width')

It requires adding a component to your object and telling it what things should be the same, with this interface:

Essentially, if you just check the 'control XX' button, it will ensure that if they were the same size in your reference resolution, they'll be the same size on screen. If you also give a \> 0 'min XX', then it will further enforce that the on screen size is never less than that - which can help prevent your lines disappearing.

Here is the code for the thing. Note that I'm assuming you have a pixel perfect camera (probably the right choice for UI). I'm doing my testing in a Screen Space - Overlay render mode; I suspect it will work fine for Screen Space - Camera too. And, of course, I've got a Canvas Scaler set to Scale With Screen Size... which is sorta the whole point of the question ;)

```
public class PixelSizeCorrector : MonoBehaviour
{
    // For reference: UiManager's properties are:
    // public int ReferenceWidth => (int)(this.Canvas.GetComponent<CanvasScaler>().referenceResolution.x);
    // public float ScaledWidth => this.Canvas.pixelRect.width;
    // NOTE: I'm assuming your scaling is controlled by width here; this is a setting on the CanvasScaler... if you're using something else, you might need to calc this differently.
    // public float ScaledToReferenceMultiplier => this.ReferenceWidth / this.ScaledWidth;

    public bool ControlWidth;
    public bool ControlHeight;
    public int MinWidth;
    public int MinHeight;

    protected override void OnEnabling()
    {
        base.OnEnabling();

        var rectTrans = this.GetComponent<RectTransform>();
        if (this.ControlWidth)
        {
            this.RationalizeScaling(rectTrans, rectTrans.rect.width, this.MinWidth, RectTransform.Axis.Horizontal, "Width");
        }

        if (this.ControlHeight)
        {
            this.RationalizeScaling(rectTrans, rectTrans.rect.height, this.MinHeight, RectTransform.Axis.Vertical, "Height");
        }
    }

    private void RationalizeScaling(RectTransform rectTrans, float referenceDimension, float minInPixels, RectTransform.Axis axisName, string dimensionName)
    {
        // First determine how many pixels we're actually going to be
        var scaledDimension = referenceDimension * UiManager.Instance.ReferenceToScaledMultiplier;

        // Now determine our target (it's either a consistent rounding or, if a min was requested and we're below it, that min)
        float targetScaledDimension = Mathf.RoundToInt(scaledDimension);
        if (minInPixels > 0 && targetScaledDimension < minInPixels) targetScaledDimension = minInPixels;
        // Backsolve for what the original reference dimension needs to be to give us the targetScaledDimension
        var targetReferenceDimension = targetScaledDimension * UiManager.Instance.ScaledToReferenceMultiplier;

        rectTrans.SetSizeWithCurrentAnchors(axisName, targetReferenceDimension);

        //Logger.ErrorLog($"{dimensionName} -> Reference: {referenceDimension}, Scaled: {scaledDimension}, targetScaled: {targetScaledDimension}, targetRef: {targetReferenceDimension}, refToScaledMult: {UiManager.Instance.ReferenceToScaledMultiplier}");
    }
}

```

Do keep in mind that if something else (like a Layout Group) is controlling the dimensions of your object, it will likely overwrite what this script is doing. So, you might need to hook this up to control whatever is controlling the dimension (like a LayoutElement). If there's any interest, I'm probably going to do that myself and am happy to share.

Hope this helps folks who are struggling with this issue too!
> 3 votes

# Answer
It seems that the root of the problem is not in Unity or any other rendering system, but in the fact that the image on the monitors is still made from pixels. Therefore, if you don't create a user interface for a specific device with a constant resolution you won't be able to guarantee 100% correct representation of the image on the display with a different resolution (except for the cases when such a resolution is always greater than the original one and its multiplier is always a whole number).

Just imagine you have 2x2 pixels monitor (or Canvas in your case) and 1 pixel image on it at (0, 0). What happens if you try to display the same canvas on a 3x3 monitor? The canvas will be scaled by 1.5 and the image will occupy 1.5 pixels. This is exactly where visual artifacts begin to appear. The rendering system will try to make some approximation but it is technically impossible to display anything on half a pixel without loss of quality (or at least I can't imagine how it could be made).

My point here is that visual artifacts are not some kind of error, quite the contrary they are to somehow compensate for the inability to reliably display the image on different resolutions. Hence it is impossible to completely get rid of the artifacts, but you can try to make them less noticeable.

On different resolutions, the same lines may correspond more or less exactly to an integer number of pixels, so they may look like they have different heights or brightness despite the system's efforts to hide this.

For example, this image has 1px white lines and 2px colored lines:

in a different resolution it can be displayed like this (I intentionally scaled it to make the artifacts more noticeable):

Approximation/anti-aliasing algorithms hide the imperfection of displays quite well when it comes to large objects, but in your case they will hardly be able to make it unnoticeable to the eye when the lines are only a couple of pixels thick, are located strictly horizontally (collinear to the display pixels), and are deliberately made contrasting to the background - all this taken together makes it much easier for the eye to compare them and to notice any difference. Therefore, I don't think that you will be able to achieve an acceptable result using such approach (which is applied by default), unless you want to avoid a design with very thin lines.

Another option could be (as suggested in the @liggiorgio answer) using the Pixel Perfect option along with Constant Pixel Size. This can give a good result if you are ready for some compromises, for example, to give up scaling and smooth movement (if you move the element by 0.5 pixels you will get height artifacts back), but for the UI it could be a decent solution since the requirements for animations in the UI are not so high especially if it's just kind of a dialog moving/dragging. Still, I can't see any point in using images to create lines (as @liggiorgio suggests) except for keeping them aligned with pixels when moving, but this may also make them out of sync with other elements of the background image which would look like jittering. Instead, you can move UI elements by whole pixels using `RectTransform` without any need to resort to such tricks.

What about scaling - you can customize `CanvasScaler` so that it will scale only by whole numbers. IOW your UI can be scaled (without getting artifacts) only when the ratio of a new resolution to the reference one gives an integer number. In your case (if you are only interested in horizontal lines) you can only take into account the height values ratio. You can find an example of `CanvasScaler` customization here and adapt it to your needs.

---

So, at the end once again: I am not an expert in this matter and I have not even had to solve a similar problem for the UI, so all my reasoning is mostly theoretical.
> 0 votes

---
Tags: unity, gui, unity-ui, scale
---


title: Is DirectX 12 or lower just an API?

text:
# Question
Title: Is DirectX 12 or lower just an API?
I am programming a game using DirectX 12. Shall it support all GPUs? Or just newer GPUs? What about the version of the Windows OS supported?

What changes when a new DirectX version comes?

# Answer
> Shall it support all GPUs? Or just newer GPUs? What about the version of the Windows OS supported?

From Nvidia, DirectX12 supports all GPUs using the **Ampere** (RTX 3000 Series), **Turing** (RTX 2000 Series), **Pascal** (GTX 1000 Series), **Maxwell** (GTX 900 Series), **Kepler** (GTX 700 Series) and **Fermi** (GTX 500 Series) architectures, although **4000** series RTX cards should work as well.

It's important to note that where series are missed out (for example **600** and **800** series) they may be using architectures from older generations, for example the GTX **600** Series are actually using the **Kepler** architecture, and the **800** Series are actually only a series of **laptop GPU**, but should still support DirectX12.

On the AMD side, I can't seem to find a definitive answer, but just know that most GPUs in todays age will support it, and **its not worth downgrading to DX11 for the tiny percentage of people that can't play it**.

In terms of **operating system** again, I wouldn't worry, about it, DirectX12 works on Windows 11, 10, 8, and slightly on 7. But as I said before, anyone who plays games will likely already have a decent GPU and will probably be on **Windows 10 or even 11** by now.

> What changes when a new DirectX version comes?

Well, I'm not quite sure what you mean by this one, when a new version comes, it comes. If you're talking about what that will mean for your game, it would mean you're using an older version. But **would you rather wait for them to release a new version?** Probably not it would be a waste of time.

Hopefully that answers your question(s)
> 1 votes

---
Tags: windows, gpu, directx12
---


# Question
Title: What expressions/functions are supported in numeric fields?
In the Unity Editor, we can type an expression in a numeric field and press Enter to apply the result of the expression. For example, for a float field, we can type `10 * 5`:

If we press enter, the expression is resolved to `50` and that value is applied to the field.

Addition, subtraction, and division are also supported.

We can also type some mathematical functions, e.g.:

```
floor(131.8)
ceil(22.2)
round(5.5)

```

What other expression syntax/functions are supported?

# Answer
According to documentation for editing properties, the C# ExpressionEvaluator is used for processing numeric field expressions. The expressions that can be evaluated are:

* arithmetic operators `a+b`, `a-b`, `a*b`, `a/b`,
* power (`a^b`) and modulo (`a%b`) operators,
* parentheses,
* math functions `sqrt(a)`, `floor(a)`, `ceil(a)`, `round(a)`,
* trigonometric functions `cos(a)`, `sin(a)`, `tan(a)` (argument expressed in radians), and a constant `pi`.

Supported number types are: `int`, `float`, `long`, `double`.
> 5 votes

---
Tags: unity
---


title: How to choose how to store data?

text:
# Question
Title: How to choose how to store data?
Until recently, I used two methods to store data on my non-game project: XML files, and relational databases. I know that there are other kinds of database as well: the *NoSQL* kind. However I don't know if there are more choices available to me, or how to choose in the first place, aside from arbitrarily picking one.

How should I choose the kind of data storage to use for a game project?

I am interested in the following criteria when choosing:

* The size of the project.
* The platform targeted by the game, as well as the development platform used.
* The complexity of the data structure.
* Portability of data amongst many project.
* Simultaneous use of the data amongst different project. (i.e. User data)
* How often should the data be accessed
* Multiple type of data for a same application
* Configuration with multiple data storage.
* Any other point you think is of interest when deciding what to use.

I know about Would it be better to use XML/JSON/Text or a database to store game content?, but thought it didn't address exactly my point.

Furthermore, I would be interested to hear what other options are available, aside from flat file storage and relational databases. What about non-relational databases, for example? When is it relevant to use such a database over the formerly mentioned other options?

# Answer
Your question is *really* broad because of the sheer number of genres out there, but here's the perspective of a professional software developer.

You provided a list of criteria that you want to use to determine which data persistence mechanism you use. Those were:

* The size of the project.
* The platform targeted by the game.
* The complexity of the data structure.
* Portability of data amongst many project.
* How often should the data be accessed
* Multiple type of data for a same application
* Any other point you think is of interest when deciding what to use.

First we need to establish which options are available to us. Since you didn't specify a language or technology, it's hard to say exactly, but you are probably trying to decide between **XML** and **relational database** storage.

An important distinction to make is that **XML** isn't really a storage *mechanism* so much as a serialization technique. It's a way to represent in-memory structures for your game. Given that, you're really talking about **flat file** vs. **relational database** storage. These aren't the only options, but they're the most common, so I'm going to use them.

For flat files:

* XML
* JSON
* YAML
* XAML
* Plain Text

For databases:

* SQL Server
* MySQL
* DB2
* Oracle
* Many More

**EDIT:** You asked about other types of mechanisms aside from files and relational databases. The only other notable type of database that I have seen used on a regular basis are "Berkeley-style" databases, which are essentially key-value based. These tend to use B-trees to structure data so lookups are fast. These are great for configuration/setting lookup where you know exactly what you want (e.g., give me all the telemetry data for "Level 1").

Now that we have all the basics out of the way, let's touch on some of your criteria.

**The size of the project.**

Some might disagree, but the size of your project won't necessarily have a huge impact on your data persistence mechanism. You will want to build a reusable library of functions that store/load data from whichever mechanism you want. I would even suggest implementing an abstraction layer (check out the Adapter pattern) so that you could easily change your persistence mechanism if you needed to.

Having said that, for small projects, using XML on the file system can potentially work well, but you will want to address some of your security concerns (i.e., encryption) so that players can't change data at will.

**The platform targeted by the game.**

Platform isn't going to be a huge issue either. You should be more concerned about your development platform than the target platform. The reason for this is that some languages handle certain types of markup or databases better than others out of the box. That isn't to say that you couldn't use any of the above in almost any language, but sometimes it's best to use the supported tools that are available to you. Any platform will support flat files and parse XML, but on mobile platforms you might want to consider binary serialization if possible, or at least optimize your XML for storage.

**The complexity of the data structure.**

This is sort of a tricky one. Relational databases are great for just that...storing entities and their relationships. You have a better ability to enforce structure using a relational storage repository than you do with files on a file system. Consider the types of relationships between your entities as well as how often you're changing them or finding related entities. For extremely complex structures, I would suggest going the database route.

**Portability of data amongst many project.**

When it comes to portability, you should consider the fact that databases are naturally more heavyweight than files. There's installation and configuration overhead, different databases will be available for different platforms, etc. SQLite is a pretty good way around this. However, when it comes to portability, you will likely have an easier time with file-based solutions like XML.

**EDIT:** There are some other concerns you mentioned about portability in one of your comments. Ultimately you don't want your data to be coupled too tightly to any product or file type. It's ultimately best if you can store stock data (levels, enemies, etc.) in some kind of abstract format (tab delimited files, XML, etc.) that you can easily parse and store in a database/file system at compile or load time. This means that you can swap out your storage mechanism on a whim and just rewrite the parsing piece.

**How often should the data be accessed**

Lots of data access means lots of I/O unless you have some kind of a caching mechanism. Databases keep structures in memory and are great for data manipulation and retrieval. If you're really persisting data constantly, you might want to stick with a database.

**Multiple type of data for a same application**

Volume is certainly a consideration, but unless you're talking about persisting thousands or millions of objects, file system will still be acceptable as a solution.

**Game Type**

The type of game you're building can have a huge influence on the platform you choose. Yeah, for most client-only single-player games, you're going to be fine using a compressed or encrypted file system-based solution. If you're talking about games with an online component, though, that would be crazy. Go the database route and save yourself the headache. Let the server manage all of your data using a back-end cluster.

Hope some of this feedback helps. It's by no means completely comprehensive, and making the decision is ultimately up to you, but my commentary should give you some things to think about.

**EDIT:** There are some times where taking a hybdrid approach makes a lot of sense. For example, let's say you are developing an MMORPG. On the client side, you might store cached data about other players in a non-relational database (as mentioned above). On the server side, you're storing all game data in a relational database to persist it. And then again on the client side you're probably storing log data, configuration data, etc. in XML/flat files for easier accessibility.

Another poster also mentioned that sometimes it's nice, even if you're storing data for production in a database, to have a way that you can use flat files for development instead...it can just be easier to remove another product from the mix.
> 26 votes

# Answer
Lately I've found myself constrained by the rigidness/difficulty of adding to relational databases. I'd love to explore document-based databases (e.g. couchdb), as they seem very suitable for games, state, and flexibility. But it's not really practical to set up multiple database types for a small project. As a result, I've set up a hack similar to just using a binary blob field in certain fields of the database.

What I'm doing is using json encoded data in the database and a wrapper that converts the data into json and back out whenever it's needed. So a basic character profile might look like this in the database:

`{"char_id":24,"char_name":"tchalvak","level":43,"profile":"Some profile here."}`

Json is still nicely readable in the database so if you're working bare to the metal with the sql and sometimes access the database directly as well, it's manually modifiable if you wish to.

Now, all of that is a hack, and I don't advise copying it, but here's the overall point: **Don't rely only on one system.** Use a relational database and fudge the system. Or use two different types of data storage systems (e.g. flat file and relational database?), so that you can get the most benefit from both. No matter what people suggest, or what one system you go with, down the line you're going to find circumstances where another approach would work better, so be prepared to add an alternative and see where it takes you.
> 2 votes

# Answer
Why use one method of data storage?

In most cases, the game you release to the world does not need the same data storage functionality that the game needs during development.

Here's a comparison of some release / development requirements:-

```
Requirement      |  Release  |  Development  |  QA
==================================================
Multi user       |    No     |      Yes      |  No
Writable         |    No     |      Yes      |  No
Revision Control |    No     |      Yes      | Yes (but only reading)
Compact          |   Yes     |       No      |  No
Fast             |   Yes     |       No      |  No

```

Ideally then, you would define an interface to your data loading module and then create multiple versions, each tailored to specific needs.

On one project I worked on many years back, loading level data off CD was taking far too long (off HD wasn't great either). So I came up with a the following. I had three methods for loading level data:-

1. Normal loading - for development time when assets were changing
2. Pre-release - effectively a method to convert normal data into fast loading data
3. Release - fast data only (not editable)

This reduced loading times from minutes to seconds.
> 2 votes

# Answer
In the RTS gene, game data has been stored in files.

The units and attributes have been stored in INI or XML files or other text-based formats, and the models have been a mix of binary or even text-based formats, and the textures and sounds and other media in mainstream formats. Sometimes it has been in a container that has crude encryption - Westwood's mix format comes to mind. But this is mostly obfuscation - if you look inside them, they are just normal files in easy to handle formats.

With the advent of online play it has become increasingly common for the game data to be provisioned post-installation over the internet, although often this is still stored on the filesystem.
> 0 votes

# Answer
An approach I recently used for a hobby project RPG is the following ...

Data for entities I store in CSV files, which can be thought of as a simple textual database. For my use-case I use `|` as a seperator.

I've added a shell script that converts each entry in the CVS file into a Lua file, as the game is written in Lua with LÖVE.

Since all generated files for entities are in Lua, these files can be loaded directly into the game.

One might wonder: why not just add Lua files directly for each entity? Well, it's more error prone to ensure all keys and values are entered correctly. Especially when each entity is defined in its own file. The tabular format of CSV makes it easy to check if no field is missing, the correct value is used in each column (when comparing to other columns), etcetera.

One might also wonder: why not just use a real database like SQLite? Personally, I just find it easier to modify tables directly in a text editor instead of requiring special tools.

My **creature.csv** looks as such:

```
ID$|NAME$|HD$|AC#|WEAP@|SPEED#|SIGHT#|CR#|SPRITE$|SOUND_HIT$|
skel_warr1|Skeleton Warrior|1d12|15|scimitar1,claw1|30|60|1/3|skeletal_warrior_new.png|growl6.wav|
goblin1|Goblin|1d8+1|15|morningstar1,javelin1|30|60|1/3|goblin_new.png|paind.wav|
wolf1|Wolf|2d8+4|15|bite1|50|60|1|wolf.png|monster-8.wav|
ogre1|Ogre|4d8+11|16|greatclub1,javelin1|30|60|3|ogre_new.png|ogre4.wav|

```

***NOTE 1**: The weapon types are IDs based on another **weap.csv** file. Again, in a way this makes these CSV text files a database as these IDs can be thought of as foreign keys.*

***NOTE 2**: I've added type annotations in the header field, which are used by the shell script to generate values of the correct type. I've added type annotations for string (`$`), number (`#`) and array (`@`). If no type annotation is defined, will assume string.*

***NOTE 3**: Instead of editing text files directly, one could also use a tool like Excel. This might be useful when dealing with non-programmers. Likely for most people also easier than using an actual database.*

The generator shell script is defined as such:

```
#!/bin/bash

# the script directory
DIR="$(dirname "$0")"

TARGET_DIR="${DIR}/gen"

# arrays to manage CSV column names & related type info
COL_NAMES=()
TYPE_INFO=()

# set Internal Field Seperator to: |
OIFS=${IFS}
IFS="|"

isnumber() {
    awk -v a="$1" 'BEGIN {print (a == a + 0)}';
}

function generateEntity() {
    declare -a FIELDS=(${1})

    local CSV_PATH="${2}"
    local ID=${FIELDS[0]}
    local TYPE=$(basename ${CSV_PATH/\.csv/})
    local TYPE_DIR="${TARGET_DIR}/${TYPE}"
    local FILE_PATH="${TYPE_DIR}/${ID}.lua"

    # constants for newline and tab - these are escaped for use with awk script
    local nl="$(printf '\nq')"
    local tab="$(printf '\tq')"

    # notify on the entify file we're generating
    echo "${tab%q}${FILE_PATH}"

    # create an entity type directory if none exists already
    mkdir -p "${TYPE_DIR}"

    # generate LUA string for entity file
    S="return {${nl%q}"

    # get field count from array
    local N_FIELDS=${#FIELDS[@]}
    for (( i = 0; i < $N_FIELDS; i++ )); do
        local COL_NAME=${COL_NAMES[i]}
        local TYPE=${TYPE_INFO[i]}
        local VAL=${FIELDS[i]}

        # based on type, add value as number, array or string
        if [[ $TYPE == number ]]; then
            # assign default value of 0 if not defined
            if [[ -z ${VAL} ]]; then VAL="0"; fi

            # append to Lua string
            S+="${tab%q}${COL_NAME} = ${VAL},${nl%q}"
        elif [[ $TYPE == array ]]; then
            # variable to store result
            local OUT=""

            # temporary use comma seperator for fields
            IFS=",";

            # loop through each item in fields
            declare -a VALS=(${FIELDS[i]})
            for VAL in "${VALS[@]}"; do
                if [[ `isnumber ${VAL}` == "1" ]]; then
                    OUT+="${VAL}, "
                else
                    OUT+="'${VAL}', "
                fi
            done

            # trim comma-space (, ) at the end
            OUT="${OUT%%, }"

            # restore pipe as field separator in order to parse columns properly
            IFS="|"

            # append to Lua string
            S+="${tab%q}${COL_NAME} = { ${OUT} },${nl%q}"
        else
            # append to Lua string
            S+="${tab%q}${COL_NAME} = '${VAL}',${nl%q}"
        fi
    done

    S+="}"

    # write the LUA entity string to the entity file
    echo "${S}" > "${FILE_PATH}"
}

function configureColumns() {
    local CSV_FILE="${1}"

    # extract the header rows
    HEADER=$(head -1 $CSV_FILE)

    COL_NAMES=()
    TYPE_INFO=()

    # convert column names to lower case and store in array
    for COL in $HEADER
    do
        # parse header type annotations:
        # - #: number
        # - @: array of strings
        # - $: string
        # default is string if no annotation provided
        if [[ $COL == *\$ ]] ; then
            TYPE_INFO+=(string)
            COL=${COL%?} # remove last character
        elif [[ $COL == *\# ]] ; then
            TYPE_INFO+=(number)
            COL=${COL%?} # remove last character
        elif [[ $COL == *\@ ]] ; then
            TYPE_INFO+=(array)
            COL=${COL%?} # remove last character
        else
            TYPE_INFO+=(string)
        fi

        # store the column names in an array
        COL_NAMES+=(`echo $COL | awk '{ print tolower($1) }'`)
    done
}

function parseCSV() {
    local FILE_PATH="${1}"

    # notify on the CSV file we're processing
    echo "${FILE_PATH}"

    # add newline at end of file in order to parse CSV properly
    [[ -n "$(tail -c1 ${FILE_PATH})" ]] && echo >> "${FILE_PATH}"

    {
        # ignore the header line
        read

        # parse remaining lines
        while read -r LINE; do
            # skip empty lines
            [[ -z "${LINE}" ]] && continue

            generateEntity "${LINE}" "${FILE_PATH}"
        done
    } < "${FILE_PATH}"
}

function generateEntities() {
    # clear target directory if exists
    if [[ -d ${TARGET_DIR} ]]; then rm -Rf ${TARGET_DIR}; fi

    # parse CSV files
    for FILE_PATH in "${DIR}"/*.csv; do
        configureColumns "$FILE_PATH"
        parseCSV "$FILE_PATH"
    done
}

generateEntities

# restore internal field seperator
IFS=$OIFS

```

The shell script will look for any CSV files in same directory as the script file. For each CSV file it will generate a subdirectory inside an **entities/** directory. For example, for a **creature.csv** file an **entities/creature/** directory will be generated and for each creature a Lua file is generated inside the directory based on its `ID` value.

The first entry of **creature.csv** results in the following **entities/creature/skel\_warr1.lua** file after being parsed by the generator script:

```
return {
    id = 'skel_warr1',
    name = 'Skeleton Warrior',
    hd = "1d12",
    ac = 15,
    weap = { 'scimitar1','claw1' },
    speed = 30,
    sight = 60,
    cr = 1/3,
    sprite = 'skeletal_warrior_new.png',
    sound_hit = 'growl6.wav',
}

```

**FINAL NOTE**: I don't use these generated entities directly in the game. Inside the game I still treat these files as data files. I make use of an entity factory to parse values from Lua data files to generate Entity classes.

The Entity class itself is based on ECS principles. For each Entity components can be added based on type. Some examples:

* Creature types will have a **CPU control** component added so the computer can handle movement.
* Player types will have a **keyboard control** component added, so the player will respond to keyboard input.
* Door types will have an **interactable** component added, so players and creatures can interact with the door to open or close it. And so on and so forth ...
> 0 votes

---
Tags: databases, data, xml
---


title: Test UE5 game on Xbox Series S

text:
# Question
Title: Test UE5 game on Xbox Series S
I have developed a simple game on UE5, and I want to test this on my Xbox Series S. Ideally, I would be able to have a beta version on my Xbox that updated when I edited it on my computer.

Apparently you can use something called Dev mode to do it. Does anyone know how I use this to test my games?

# Answer
> 2 votes
Yes, I believe that you'll need Developer Mode if you want to test your game directly. Below is a summary of Microsoft's documentation on Developer Mode.

### Installing Developer Mode

* Activate Developer Mode on your retail Xbox console
* Start your Xbox console.
* Search for and install the Xbox Dev Mode app from the Microsoft Store.
    + This Reddit thread mentions there may be two different apps (I was unable to verify this myself) and that you want the one with a green icon called "Xbox Dev Mode" and **not** the one with a black icon called "Dev Mode Activation".
* Launch the app from the Store page.
* Note the code displayed in the Xbox Dev Mode app.
* Register an app developer account in Partner Center. This is also the first step towards publishing your game.
* Sign in to Partner Center with your valid, current Partner Center app developer account. If you don't see multiple options in the left hand navigation pane, or don't see the **Create a new app** option in the **Overview** section, the following steps and activation links *will not work*; make sure you fully registered your app developer account from the previous step.
* Go to partner.microsoft.com/xboxconfig/devices.
* Enter the activation code displayed in the Xbox Dev Mode app. You have a limited number of activations associated with your account. After Developer Mode has been activated, Partner Center will indicate you have used one of the activations associated with your account.
* Click **Agree and activate**. This will cause the page to reload, and you will see your device populate in the table. Terms for the Xbox Developer Mode Activation Program agreement can be found at Xbox Developer Mode Activation Program.
* After you’ve entered your activation code, your console will display a progress screen for the activation process.
* After activation has completed, open the Xbox Dev Mode app and click **Switch and restart** to go to Developer Mode. Note that this will take longer than usual.

---

The prior material was almost exclusively taken from Microsoft's documentation. The information below (accessing the portal & installing apps) was taken from the previously linked Reddit thread.

---

### Accessing the XBox Device Portal:

Developer Mode maintains its own settings, so if you did any network setup in Retail Mode (wifi, etc), you need to repeat that setup again for Developer Mode. You can do this by pressing the **Home Button** and entering the **Settings App**.

Back at the Developer Mode home screen, look at the **Test Accounts** window in the top right. If you do not see your email there, then you need to add it. Choose the **Add existing** button, and sign in with the same account you used for your Microsoft Partner Account.

After adding your account, make sure the box next to your email is checked in the **Test Accounts** window as well.

Next, in the **Remote Access** window in the bottom right, choose the **Remote Access Settings** button.

Make sure **Enable Xbox Device Portal** and **Require authentication to remotely access this console from the web or PC tools** are both checked.

Underneath the **Authentication** section, click the **Set username and password** button.

Create another username and password to access this device from your PC. It's separate from your account, so you can make it anything you want, just make sure to remember it.

Once you have entered a username and password for remote access, click the **Close** button to go back to the home screen.

You can now access the XBox Device Portal. Displayed in the **Remote Access** window is a URL for your specific to your Xbox. On your PC, type that URL into a web browser and hit `Enter`.

A page warning about your connection not being secure may appear. Go ahead and ignore it and proceed anyway. You may need to click an **Advanced** button to see the option to continue/proceed.

A small window to enter a username and password should appear. Enter the same username and password you used in the Remote Access Settings earlier. After entering the information, you should now be at the XBox Device Portal for your XBox. If you bookmark this page for convenience, you may need to remove `#home` from the end of the URL for the bookmark to work properly.

### Installing Developer Mode Apps from the XBox Device Portal:

When entering the Xbox Device portal for the first time, you will be on the **Home** tab. In the list on the left hand side, click on the **Settings** tab.

Scroll down and activate the **Preferences** drop down menu.

Make sure that both **Allow connections from the Xbox App** and **Treat UWP apps as games by default** are checked. If prompted, click the **Restart** button in the pop up to restart your XBox with the settings changes.

Once your XBox has restarted and is back at the **Developer Mode Home Screen**, on your PC at the XBox Device Portal, click the **Home** tab and refresh the page. Now you can start installing UWP apps.

Under where it says **My games & apps**, click the **Add** button.

Drag and drop your UWP game or app into the box, then hit the **Next** button.

Drag and drop any dependencies that the game or app requires to run into the box. If multiple dependencies are needed, then drag and drop one at a time until all are listed in the window. Then hit the **Start** button to push the game/app to your XBox console.

Once it has finished installing, it should appear under the **Games and apps** on your XBox **Developer Mode Home Screen**. From there you can launch and play them like you do in Retail Mode.

---

### Notes

In Developer Mode, you cannot play retail games or run retail apps. You can use Dev Home to switch between Retail Mode and Developer Mode:

* To switch to Retail Mode, open **Dev Home**. Under **Quick Actions**, select **Leave Dev Mode**. This will restart your console in Retail Mode.
* Caution (from previously linked Reddit thread): You may see a pop up with an option to "uninstall all side loaded apps/games". If you do not uncheck this your Developer Mode apps & games will be uninstalled. Various Retro Arch guides suggest using Safe-Exit instead to avoid accidentally erasing your installs.
* Do **not** run the Xbox Dev Mode app on any Xbox development hardware acquired through an Xbox managed program (for example, ID@Xbox). If you're a managed partner, you can get more information on activating development hardware here.

---
Tags: unreal, xbox
---


# Question
Title: Do real game developers use blueprints, or do they always use C++?
I'm starting to learn Unreal Engine 4. Every time I use blueprints, I think "that's not right" and I need to use C++, but there are not as many tutorials with c++ code. So, is it ok to use blueprints as a programmer?

# Answer
A real game developer is someone who manages to deliver a product.

Visual coding is a tool that can be used to achieve that. Some people use Chat GPT, some people use notepad, some people use blueprints, some use an IDE. Which tool you use boils down to personal preferences and the way you approach a problem.

As long as your game is running as you envisioned it in the end, the player will never know how you coded it.
> 58 votes

# Answer
Professional game development teams working in Unreal Engine typically use a mix of blueprint and C++.

One good strategy is for a designer to attempt to implement a feature in blueprint, then ask a programmer for review their prototype. The programmer can identify things that are inefficient, overcomplicated, or heavily used within the blueprint, and reimplement those in C++ in a reusable and maintainable way. The designer shouldn't hesitate to ask the programmer for C++ features that would make their job easier.

If you're the only developer on the team, of course, you have to wear both those hats. Use what works for you, as Zibelas suggests in their answer.
> 32 votes

# Answer
"Real" game developers always use the right tool for the job.

Even though it is perfectly possible to produce a professional game using only C++ or only blueprint graphs, most professional Unreal Engine projects use a mix of both. They both have their advantages and disadvantages.

One main advantage of blueprints is that they are very fast to compile, which makes it a lot more convenient to prototype and iterate with them. But C++ solutions are usually(!) much more performant at runtime. So when a feature that was initially prototyped with blueprints turns out to be a performance bottleneck, then redoing it as a C++ class can sometimes help.

And depending on what problem in particular you are trying to solve, either one might be easier to create, read and/or maintain. In general, blueprints excel at "simple" logic flows ("when B button is pressed, jump!"), while C++ is the better medium to convey logic that requires more complex algorithms and data structures ("when AI agent is idle, pick a job from the master job list using this rating function, break it down into steps using goal-oriented action planning and push them onto the task stack for the agent"). But there is a large grey area in between where either approach is reasonable.

And it's not uncommon either to use a mixed approach of creating a blueprint graph where some of the nodes are custom nodes implemented in C++ specifically for that one graph. This approach is particularly common in teams that contain both programmers and non-programmers who want to be able to tinker with the game mechanics without having to ask a programmer for every little change.

So the answer to the question "should I learn blueprints or should I learn c++?" is "Yes!"
> 7 votes

# Answer
I like to think of games as "interactive art". (As once, EA used to mean.) A game developer is part programmer, part artist. We should explore a lot of different modes to reify the experience we wish upon the player. Let it come from hard code (like C++, Javascript) or assistance tools like Blueprints.

Professional game developers know many ways to manifest their ideation. Some even use pen and paper to prototype the game.
> 4 votes

# Answer
In Unreal Engine - supported by the approach of the Fortnite team - the intended design of Blueprints is that C++ usually exposes functions, logic, events etc, into a blueprint ready for the game designer to make use of in the intended way. In Unreal Fest, this has been a topic raised quite often, and answered in this way.

Regardless - as others have stated - who cares. When the game works, is fun, makes money and is more often than not superceded by the next game... choices like this become a question of maintenance burden rather than anything else.

To summarise: Expose parts from C++, use in Blueprint, but most importantly, get the game made.
> 3 votes

# Answer
This answer is applicable to any software development task. As a general principal you should use the highest level language/tool that gets the job done. This will result in the fastest and cheapest development and the easiest maintenance. You should use lower level tools as needed to improve the performance of bottlenecks or to do things that are not supported in the high level tool/language. Do not base your decisions on idiology but let the task dictate the tool.

In your specific case, use blueprints wherever possible and only use C++ to do something that cannot be done with blueprints (or is more difficult) or where the performance would be unacceptable. And, as always, don't prematurely optimize code - always profile it first.

C++ is one of my favorite languages, but it is usually not the fastest or cheapest (in terms of development time) way to solve a problem with the required performance. This is the metric that should drive any 'professional' developer.
> 2 votes

# Answer
Starting with **Blueprints in Unreal Engine is awesome**! They're a visual way to learn core concepts without code, making it easier to grasp than diving straight into C++. Think of them as training wheels - building your understanding before transitioning to C++ for more control and efficiency. Don't be afraid to mix and match! Use Blueprints for faster iteration and C++ for performance-critical sections. This flexibility is key in Unreal, so have fun creating and learning!
> -1 votes

---
Tags: c++, unreal-4, blueprints
---


# Question
Title: Correct way to control tiles transparency on tile map?
Some 2D top-down games use tile maps and use transparent tiles for representing static objects. For example **Stoneshard**. When the character walks behind a tree, the tree becomes partially transparent. ( More recognizable example may be Stardew Valley, but I don't remember exactly )

It does not seem like a difficulty in terms of rendering, however I wonder what is efficient way to *detect* such condition, when the character "intersects" particular potentially transparent object.

I can determine the indices and values of tiles which are intersected by the character, but what if the character is partially covered by some object? Then the whole object should become transparent. Does it mean that I have to implement some kind of data object to represent the potentially transparent object on the map and its tiles?

It may seem like I have already come up with solution myself, but I suppose there can be some other, more efficient ways to do this

# Answer
I managed to implement this kind of behavior. First step was to parse the certain layer of the map, containing potentially transparent objects, to a collection of data structures. Each of them holds the mesh for respective tiles. For a case, when an object is presented by multiple adjacent tiles, I used simple algorithm to check if tiles are present in the layer at positions adjacent to the target tile.

Second step was to create the same shader instance for each object and set uniform value, representing the transparency/opacity on intersecting the object. To determine, which object on the layer is intersected, I added property to the object data structure hold, which holds the set of tiles' indices related to the object.

The shader itself is simple.

```
in vec2 fragmentUV;
out vec4 fColor;

uniform sampler2D textureSample;
uniform float transparency;

void main(void)
{
    fColor = vec4(1.0, 1.0, 1.0, transparency) * texture(textureSample, fragmentUV);

    if (fColor.a <= 0) {
        discard;
    }
}

```
> 0 votes

# Answer
Implement alpha blending at the pixel level during rendering for partial transparency in 2D top-down games without requiring complex data structures for individually transparent objects.
> 0 votes

---
Tags: tilemap, tiles
---


# Question
Title: Unity crashes if there are more than 4 terrains
please can you help me with the issue that I face, that is, I decided to create open-world game by creating several terrains and connect them together in Unity and firstly respective size of the terrains was 500X500 then I decided to add more terrains to make game world bigger and once I added the 5th terrain in the scene, Unity simply crashed. Later, I thought what if I increase the sizes of terrains rather than create more new terrains then the sizes of originally created terrains were changed from 500X500 to 800X800 and again Unity crashed. Please guys help me out with that and how to overcome that and I am just trying to create game without using any ready plugins and, say, try to create the game on my own. Thank you for your attention))).

# Answer
> 0 votes
If you're truly trying to create an open-world, you shouldn't have an entire map in a single scene (at least in my experience) - without various camera rendering techniques. Unity offers a few ways to get around this need for complex algo's, the simplest being: this

Other methods would involve 'stitching' I don't know if that's the technical term, but it's what I've used for many years. Quick search reveals: this post on reddit, with a 'stitcher' script

There are many more ways of combating this, probably too many to mention, but these should be a good starting point.

I'd recommend **not** buying a new PC... Just research tried and tested methods of loading, rather than dump it all in a single scene.

# Answer
> 0 votes
I would highly recommend using a "chunk" system, in which it generates terrain around the player, and then unloads/loads terrain when its close to the player, a good example if you've ever played it, is Minecraft. Which uses a chunk system to load and unload chunks of 16x16 blocks around the player, this way you can have unlimited terrain but it will never be loaded in all at once.

I can't explain how to do this on Stack, since that isn't really what it's meant for, but there are many chunk tutorials on YouTube that explain how to do it pretty well.

---
Tags: unity, 3d
---


# Question
Title: Syncing chest content in a host-client multiplayer setup
I'm modding a FPS game by adding a 2 player co-op multiplayer to an otherwise completely single player game.

One game instance acts as the host and I try to implement the synchronization of the gamestate as host-authority. The host does a full game state sync every 3 seconds, and inbetween, the host and client mostly exchange small diffs.

The client mostly asks the host to perform certain activities, such as building, adding and removing to/from chests both players can see and interact with.

For example, the player wants to add an item to a chest, so it puts the item into the chest locally, then sends a request to the host so the host does it too on its end. However, if there is a full game state sync right at the same time, the host doesn't know about the item yet, and makes the client remove the item from the chest the client just added. Of course, a bit later the host confirms the original request-to-add and both client and server see the item correctly in their inventory. The item flickers in-and-out for the client which looks confusing.

(There is a reverse problem of this where the client removes an item, the host full sync puts it back, then the acknowledgement removes it again.)

**How can I work around this?**

What I thought but haven't tried yet is to set a flag on the chest/item on the client so if a full sync comes between the request and acknowledgement, it is ignored by the client with respect to that particular chest/item.

# Answer
Assuming you are using a network protocol that has guaranteed delivery (so either TCP or UDP with a guaranteed delivery layer on top), you don't need to do full inventory syncs.

All you need to do is send the complete inventory when the character enters the game and then update the content with incremental AddItem/RemoveItem messages during the game session.
> 2 votes

# Answer
You usually want to assume that the client is "truthful" until proven otherwise by the host. What I would do in this case is this:

When the client puts an item on the chest, I would put a timer on the client's side to not be overwritten by the host until one cycle of synchronization has taken place.

That way, the client's actions won't get deleted until the next cycle.
> 1 votes

# Answer
As **MariaA** highlighted, it's crucial not to fully trust players in the game.

Make certain the client doesn't locally add the item to the chest. The item should only appear in the chest once the server approves it.

I would also recommend modifying the synchronization process for this. Rather than updating every 3 seconds, it's more efficient to have the client wait for the server to notify it of any changes.

If implementing those change requires adjusting your codebase, it's advisable to invest the extra effort for the future integrity of the game.
> 0 votes

---
Tags: networking, multiplayer, synchronization
---


# Question
Title: Using Unreal Engine 5 PCG graph to spawn terrain altering blueprint actors causing loop
I am using a PCG graph to spawn in actors, which are blueprint stamps for the terrain height map. I believe the issue I am facing is that when the blueprints are spawned, they alter the terrain, which prompts the PCG graph to regenerate.

My PCG graph is pretty simple:

Is there a way to set all points to 0 on the global z-axis? Or a way to only sample the pre-altered terrain?

# Answer
> 1 votes
Yah mate ran into the same problem. Try using a WorldRayHitQuery instead of the Input node or Get Landscape Data node.

When the landscape updates it doesn't re-dirty the hit query so your graph won't flicker.

---
Tags: procedural-generation, unreal-5
---


title: Networking for Complex AI movement

text:
# Question
Title: Networking for Complex AI movement
The enemies in my game are underpinned with a FSM with the motion planning handled by vector steering behaviors, in short - It just calculates a new vector based on obstacles/other objects around it.

This makes it highly volatile as opposed to an A\* path finder.

My question: How do multiplayer games handle 'complex' calcs for movement where the risk of de-sync is high? What is the recommended/general use pattern in this case?

Would the server & client both run the vector code and then simply have the server check periodically to correct?

Or would the server just handle all the logic and simply feed coordinates to the client to display the enemies? While this option seems easier and would work in theory. I feel in practice it wouldn't be very efficient having a server firing off packets for 50 different enemy units.

# Answer
It's a good practice to never trust the client.

For NPC states that should be the same for everyone, it's better to let the server handle the calculations and behavior. If the NPC's behavior doesn't depend on specific player states, you don't even need to replicate the position because the server will handle the NPC movement. Instead, if the client dictates the NPC's movement and calculates the position, then that position needs to be replicated.

When it comes to player actions, rather than giving the client full control, have it request the server to perform actions. After the server verifies and approves, it can implement the changes and inform everyone.

This approach ensures consistency and reliability for everyone in the game.
> 1 votes

# Answer
First, of all, give authority of those NPCs to the server. They feed the client the positions and movement vectors, and the clients just render them as they arrive. Now all the clients will see the same behavior.

However, due to network latency, the behavior might look a bit choppy and incoherent at times. To compensate for that, you can let the clients do client-sided prediction. Which means they run the same simulation as the server does and render the results, assuming that the server will agree.

Now what happens if the server does not agree? What if a packet arrives that tells the client that their prediction was wrong and the npc went left instead of right? Then you need to correct the position.

* With small enough differences, it might not be worth to correct at all. That might just result in constant jitter.
* With medium-scale differences, you might correct by slowly interpolating the character back to their actual course over the next couple frames.
* With very large differences, you might have no other option but to immediately snap them to the correct position.

What exactly does "small enough", "medium-scale" and "very large" mean in numbers? That's something you need to tweak through playtesting under bad network conditions and experimentation.
> 1 votes

---
Tags: networking, multiplayer
---


title: Building system similar to Satisfactory

text:
# Question
Title: Building system similar to Satisfactory
I'm currently collecting ideas how to make a building and placement system in Unity.

The user can place the game objects on several layers or floors, but the objects need to be on top of the objects beneath. It can't hang in thin air. The layers could be in theory infinite.

First idea, to have several planes with a grid system where the user can place the objects. Each layer is its own plane and the objects are child elements of the plane, storing the positions of the objects of each layer and displaying the outline of the game objects beneath the current layer.

Second idea, having only one plane with a grid system and placing the game objects.

Any other ideas?

# Answer
> 0 votes
As far as I can tell from playing Satisfactory, it seems to not have a global grid. Objects can be freely placed anywhere in the world.

However, some objects (i.e. foundations) create an ad-hoc local grid when placed. Other objects can then be attached to that grid by placing them on a foundation-type object that is already part of the grid. This limits their orientation to 90° angles relative to the grid and positions to fixed grid increments, so the whole grid becomes neatly arranged.

How would I implement a system like that in pseudo-code?

```
when the player places a building
    perform a raycast from camera into the world
    if there is a hit
        if the hit is on the terrain
            allow free placement of the object
            if the placed object is a foundation object
                create a local grid aligned to the rotation and position of the object
                make the newly placed object the first member of that grid
        if the hit is on a non-foundation object
            deny placement
        if the hit is on a foundation-object
            get the grid the object is a member of
            snap position and orientation to the grid
            make the object a member of the same grid

```

# Answer
> 0 votes
How I would solve it would not involve multiple planes but rather a single one.

A grid for placement is displayed at the intercetion shadow building with the world. You will have three different states I can think of

* Collision with the default world
* Collision with an uneven building top
* Collision from the side

Your life will be a lot easier if you allow to build only buildings on top of platforms. This will allow you in the default world to have a ground that is not straigt by simply extending the platform downwards and offering an even surface afterwards.

When you try to place a platform on top of an existing structure, the building grid can be calculated by storing (not neccessary on the object itself) the buildings/ producer height. Since all buildings are placed straight, any point from the bottom of the building to the stored max size will allow an easy placement on top of something without having a weird 2/3 stacked building next to each other/ partially overlapping. You can make your life even easier if all buildings are either having the same total height or only a few total heights overall.

Side collisions can be solved again with platforms. If buildings can be only placed on them, you ignore the collision and use the last valid location you had. This means you would not display a shadow outline when the initial hit for a building is on a second building. The first hit with a platform will display the shadow building. If you snap the building to the grid already, it will have a similar feel for the player in the regard that the shadow is not updating the location all the time. A hovering from platform to build building to platform might look similar from updating the location between grid locations. If the distance between last valid hit and current hit is too big (like pointing the mouse over a long building complex), you could simply hide the shadow image again until the next platform hit.

You will face another problem with an inifite layer approach or allowed building height though.. The target hardware will only be able to handle so much. If you offer your player infinite layers, they will use those. The buildings won't be taking too many ressources itself but conveyor belts with items on it might get really fast on the limit what you can handle. Depending on how you create the visuals on it, how far they can travel in your game, how far from the player they can run/ be active, etc. The placing of objects in comparison is simpler

---
Tags: unity
---


# Question
Title: How can I change the game executable name to something other than UE4.exe?
I have a game and when I export it it is called Bounced! but in windows task manager the process appears as UE4.exe but with the logo of my game, how can I change this to Bounced.exe?

# Answer
The name of the executable is dictated by the name of your ***.uproject** project file when you first create your project and package it, so if you already have an existing project called something like "UE4", you won't be able to change the name of the executable - it will always have the same name as the name of the project.

To change it on an existing project, it seems like you'll have to make a new project with a new \*.uproject file, copy the old project over to the new project directory, delete the old .\*uproject file, and then run it again and repackage it. Alternatively, you can rename that \*.uproject file and then make any code changes to reference the new project name as needed, depending on if your project is blueprint-based or not. (**Source**)
> 1 votes

# Answer
Older versions of Unreal might be a little different, but this worked for me on 5.3:

1. Rename the `.uproject` file to the new name. This does not change the executable name, but does change the name of the directory that the game data is stored in. You should be able to just directly rename it without editing anything inside of it.
2. Open your `Source` folder and rename the two `.Target.cs` files. Edit them and change the class name to match the new file names (without the `.Target` part). The name of the non-editor "target" will be what is used for the executable name. You do not need to change the names of the any of the modules in `Source`; just change the `.target` files.
3. Delete your `Binaries/Win64`, `Intermediate`, and `Saved` folders, regenerate the project files and rebuild. You might be able to omit deleting some of them, but I find that this is the safest option. NOTE: deleting "Saved" will reset your editor preferences and source control settings.

When you do a new build, it should now use the new name.
> 1 votes

---
Tags: unreal-4, windows, export
---


# Question
Title: How do I save data for multiple things sharing the same script?
I have level 0 rusted sword, then I upgrade it and save my game.

I implemented my save system by following Godot tutorials. But with this approach, after exiting and re-launching the game, all rusted swords in the game are now upgraded.

What do I have to do so that only that specific sword is upgraded?

My current system works like this:

```
detect item on floor:
       press key to pick:
        check what type of item it is:
          check if item slot is viable:
              delete item from floor, add into the item slot

```

And I reverse the order for dropping items, which of course means that item ID changes every time it is dropped and instanced again, so using that is problematic.

```
func savePlayerData():
    var data = {
       "strength": strength,}
    var dir = Directory.new()
    if !dir.dir_exists(SAVE_DIR):
        dir.make_dir_recursive(SAVE_DIR)
    var file = File.new()
    var error = file.open_encrypted_with_pass(save_path, File.WRITE, "P@paB3ar6969")
    if error == OK:
        file.store_var(data)
        file.close()

func loadPlayerData():
    var file = File.new()
    if file.file_exists(save_path):
        var error = file.open_encrypted_with_pass(save_path, File.READ, "P@paB3ar6969")
        if error == OK:
            var player_data = file.get_var()
            file.close()
            if "strength" in player_data:
                strength = player_data["strength"]

```

# Answer
Let us talk about inventories.

Real world inventories.

An object in a store have a unique id (e.g. a Serial Number) and a model (e.g. "Rusted Sword 2000").

And there might be other information attached to it, for example a manufacturer/provider (e.g. "Acme Inc."). Now, is that attached to the unique id or the model?

Well, all objects of the same model are by the same manufacturer ("Acme Inc." makes "Rusted Sword 2000"), so it does not make sense to attach that to the unique id, but to the model.

Other attributes might be different per item. For example if you need to track where it is in the store, or if it is damaged, and so on. That information need to be attached to the unique id.

---

Now, in your game, you have rusted sword object. Does that object represent the unique item, or does it represent the model? Well, you might need both.

You will have an object that represents the item, which have information about it such as the durability, or upgrades that the player has added to it.

And that object must have a reference to another object that represents the model, which will have information common to all items of the same kind, for example its base stats.

---

Now, as you can imagine, if you put the upgrades in the object that represents the model, then it will apply to all items. Which seems to be the issue at hand. And you would solve it by moving that information to the object that represents the unique item.

It might be the case that you do not have an object to represent the unique item, in which case you need to come up with it.

In any case, I believe you need to think about the structure of your data. And this is not a problem of how you store or load it.

**Addendum**: I've been saying object, but these might be rows in a table, or items in an array, whatever works.
> 3 votes

# Answer
Hey **Blue** the post of **Theraot** perfectly describes your problem.

Consider to create an identifier to identify a specific item.

***Your item class:***

```
// Set properties
var item_id : int = uniqueID
var name : String = ""
var description : String = ""
var strength_bonus : int = 0

// then we define a constructor
func _init(item_id: int, name: String, description: String strength_bonus: int):
self.item_id = item_id
self.name = name
self.description = description
self.strength_bonus = strength_bonus

// we define a method to upgrade an item stength
func upgrade_item(new_strength_bonus: int) -> void:
strength_bonus = new_strength_bonus

```

***When we saving our data we save an array of items:***

```
    var data = {
    "items": []  // array to store items of type itemclass
}

```

***When loading our data we loop through the items:***

```
    for item_data in player_data["items"]:
    var item_id = item_data["item_id"]
    var item = find_item_by_id(item_id) // this would be a helper method that needs to implemented first

```

I hope this was helpful :)
> 1 votes

---
Tags: savegame, gdscript, godot-3
---


# Question
Title: Identify doorways to partition a collection of walls with gaps into rooms
I am looking for an algorithm that can find separate rooms inside a set of walls, by determining which openings should be considered doorways between adjacent rooms. All is defined on a grid. My main problem is that I cannot be sure that both sides of the same passage will be in one straight line.

In the picture there is an example with five rooms separated with red lines and black walls, although it might be acceptable to merge the middle room with one of the others. I have the black walls as input, and I want to generate the red lines marking the doorways as the output.

Basically I am trying to avoid having to mark them manually to minimize any chance of making a mistake. I made some attempts with focusing on the corners, but got stuck with the passageways not in a straight line problem.

Any ideas?

The walls are stored in a two dimensional array of (half-)bytes storing a bitmask where

* 1 means that the wall in this cell has a connection to the cell above
* 2 -\> connection to the cell to the right
* 4 -\> connection to the cell below
* 8 -\> connection to the cell to the left
* 0 -\> cell is empty room

If the wall in a cell has multiple connections the sum of the connections is stored. For example a '3' would represent a "L" shaped wall segment, 'E'(14 in hex) would represent a "T" shape and 'F'(15) would represent a "+" shape.

The example would be stored like this:

```
6AAEAAC
5001005
5000005
780002D
5000005
5005005
3AA9029

```

# Answer
> 0 votes
It took a while, but I think I got some thing.

It might not work with small rooms, but with at least 3 fields in diameter should work.

1. Assign to each field an integer value equal to its distance to the nearest wall. This will create disconnected patches of higher numbers. Each patch will be a core of a room.
2. Expand each patch by adding to it every field adjacent to it that does not neighbors a field with an assigned number higher than its own, unless the field with a higher number already is a part o the patch.
3. Repeat until no new fields are added to any of the patches.
4. A few fields may still be outside of every patch. Add them to the nearest patch (several if more than one patch are at the same distance).

Curious thing happens with a long corridors between large chambers, if the is no narrowing at the end. In that case the corridor is considered a part of both chambers. Which turns out suits my purpose.

# Answer
> 1 votes
This is a variation of an algorithm I used myself in a grid based randomly generated level (a simply 0= empty 1= wall grid) to place doors.

## Finding possible doorway tiles

There are some simple rules depending on the surrounding tiles to determine whether or not there can be a door.

The tile itself must be empty and have at least two neighboring wall tiles that are not connected with each other (only within the neighbors).

For this you can examine the neighboring tiles counter-clockwise. Whenever you examine a "wall" tile after examining an "empty" tile you increase a counter by 1. If that counter is exactly 2 after one complete circle (examining the first tile a second time as last tile). you have a possible doorway.

However this will produce "to many" doorways, often adjescant to each other. In your example the door at the lower edge has two possible doorway tiles. The "real" doorway you marked as red in the image and the empty tile directly above that.

## Finding the right doorway tiles

Now that we have all possible doorway tiles (here X but maybe marked with -1 in the array)

```
6AAEAAC
5001005
50X0X05
780002D
50X0X05
5005X05
3AA9X29

```

To solve this problem you could create a "ranking" on how the best/worst doorway situations look like. For this ranking we can continue using negative numbers in the array, e.g. -1 being "the best" doorway and "-F" being the worst

1. The "best" doorway tile is a tile that has exactly two adjescant wall tiles that are exactly opposite of each other and only empty tiles as neighbors otherwise.
2. Next come those with more than two adjescant wall tiles but who still have two exactly opposing wall tiles
3. Next those that have exactly two adjescant wall tiles which are not exactly opposite of each other
4. And lastly all remaining doorways.

With the ranking in place we can always delete the worse of two adjescant doorway tiles or a random one in case of equal ranking.

This should leave you with nicely placed doorways.

---
Tags: 2d, algorithm, grid
---


# Question
Title: How to ACTUALLY full screen the game view?
In Unity, you can use the maximise on play option, to full screen the game when you play it. You can also double click the tab to maximise or minimize the view.

This works fine, but as you can see in the photo, technically it still leaves quite big borders around the view. This isn't really an issue, but when it comes to testing the game, having these borders is really annoying when attempting to scale things to the right size. It also feels less immersive which makes it more difficult to fine tune small details.

Both of these issues are quite important in the game that I'm making which is why I'm asking if theres a way to remove these borders and actually full screen the game without having to build/compile it.

# Answer
> 5 votes
The fullscreen feature was removed from Unity more than a year ago; see this thread.

The thread includes a link to an Asset Store package which adds support for full-screen play. I haven't tried the package and can't tell you whether or how well it works.

---
Tags: unity
---


# Question
Title: Particle system won't collide with box collider all the time. Rain seeps through ceiling
I'm trying to make it rain in my game, but am having a problem with it seeping through the ceiling. I put a box collider above the house to catch the rain as it falls and it worked for a while, but stopped working suddenly. I'm unsure of the cause of this at the moment. I have tried to change some variables in the particle system and tried other box colliders to test out different approaches, but nothing seems to be working. I am pushing a lot of particles for the rain system being about 2500 at any given time, but its not slowing down the gameplay at all. Could it just be too much for the system to process at a time? Below is a few images of my setup.

# Answer
As you can see in your screenshot, the Particle System's Collision Module has a property "Max Collision Shapes" which is currently set to 256. This means that only 256 rain particles will have colliders. If you have 2500 particles, most of them will not have colliders.

You can try increasing the value to 2500, but you may need to reduce the Collision Quality to prevent performance issues.
> 2 votes

---
Tags: unity, collision-detection, particles, graphic-effects, weather
---


# Question
Title: How can I make a Unity Animation (interpolation from A to B) "procedural", by varying A and B?
# Goal

One might use a coroutine to interpolate an object's position from point A to point B.

What I'm trying to do is store that interpolation as a Unity Animation file, but have the ability to manually enter points A and B each time it plays.

# Description

I have a simple Animation — a "jump", if you will — which I want to chain with the aforementioned interpolation:

* the object does a little jump;
* mid-air, the object moves/interpolates to another position.

Of course, I could do this by playing the coroutine after the first animation is done, but it'd be cleaner to store both as Animation files and use an Animator Controller to manage them, especially since the 2 animations are technically parts of one whole.

Is that possible?

If so, how could I record/create it? If not, what's a clean alternative?

# Answer
> 0 votes
It sounds like what you want is Animation Parameters.

> Animation Parameters are variables that are defined within an Animator Controller that can be accessed and assigned values from scripts. This is how a script can control or affect the flow of the state machine. \[...\] For example, a script can set a parameter to control a Blend Tree.

Parameters can also be used to control animation speed, etc.

# Answer
> 0 votes
Animations in Unity are made to be predefined and pre-setup, so you cant modify them (at least not that I know of). You are probably best of using no animations and just using Coroutines, at least I think that would be easier. That way you can call another Coroutine after one has finished. Similar to how you would do it at the end of an animation. It would probably be a much "cleaner" method. As it would be all-code rather than a mix of animation and code.

---
Tags: unity, animation, animation-controller
---


# Question
Title: If I have three different kinds of blob tiles, how many tiles do I need?
Blob tiles are autotiles that match edges and corners. I know that for two different kinds of tiles, I need 47 * 2 tiles. But I have three different kinds of tiles. I thought that I needed 47 * 3! tiles, but I made them all and tried to use them, and discovered I was missing some. Like, a tile can have all three different kinds of tiles on it, and I didn't make those. How many do I need to make?

# Answer
If I'm reading Godot's Terrain TileSets documentation right, you can potentially select a different tile for any permutation of terrain types painted in *this* square and the 8 squares around it.

So if you have 3 choices in each of those 9 slots, that's \\$3^9 = 19\\,683\\$ tiles.

Apart from the grief of authoring all those permutations (if you could make one tile every 15 minutes and worked 8-hour days with no weekends, that's nearly two years of work!), that's also just too much data. If each tile is say 256 pixels wide then that's 4 GB of uncompressed texture data!

So, you need another strategy.

One surprisingly effective tactic is to work on "the dual grid". This is something Oskar Stålberg champions (see a talk here where he discusses it in more detail)

Here instead of thinking of the terrain type as being defined at the center of the tile, we think of it being defined at the corners. Or alternatively (for a square grid), we think of the grid on which we place tile sprites to be shifted one half tile over from the grid we use for painting / game logic.

With this simplification, for three terrain types you need only \\$3^4 = 81\\$ tiles, so we've saved ourselves several orders of magnitude of work, data storage, and complexity. You can see a sample layout of these 81 tiles arranged to seamlessly match their neighbours in this answer.

However, I'm not knowledgeable enough about Godot's systems to comment on whether there's a way or how to coax its TileSets into using the dual grid this way. Maybe others can suggest strategies for this.
> 2 votes

# Answer
You need 698 tiles for the full blob pattern with three terrains. It's less than \\$3^9\\$ as not all combinations make sense.

You can see the full list with **this tool**, selecting blob, and put terrains up to 3.

Obviously this is completely impractical. In addition to DMGregory's answer of using dual tiling, I can also recommend quarter tiling which gets a bloblike pattern with vastly fewer tiles.
> 1 votes

---
Tags: tilemap, tiles, tilesets
---


# Question
Title: How do I make the joints and weights skinned with the variables I'm using?
For some time now I have been trying to do skeleton animation using Rust and OpenGL(specifically the gl library), I loaded the animation information correctly(with the gltf library), the bone ids and the influence weights, however I was unable to apply the animation to the 100% correct model.

The screenshot below is the furthest I could get from making the animation look correct, the problem is that if you get close... You can see that between the transition from bone to bone, the joints with a greater deformation prevent the lighting is perfect on the character's skin, creating a slight doll-like sensation in which the joints highlight the skeleton:

This happens because the code I used in the shader is basically this where I only use the first transformation in the model:

```
// Animation
vec4 tp = vec4(pos,1);
tp = CORRECAO[int(ossosid[0])]*tp;
tp = (ANIMACAO[int(ossosid[0])]*tp);
tp.xyz += ANIMACAO2[int(ossosid[0])];
// Forget that part, that's just because the animation is scaled to appear on the screen...
// It's not part of the animation calculation.
pos = tp.xyz/50;

```

When I try to follow examples in which I use influence weights... It's not working, more specifically I can give code examples and show how it's not working:

When I try to switch to calculation:

```
vec4 tp = vec4(pos,1);
tp = CORRECAO[int(ossosid[0])]*tp;
tp = (ANIMACAO[int(ossosid[0])]*tp)*pesos[0] + (ANIMACAO[int(ossosid[1])]*tp)*pesos[1];
tp.xyz += ANIMACAO2[int(ossosid[0])]*pesos[0] + ANIMACAO2[int(ossosid[1])]*pesos[1];
pos = tp.xyz/50;

```

Totally distorted when:

Using:

```
vec4 tp = vec4(pos,1);
vec4 tp0 = CORRECAO[int(ossosid[0])]*tp;
tp0 = (ANIMACAO[int(ossosid[0])]*tp0)*pesos[0];
tp0.xyz += ANIMACAO2[int(ossosid[0])];
vec4 tp1 = CORRECAO[int(ossosid[1])]*tp;
tp1 = (ANIMACAO[int(ossosid[1])]*tp1)*pesos[1];
tp1.xyz += ANIMACAO2[int(ossosid[1])];
pos = tp0.xyz+tp1.xyz;
pos = pos.xyz/50;

```

Another:

```
vec4 tp = vec4(pos,1);
tp = (CORRECAO[int(ossosid[0])]*tp)*pesos[0];
tp = (ANIMACAO[int(ossosid[0])]*tp);
tp.xyz += ANIMACAO2[int(ossosid[0])]*pesos[0];
tp = (CORRECAO[int(ossosid[1])]*tp)*pesos[1];
tp = (ANIMACAO[int(ossosid[1])]*tp);
tp.xyz += ANIMACAO2[int(ossosid[1])]*pesos[1];
pos = tp.xyz/50;

```

Just one more:

```
vec4 tp = vec4(pos,1);
tp = (CORRECAO[int(ossosid[0])]*tp);
tp = (ANIMACAO[int(ossosid[0])]*tp)*pesos[0]+(ANIMACAO[int(ossosid[1])]*tp)*pesos[1];
tp.xyz += ANIMACAO2[int(ossosid[0])];
pos = tp.xyz/50;

```

In other words... I can't make elbows, knees, shoulders, leg connections and hips as smooth as I can do everything else... Specifically, know that: `CORRECAO` is the inverse bind matrix, `ANIMACAO` is the variable that rotates the point and `ANIMACAO2` is the position of the point in the animation.

My question is how do I make the joints on the model look smooth? How do I apply this in the vertex shader?

P.S.: The animated model is here: link

# Answer
```
vec4 tp = vec4(0);
vec4 tp1 = (CORRECAO[int(ossosid[0])]*vec4(pos,1));
tp1 = (ANIMACAO[int(ossosid[0])]*tp1);
tp1.xyz += ANIMACAO2[int(ossosid[0])];
tp += tp1*pesos[0];
tp1 = (CORRECAO[int(ossosid[1])]*vec4(pos,1));
tp1 = (ANIMACAO[int(ossosid[1])]*tp1);
tp1.xyz += ANIMACAO2[int(ossosid[1])];
tp += tp1*pesos[1];
tp1 = (CORRECAO[int(ossosid[2])]*vec4(pos,1));
tp1 = (ANIMACAO[int(ossosid[2])]*tp1);
tp1.xyz += ANIMACAO2[int(ossosid[2])];
tp += tp1*pesos[2];
tp1 = (CORRECAO[int(ossosid[3])]*vec4(pos,1));
tp1 = (ANIMACAO[int(ossosid[3])]*tp1);
tp1.xyz += ANIMACAO2[int(ossosid[3])];
tp += tp1*pesos[3];
pos = tp.xyz/100;

```
> 0 votes

---
Tags: opengl, animation, glsl, skeletal-animation, rust
---


# Question
Title: Shader to give the effect of a 2D character covered in oil
I have a 2D pixel art game where characters can be covered in a flammable black oil-like substance and I am looking for a simple way to depict that visually.

Simply tinting the character black won't work since that will just make it appear more dimly lit. It needs some form of texture or something to indicate it is oil. Simply drawing over the character with a repeating oil texture will give away the trick when the character is animated because when e.g. the head moves, that part of the texture stays in place. At least, the texture would need to have no obvious identifiable point of reference the player can track. Perhaps Perlin Noise could be used to produce such an effect somehow?

Any ideas on how to make an effect like that? Are there any examples of 2D games doing something like this?

To give you an idea of resolution and art style (Blasphemous):

# Answer
> 4 votes
I'd like to propose taking some inspiration from the 3D graphics / PBR world. From that perspective, the problem here is that your sprite image combines into a single color value, two different properties of each part of the character: its reflectance, the “actual color of the surface”, and how much light is falling on it.

So, one possible solution would be to separate those two properties. Have one image that is “flat”, un-shaded colors, and another image that has all the lighting effects — the shadows and highlights. Then, for normal rendering, you multiply the color texel by the light texel (probably multiplied by a large constant so that there's room for the lights to saturate the color to white for highlights), and for oily rendering you substitute a uniform dark gray (or perhaps a faint "oil slick" rainbow pattern) for the color. This way, the *shape* of the character still appears, because it still has bright highlights and shadowed parts, but the surface will appear to be oil instead of clothing and skin.

---

However, that requires extra work from whoever's drawing your character sprites, especially because that's not a standard 2D pixel art workflow. So if you don't want to do that, let's consider what might be a reasonable approximation instead. The key is that we want to replace the colorful materials with a dark, shiny surface. So, try these two steps:

* Desaturate (convert to grayscale).
* Apply a “curve” function that **preserves white, but pushes all other colors much darker.** By keeping the highlights, we don't lose the appearance of the character being well lit.

Doing both of those to your example sprite with simple photo editing tools gives:

It's not perfect, but for just a little color math, it's pretty good.

I think it might be further improved by adding an effect of dripping black pixels of oil below the outline of the character — implement this like you would a drop-shadow, by sampling the sprite texture at several offset positions *above* the pixel being displayed and deciding whether or not to draw a scrolling drips texture based on whether any of the sprite samples are opaque.

---
Tags: shaders, graphics, hlsl, graphic-effects, pixel-art
---


# Question
Title: GLSL limit uniform sampler2D to 4 for some reason
I'm writing a deferred rendering pipeline and my fragment shader looks like this:

```
#version 410

// Input vertex attributes (from vertex shader)
in vec2 fragTexCoord;
in vec3 fragNormal;
in vec3 fragPosition;
in mat3 worldToTangentSpace;

// Input uniform values
uniform sampler2D albedoMap;
uniform sampler2D normalMap;
uniform sampler2D metalMap;
uniform sampler2D roughnessMap;
uniform sampler2D occlusionMap;
uniform float metalnessFactor;
uniform float roughnessFactor;
uniform bool metalMapWithColor;

// output fragment color
layout(location = 0) out vec4 gbuffAlbedo;
layout(location = 1) out vec4 gbuffNormals;
layout(location = 2) out vec4 gbuffPositions;
layout(location = 3) out vec4 gbuffMetalRoughnessOcclusion;
layout(location = 4) out vec4 gbuffSpecular;

void main()
{
    // calculate normals
    vec3 normalColor = normalize((2.0 * texture(normalMap, fragTexCoord).rgb) - 1.0);
    normalColor.y *= -1;
    normalColor = normalize(worldToTangentSpace * normalColor);

    // calculate albedo color
    vec4 texelColor = texture(albedoMap, fragTexCoord);

    // get metal map value
    vec4 metalTextureColor = texture(metalMap, fragTexCoord);

    // calculate metalness factor
    float metalTextureValue = metalMapWithColor ? metalTextureColor.a : metalTextureColor.r;
    float metalValue = metalTextureValue * metalnessFactor;

    // get specular color
    vec4 specularColor = metalMapWithColor ? vec4(metalTextureColor.rgb, 1) : vec4(1,1,1,1);

    // calculate roughness factor
    float roughnessValue = texture(roughnessMap, fragTexCoord).r * roughnessFactor;

    // calculate occlusion
    float occlusionValue = texture(occlusionMap, fragTexCoord).r;

    // set gbuffer
    gbuffAlbedo = texelColor;
    gbuffNormals = vec4((normalColor + 1) * 0.5, 1);
    gbuffPositions = vec4(fragPosition, 1);
    gbuffMetalRoughnessOcclusion = vec4(metalValue, roughnessValue, occlusionValue, 1);
    gbuffSpecular = specularColor;
}

```

For some reason occlusionMap always return black pixels. I checked the uniform location that its not -1, so the uniform exists and don't optimized out, and I checked and the texture is set properly. However, its always black.

What made me realise its a sampler limit is that if I remove any other sampler, for example if I comment out the metal texture of albedo, suddenly the occlusion works and return the right pixel.

This is what it looks like with the full code (note the occlusion is black):

And this is what it looks like if I remove the albedo texture by setting it to vec4(1,1,1,1) - suddenly it works:

From what I read I should be able to use at least 16 textures. They are not so big and occlusion is only one channel. Why do I get one sampler removed?

Thanks!

# Answer
The issue is caused by exceeding the maximum number of active samplers. Removing a texture allows the occlusion texture to work because the total number of active samplers decreases. Ensure proper enabling and binding of all textures within the limit. Consider combining textures.
> 0 votes

---
Tags: shaders, glsl, fragment-shader
---


title: 2D isometric tilemap coordinates

text:
# Question
Title: 2D isometric tilemap coordinates
I am learning Unity and for now trying to rotate a tilemap using (x, y) --\> (-y, x). I have created a Grid and tilemap in it  As you can see my tiles are in cells of izometric tilemap. I am expected that each diamond is represent 'cell' and have integer coordinates (x, y) like (0, 1), see the picture below  But I can see that it is not work so

The problem is that if I try to use standart tilemap function like `GetTile` it is return wrong coordinates of the tile bcs it is use `Vector3Int` datatype, but in reality it seems obvious that coordinates is float. This problem leads to mistakes in rotation matrix.

It seems that when I chooce a cell layout property of tilemap to "Isometric" it is not change coordinate system to isometric projection.

Am I working correctly with isometric tilemap system? Or is this sort of unity's bug?

Upd: here is the source code of the script that I wrote Here how I instantiate tilemap

```
public class BaseTilemapInit : MonoBehaviour

    {
        [SerializeField]
        private Tilemap _tilemap;
        [SerializeField]
        private Tile _tilePrefab;
        [SerializeField]
        private int _width;
        [SerializeField]
        private int _height;
        [SerializeField] private float _tileWidth = 1.0f;
        [SerializeField] private float _tileHeight = 0.5f;

        // Start is called before the first frame update
        void Start()
        {
            Instantiate();
            _tilemap.CompressBounds();
        }

        public void Instantiate(){
            int offsetX = _width/2;
            int offsetY = _height/2;

            for (int x = 0; x < _width; x++){
                for (int y = 0; y < _height; y++){
                    _tilemap.SetTile (new Vector3Int (x, y, 0), _tilePrefab);
                }
            }
        }

        public int GetWidth()
        {
            return _width;
        }

        public int GetHeight()
        {
            return _height;
        }

        public float GetTileWidth()
        {
            return _tileWidth;
        }

        public float GetTileHeitht()
        {
            return _tileHeight;
        }
        public Tilemap GetTilemap()
        {
            return _tilemap;
        }
    }

```

And here is a camera controller which is responsible for positioning and rotating (okay not camera but anyway)

```
public class CameraController : MonoBehaviour
{
    //[SerializeField]
    //private Tilemap _tilemap;
    [SerializeField] private BaseTilemapInit _tiles;
    [SerializeField] private Transform _cam;
    private Tilemap _tilemap;
    private CameraControls cameraActions;
    private InputAction rotation;
    private Transform cameraTransform;

    void Start()
    {
        SetStartCameraPosition();
    }

    private void SetStartCameraPosition()
    {
        float width = _tiles.GetWidth();
        float height = _tiles.GetHeight();

        Vector2 gridCenter = new Vector2(width / 2, height / 2);
        Vector2 isoCenter = GridToIsometric(gridCenter);
        _cam.transform.position = new Vector3(isoCenter.x, isoCenter.y, _cam.transform.position.z);
    }

    private Vector2 GridToIsometric(Vector2 gridPos) {

        float tileWidth = _tiles.GetTileWidth();
        float tileHeight = _tiles.GetTileHeitht();

        float isoX = (gridPos.x - gridPos.y) * tileWidth * 0.5f;
        float isoY = (gridPos.x + gridPos.y) * tileHeight * 0.5f;
        return new Vector2(isoX, isoY);
    }

    private void Awake()
    {
        cameraActions = new CameraControls();
        cameraTransform = this.GetComponentInChildren<Camera>().transform;
    }

    private void OnEnable()
    {
        cameraActions.Camera.RotateClockwise.performed += RotateClockwise;
        cameraActions.Camera.Enable();
    }

    private void OnDisable()
    {
        cameraActions.Camera.RotateClockwise.performed -= RotateClockwise;
        cameraActions.Camera.Disable();
    }

    private void RotateClockwise(InputAction.CallbackContext context)
    {
        _tilemap = _tiles.GetTilemap();
        Debug.Log("Pressed E");
        Rotate (_tilemap);
    }

    void Rotate(Tilemap tilemap)
    {
        BoundsInt bounds = tilemap.cellBounds;

        for (int x = bounds.xMin; x < bounds.xMax; x++){
            for (int y = bounds.yMin; y < bounds.yMax; y++){
                Vector3Int position = new Vector3Int (x, y, 0);
                TileBase tile = tilemap.GetTile(position);
                if (tile != null){
                    Debug.Log ($"Tile {tile.name} at {position}");

                    Vector3Int newposition = Rotatation(position);
                    //Vector3Int newposition = IsoToCart(position);
                    tilemap.SetTile(position, null);
                    tilemap.SetTile(newposition, tile);
                }
                else{
                    Debug.Log($"No tile at {position}");
                }
            }
        }
        //_tiles.GetTilemap().CompressBounds();
    }

    private Vector3Int Rotatation(Vector3Int pos)
    {
        int x = pos.x;
        int y = pos.y;
        int z = pos.z;

        int newX = (-1) * y;
        int newY = (1) * x;

        Vector3Int newPos = new Vector3Int(newX, newY, pos.z);

        return newPos;
    }
    private Vector3Int IsoToCart(Vector3Int pos)
    {
        int x = pos.x;
        int y = pos.y;
        int z = pos.z;

        int newX = (x - y)/2;
        int newY = (x + y)/2;

        Vector3Int newPos = new Vector3Int(newX, newY, z);

        return newPos;
    }
    void OnDrawGizmos()
    {
        Tilemap tilemap = _tiles.GetTilemap();
        if (tilemap != null)
        {
            Gizmos.color = Color.green;
            BoundsInt bounds = tilemap.cellBounds;
            Vector3Int min = bounds.min;
            Vector3Int max = bounds.max;

            Vector3[] corners = new Vector3[4];
            corners[0] = tilemap.CellToWorld(new Vector3Int(min.x, min.y, min.z));
            corners[1] = tilemap.CellToWorld(new Vector3Int(max.x, min.y, min.z));
            corners[2] = tilemap.CellToWorld(new Vector3Int(max.x, max.y, min.z));
            corners[3] = tilemap.CellToWorld(new Vector3Int(min.x, max.y, min.z));

            Gizmos.DrawLine(corners[0], corners[1]);
            Gizmos.DrawLine(corners[1], corners[2]);
            Gizmos.DrawLine(corners[2], corners[3]);
            Gizmos.DrawLine(corners[3], corners[0]);
        }
    }
}

```

# Answer
> 0 votes
Okay I finally understood how it works. The key point here is that I try simply to rewrite tiles doing so:

```
for(...){
   ...
   tilemap.SetTile(position, null);
   tilemap.SetTile(newposition, tile);
   ...
}

```

So sometimes from diamond-shaped tilemap I got tile at completely wrong positions.

The solution that helps me is: **Store new position somehow** (I had chosen a Dictionary)

```
Dictionary<Vector3Int, TileBase> tilesPositions = new Dictionary<Vector3Int, TileBase>();
   for(...){
   ...
   Vector3Int newposition = Rotatation(position);//here Rotation do (x, y) -> (-y, x)
   tilesPositions[newposition] = tile;
  ...
  }

```

Then clear all tiles and set it from Dictionary

```
tilemap.ClearAllTiles();
foreach (var item in tilesPositions)
{
    tilemap.SetTile(item.Key, item.Value);
}
tilemap.CompressBounds();

```

---
Tags: unity, isometric
---