# Question
Title: Persistent save value, event after deleting savefile
Now, I now the title is really obscure, but I have tried to solve the following problem for so long and most of it is integrated into my game so far that I can't just copy & paste it here, so this is as simple as I can explain it:

I'm saving my data using NewtonSoft Json.

I basically have a singleton manager script that stores all quests in the game (`quests`), and all completed quests (`completedQuests`).

I use a property for getting all quests, since I don't want the base collection of every quest to ever change.

The `SaveData` class is what I am saving in Json.

```
public class GameStatistics : MonoBehaviour
{
    [Header("Settings:")]
    [SerializeField] private QuestTemplate[] quests;

    public QuestTemplate[] Quests
    {
        get { return quests; }
        private set { quests = value; }
    }

    public List<QuestTemplate> completedQuests { get; set; } = new List<QuestTemplate>();

    public static GameStatistics Instance { get; private set; }

    private void Awake()
    {
        if(Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }

    [System.Serializable]
    public class SaveData
    {
        [SerializeField] public List<QuestTemplate.QuestData> questDatas = new List<QuestTemplate.QuestData>();

        [JsonConstructor]
        public SaveData(List<QuestTemplate.QuestData> questDatas)
        {
            this.questDatas = questDatas ;
        }

        public SaveData()
        {
            questDatas = new List<QuestTemplate.QuestData>();
        }
    }
}

```

Every `QuestTemplate` also contains 2 other classes, one for messages that are shown once the quest is completed (`QuestMessage`), and one for all data that needs to be saved (`QuestData`).

As you can see there are 2 `QuestMessage` lists in total, this is because it isn't possible to save Dictionaries with complex keys properely with NewtonSoft Json, but I still need to know which message I am storing, so I put a whole list of `QuestMessage`s in there.

```
public class QuestTemplate : ScriptableObject
{
    [Header("Settings:")]
    public QuestData questData;
    public float timeLimit;
    public List<QuestMessage> messages = new List<QuestMessage>();

    [System.Serializable]
    public class QuestData
    {
        public string saveName;
        [HideInInspector] public float completionTime;
        [HideInInspector] public List<QuestMessage> messages = new List<QuestMessage>();
    }

    [System.Serializable]
    public class QuestMessage
    {
        public string headline;
        public string sender;
        [public string text;
        [HideInInspector] public bool read = false;
    }
}

```

This is my script I use for saving / loading:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using Newtonsoft.Json;

public static class SavingSystem
{
    private static readonly string SaveFileFolder = Application.persistentDataPath + "/Saves/";

    public static void Save(GameStatistics.SaveData data)
    {
        if(Directory.Exists(SaveFileFolder) == false)
        {
            Directory.CreateDirectory(SaveFileFolder);
        }

        string _savePath = SaveFileFolder + "Data.json";

        string _data = JsonConvert.SerializeObject(data, formatting: Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});

        File.WriteAllText(SaveFileFolder + "Data.json", _data);
    }

    public static GameStatistics.SaveData Load()
    {
        string _savePath = SaveFileFolder + "Data.json";

        if(File.Exists(_savePath) == true)
        {
            string _data = File.ReadAllText(_savePath);
            return (JsonConvert.DeserializeObject<GameStatistics.SaveData>(_data));
        }
        else
        {
            return(null);
        }
    }

    public static void DeleteData()
    {
        string _savePath = SaveFileFolder + "Data.json";

        if(File.Exists(_savePath) == true)
        {
            File.Delete(_savePath);
        }
        else
        {
            Debug.LogWarning("File doesn't exist.");
        }
    }
}

```

**The Problem:**

The saving to Json and loading from Json itself seems to be working alright, the problem is that whenever I am changing `read` (e.g. to `true` when the message has been read) the value seems to be persistent even when deleting the `Data.json` file, even restarting the game doesn't reset it, the only thing that managed to do that was restarting my PC completely.

I did some checks with `Debug.Log`s and it seems that whenever a message.read in the `completedQuests`' `questData`s is changed, that also changes the base array `quests`, which is then persistent until I restart my PC.

I have absolutely no idea what to do, I tried so many thing and I have literally spend like 3 days in total working on some sort of fix.

*If you have any idea what could be the problem, be it some strange behaviour of a list or array or the way my save structure is set up, please post it, at this point I am willing to try anything.*

# Answer
The problem you encounter comes from the fact that you use ScriptableObject. From the docu:

> A ScriptableObject is a data container that you can use to save large amounts of data, independent of class instances. One of the main use cases for ScriptableObjects is to reduce your Project’s memory usage by avoiding copies of values. This is useful if your Project has a Prefab that stores **unchanging** data in attached MonoBehaviour scripts.
>
> Every time you instantiate that Prefab, it will get its own copy of that data. Instead of using the method, and storing duplicated data, you can use a ScriptableObject to store the data and then access it by reference from all of the Prefabs. This means that there is **one copy** of the data in memory.

That means when you change the value of your quest at run time, your scriptable object gets updated. So your QuestTemplate should not contain things like completionTime or read. Instead give it a unique quest id. Now you can make a normal GameObject - or even better, use the plain old data structure (POD has the benefit that serializing and dezserializing becomes much easier), attach the values that you would like to persist/ that can be updated at runtime. Your save load function does not need to actually save things like the text in QuestMessage, you would store the id of quest XY and the status. This will make things as well easier when you want to implement different languages.
> 0 votes

---
Tags: unity, savegame, file, json
---


# Question
Title: How can I change the image used by a TileSet in Godot?
I have a tile set that uses an image. I want it to use a new image. The new image has a different name/path than the old image.

How do I tell the tile set to use the new image?

# Answer
> 1 votes
1. Go to the Tile Sets area (see bottom bar)
2. Select the Tile Set
3. Select the "Texture" dropdown
4. Change "Resource \> Path" to the new path

---
Tags: godot
---


# Question
Title: Can I use the music from an AI in my video game?
That's the song that Ai made specific for me, I'm only use the free version, so it is legal to use that song in my video game?

# Answer
Context matters. With any legal question, jurisdiction is important - different places have different rules.

Furthermore, "AI" is vague. What are the terms of use on the AI? No one answer here is likely to cover all the possible generative AI tools. Carefully read the label on any of the tools (AI or otherwise) that you are using.

Finally, there's also the platform to consider. For example, Steam is rejecting games with AI-generated artwork. Steam's publishing guidelines require you to use content you own or have adequate rights to use. The legal landscape for establishing adequate rights to content generated by the currently available AI tools is at best poorly defined. To that point, In January artists have filed a class-action lawsuit against various generative AI art companies over their use of their copyrighted art as training data. In February Getty Images filed a similar lawsuit. The outcome and its impact on establishing adequate rights remains to be seen. While the focus of that mostly seems to be on visual art, music is subject to the same complications.

Ultimately, legal advice comes from legal experts.
> 5 votes

# Answer
**tl;dr: Maybe? Nobody knows.**

Generative AI (GAI) is a new field, not just technologically but also legally. In the next years we are going to see a lot on how judges will apply existing laws and how legislators react to these decisions by making new laws.

Is the output of a GAI tool covered by copyright at all? The US copyright office says no, because they only protect the human input into a work. On the one hand, this would be good for game developers, because it means GAI works are free to use and GAI tool providers will have a hard time to use service terms to stop you. But on the other hand, that also means that GAI works are free for others to steal. So if you don't want someone else to use your AI-generated music, you will have to modify it in a way that fulfills the required creative threshold to be eligible for copyright.

But don't forget that the US copyright office is an executive organ. They just execute existing law. They don't have the authority to make laws, and their legal opinions on existing laws become irrelevant when judges decide otherwise.

And then there is the big elephant in the room: What about the copyright on the training data? Is it copyright infringement when a generative AI tool was trained on copyrighted material? GAI enthusiasts say no, because in their opinion a GAI learns just like a human does: By taking inspiration from work and using that inspiration to create something original. GAI skeptics say yes, because in their opinion GAI copies elements from the artworks it was trained with and then combines them into an amalgamated work that is a derivative of all these artworks.

Who is right? This is currently a subject of a class-action lawsuit against stable diffusion. We are probably going to see a lot of legal precedence on this subject in the coming years.

Until then, the answer is unfortunately: **¯\\\_(ツ)\_/¯**
> 3 votes

---
Tags: copyright, music
---


# Question
Title: Does GPU mipmapping assume the texture is gamma corrected?
I have been reading the ***Real Time Rendering*** book and stumbled upon this paragraph:

> For textures encoded in a nonlinear space (such as most color textures), ignoring gamma correction when filtering will modify the perceived bright- ness of the mipmap levels \[121\]. As you get farther away from the object and the uncorrected mipmaps get used, the object can look darker overall, and contrast and details can also be affected. For this reason, it is impor- tant to convert such textures into linear space, perform all mipmap filtering in that space, and convert the final results back into nonlinear space for storage.

I have never taken into account gamma correction for color textures using mipmapping.

For generating mipmaps I have always used the GPU-implementation (OpenGL):

```
glGenerateMipmap

```

In the resources I have learned from, gamma correction has not been mentioned as something that has to be taken into account for mipmapping.

I was wondering, since color textures that include gamma correction seem to be the norm, are the GPU-provided filtering functions already taking into account gamma correction?

# Answer
> 3 votes
Taking from the OpenGL 4.4 specification:

> The contents of the derived arrays are computed by repeated, filtered reduction of the levelbase array. For one- and two-dimensional array and cube map array textures, each layer is filtered independently. **No particular filter algorithm is required, though a box filter is recommended as the default filter**.

So we can see that this is farily weakly-specified, and details of how submips are filtered are left up to the implementation.

In other words: if you require gamma-correction you can't make any assumptions about how, or even if, your GL implementation will do it, so you will need to write your own miplevel reduction in software.

# Answer
> 2 votes
Some people in the comments pointed out some mistakes in my previous answer. This answer tries to fix all those issues. Thanks for the feedback!

Here is the new code.

I have chosen better images for the experiment this time.

This image has more high-frequency contrast changes.

And this is a extreme case: black and white checker 1-pixel grid.

Now the program uses more correct linear\<-\>srgb conversion formula:

```
#define SIMPLIFIED_SRGB_FORMULA 0
// https://stackoverflow.com/questions/61138110/what-is-the-correct-gamma-correction-function
static float linearToGamma(float x) {
    #if SIMPLIFIED_SRGB_FORMULA
        return powf(x, 2.2f);
    #else
        return x <= 0.0031308f
            ? x * 12.92f
            : powf(x, 1.0f / 2.4f) * 1.055f - 0.055f;
    #endif
};
static float gammaToLinear(float x) {
    #if SIMPLIFIED_SRGB_FORMULA
        return powf(x, 1.f/2.2f);
    #else
        return x <= 0.04045f
            ? x / 12.92f
            : powf((x + 0.055f) / 1.055f, 2.4f);
    #endif
};

```

The new program generates 4 images and compares them:

1. **cpu\_no\_conversion.png**: box filtering performed on the CPU, without any gamma conversions
2. **cpu\_conversion.png**: box filtering performed on the CPU, converting from gamma to linear, and back from linear to gamma
3. **gpu\_no\_conversion.png**: let OpenGL create the mipmaps, RGB format
4. **gpu\_conversion.png**: let OpenGL create the mipmaps, SRGB format

As you can see in the previous images, there are some visual differences if we do the gamma conversion or not. This is very obvious for the checkers sample image. But noticeable for the tent sample image as well.

OpenGL seems to be doing something similar to our gamma\<-\>linear conversion. So, at least in my system, OpenGL seems to be doing things right.

The program also prints a table with the difference between the generated images.

Meaning of the labels:

* CPU: downscale performed in the CPU
* GPU: downsample computed with OpenGL's glGenerateMipmap
* NG: doesn't do any gamma conversion
* G: converts from gamma space to linear when reading, and back to gamma when writing

For the tent image:

|  | CPU, NG | CPU, G | GPU, NG | GPU, G |
| --- | --- | --- | --- | --- |
| CPU, NG | 0 | 2102348 | 49224 | 2121146 |
| CPU, G | 2102348 | 0 | 2276882 | 10106 |
| GPU, NG | 49224 | 2276882 | 0 | 2295830 |
| GPU, G | 2121146 | 10106 | 2295830 | 0 |

For the checker image:

|  | CPU, NG | CPU, G | GPU, NG | GPU, G |
| --- | --- | --- | --- | --- |
| CPU, NG | 0 | 176947200 | 0 | 176947200 |
| CPU, G | 176947200 | 0 | 176947200 | 0 |
| GPU, NG | 0 | 176947200 | 0 | 176947200 |
| GPU, G | 176947200 | 0 | 176947200 | 0 |

For the checkers sample image, OpenGL perfectly matches the output of our CPU box-filtering in all cases (with conversion and without)!

For the tent sample image, it's doesn't 100% match but it's very close.

I performed the tests in Windows, and the RX6600 GPU.

---
Tags: opengl, color, mipmaps
---


# Question
Title: Why is rotationAngle not taking effect when changing it in the inspector?
I want to make it so that, when I'm changing the `rotationAngle` Range slider in the inspector at runtime, it will change the transform rotation angle, but it's not working. If I'm only changing it to 360 degrees then it's doing 360 rotation but then when I'm changing the slider back to any other smaller value it's not affecting it anymore.

And also, when changing the `rotationAngle`, then it's not rotating from side to side, it's rotating only in one direction. For example 360 then it keeps rotating only in one direction instead of changing direction when getting to 360.

It works only when running it for the first time, but then after that, the `rotationAngle` is not working as expected.

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

public class WeaponsController : MonoBehaviour
{
    [Range(0f, 100f)]
    [SerializeField] private float rotationSpeed = 10f;
    [Range(0,360)]
    [SerializeField] private float rotationAngle = 45f;

    private float currentAngle;
    private bool rotateClockwise = true;

    private void Update()
    {
        // Calculate the rotation amount based on the rotation speed and time
        float rotationAmount = rotationSpeed * Time.deltaTime;

        // Update the current angle based on the rotation direction
        currentAngle += rotateClockwise ? rotationAmount : -rotationAmount;

        // Check if the current angle exceeds the specified angle limit
        if (Mathf.Abs(currentAngle) >= rotationAngle)
        {
            // Reverse the rotation direction
            rotateClockwise = !rotateClockwise;
        }

        // Apply the rotation to the object
        transform.localRotation = Quaternion.Euler(0f, currentAngle, 0f);
    }
}

```

# Answer
> 0 votes
This is working as I expected. maybe there is a better way to write the script but it's working.

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

public class WeaponsController : MonoBehaviour
{
    [Range(0f, 1000f)]
    public float rotationSpeed = 10f;
    [Range(0f, 360f)]
    public float rotationAngle = 45f;
    public bool rotateClockwise = true;

    private float currentAngle;

    private void Update()
    {
        // Calculate the rotation amount based on the rotation speed and time
        float rotationAmount = rotationSpeed * Time.deltaTime;

        // Update the current angle based on the rotation direction
        if (rotateClockwise)
        {
            currentAngle += rotationAmount;
            if (currentAngle >= rotationAngle)
            {
                currentAngle = rotationAngle;
                rotateClockwise = false;
            }
        }
        else
        {
            currentAngle -= rotationAmount;
            if (currentAngle <= -rotationAngle)
            {
                currentAngle = -rotationAngle;
                rotateClockwise = true;
            }
        }

        // Apply the rotation to the object
        transform.localRotation = Quaternion.Euler(0f, currentAngle, 0f);
    }
}

```

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


# Question
Title: Trying to calculate hitbox vertices for my game and adding SAT collision
I am currently working on a basic HTML, CSS, and JavaScript game as a freshman high school summer project. I am currently trying to implement separating axis theorem (I spent a lot of time learning the math on khan academy in their linear algebra course because I didn't know what vectors and dot product were). It is for my player’s shield. I have been having a lot of trouble with it generally. But right now, I am just focusing on trying to locate the top left of the shield hitbox. I also draw the hitbox results out so I can see what is going on. The result is that the located hitbox is really far away, and just doesn't seem to really correlate to the top left corner of the hitbox at all. The equations I have been trying to use are:

```
  x′= xcos(θ)−ysin(θ)
  y′ = xsin(θ)+ycos(θ).

```

The following code is my attempt to locate the top left vertex:

```
const vertOne = {
        x: oneX + Math.cos(shieldAng + Math.PI/2) * oneRad,
        y: oneY - Math.sin(shieldAng + Math.PI/2) * oneRad
    };

    // Other vertex of shield
    const vertTwo = {
        x: oneX + Math.cos(shieldAng - Math.PI/2) * oneRad,
        y: oneY - Math.sin(shieldAng - Math.PI/2) * oneRad
    };

    const midpoint = {
        x: oneX + Math.cos(shieldAng) * oneRad,
        y: oneY - Math.sin(shieldAng) * oneRad
    };

    const center = {
        x: oneX,
        y: oneY - oneRad / 2
    };

    const rectOne = {
        get x() {
            let v1UnrotatedX = (((vertOne.x - center.x) * Math.cos(Math.PI / 2) - (vertOne.y - center.y) * Math.sin(Math.PI / 2)) + center.x);
            let v1UnrotatedY = (((vertOne.x - center.x) * Math.sin(Math.PI / 2) + (vertOne.y - center.y) * Math.cos(Math.PI / 2)) + center.y);
            let x = v1UnrotatedX + 2 * oneRad;
            let y = v1UnrotatedY + oneRad;
            return (((x - center.x) * Math.cos(shieldAng) - (y - center.y) * Math.sin(shieldAng)) + center.x);
        },

        get y() {
            let v1UnrotatedX = (((vertOne.x - center.x) * Math.cos(Math.PI / 2) - (vertOne.y - center.y) * Math.sin(Math.PI / 2)) + center.x);
            let v1UnrotatedY = (((vertOne.x - center.x) * Math.sin(Math.PI / 2) + (vertOne.y - center.y) * Math.cos(Math.PI / 2)) + center.y);
            let x = v1UnrotatedX + 2 * oneRad;
            let y = v1UnrotatedY + oneRad;
            ctx.strokeStyle = 'blue';
            ctx.strokeRect(v1UnrotatedX - 10, v1UnrotatedY - 10, 20, 20);
            return (((x - center.x) * Math.sin(shieldAng) + (y - center.y) * Math.cos(shieldAng)) + center.y);
        },

        width: 2 * oneRad,
        height: oneRad
    };

```

If you are interested in the rest of the code, I linked to it on GitHub below. The file for the code mentioned above is called collision.js. Thanks for reading, and any help is greatly appreciated!

**Resources I Have Been Using:**

How to calculate corner positions/marks of a rotated/tilted rectangle?

https://math.stackexchange.com/questions/270194/how-to-find-the-vertices-angle-after-rotation

https://stackoverflow.com/questions/62028169/how-to-detect-when-rotated-rectangles-are-colliding-each-other

https://www.youtube.com/watch?v=7Ik2vowGcU0&t=609s&pp=ygUXc2VwYXJhdGluZyBheGlzIHRoZW9yZW0%3D

https://www.youtube.com/watch?v=Nm1Cgmbg5SQ&t=620s&pp=ygUXc2VwYXJhdGluZyBheGlzIHRoZW9yZW0%3D

https://www.youtube.com/watch?v=Ap5eBYKlGDo&t=84s&pp=ygUXc2VwYXJhdGluZyBheGlzIHRoZW9yZW0%3D

http://programmerart.weebly.com/separating-axis-theorem.html

https://gamedevelopment.tutsplus.com/collision-detection-using-the-separating-axis-theorem--gamedev-169t

https://dyn4j.org/2010/01/sat/

https://www.khanacademy.org/math/linear-algebra/vectors-and-spaces (up to the video "Defining the angle between vectors" in lesson 5)

**My GitHub Page (all the code is here):**

https://github.com/Josh60169/Shape-Fight/tree/main/Shape%20Fight

# Answer
> 1 votes
After reading the code and guesswork, I've landed in that you have a rectangle defined by:

* A center point given by `oneX` and `oneY`
* A height given by `oneRad`
* A hardcoded aspect ratio of 2 to 1

Like this:

*Rectangle with dimensions `2 * oneRad` by `oneRad` centered at `(oneX, oneY)`*

---

And you want to compute the coordinates of the corners of the rectangle...

After rotating it by `shieldAng`, by a pivot placed at `(oneX, oneY - oneRad / 2)`. *Probably that is what you want. I'll solve this for an arbitrary pivot anyway, so if it isn't you can change it.*

But first, the coordinates of the corners *without rotation*:

```
let size {x: 2 * oneRad, y: oneRad};
let half_size = {x: size.x * 0.5, size.y * 0.5};
let center = {x: oneX, y: oneY};

let corners = [
    {x: center.x - half_size.x, y: center.y - half_size.y},
    {x: center.x - half_size.x, y: center.y + half_size.y},
    {x: center.x + half_size.x, y: center.y + half_size.y},
    {x: center.x + half_size.x, y: center.y - half_size.y}
];

```

And let us define a function to rotate them based on the answer of How to calculate corner positions/marks of a rotated/tilted rectangle?:

```
function rotate(vector, pivot, angle) {
    let tmp = {x: vector.x - pivot.x, y: vector.y - pivot.y};
    return {
        x: tmp.x * cos(angle) - tmp.y * sin(angle) + pivot.x;
        y: tmp.x * sin(theta) + tmp.y * cos(theta) + pivot.y;
    };
}

```

And we can get the rotated corners like this:

```
let size {x: 2 * oneRad, y: oneRad};
let half_size = {x: size.x * 0.5, size.y * 0.5};
let center = {x: oneX, y: oneY};

let pivot = {x: oneX, y: oneY - oneRad / 2};
let angle = shieldAng;

let rotated_corners = [
    rotate({x: center.x - half_size.x, y: center.y - half_size.y}, pivot, angle),
    rotate({x: center.x - half_size.x, y: center.y + half_size.y}, pivot, angle),
    rotate({x: center.x + half_size.x, y: center.y + half_size.y}, pivot, angle),
    rotate({x: center.x + half_size.x, y: center.y - half_size.y}, pivot, angle)
];

```

Change the `pivot` if it is incorrect. Add an offset to the angle if you need (e.g. `angle = shieldAngle + Math.PI / 2` or whatever).

---
Tags: collision-detection, javascript, separating-axis-theorem
---


# Question
Title: Would it be possible to make a Game Genie like program in Javascript?
Game Genie was a tool for the NES that allowed users to input codes that were able to drastically able to change the mechanics of a game by getting CPU reads and replacing the game's response with its own response. I have made a game in JavaScript using the HTML5 canvas and I want to try and make something like the Game Genie for my game but I have no idea where to start or if it's even possible. Any help?

# Answer
What exactly do you want to replicate from a Game Genie code?

The format of the original can be found in the docs here, but fundamentally they identified a part of the memory to change and the type of change to make.

Most commonly, that was "Fix the value in memory to always be X", but other operations were supported (like XOR-ing the value found in memory).

Whilst that doesn't map 1:1 to javascript, the core concepts are still valid.

At its most primitive, your "JSGenie" code could be `playerLives:fix:100`

Then on every frame, run through all the codes in use, extract the variable names, operations and values, then set the variables as appropriate.

If you want something a bit more game-genie-feeling with letters/numbers that aren't so human-readable, you've got a few different ways you can implement that.

Fundamentally, you'll want some way of mapping from "short alphanumeric code" (let's call it a key) to variable name.

Then your genie code becomes something like `a3c1:fix:100`. Of course, we can replace `fix` with a value to indicate the operation (let's sat "fix" is `0`)... `a3c1:0:100` (or even omit the operation entirely and only support fixing values ... `a3c1:100`)

There's really no limit to how you can format/pack the data. If you don't want to use colons, make the fields fixed-width, or bit pack them, or ...

You could also use hexadecimal (or any reversible operation) for the value itself, so it's not obviously `100`.

It depends entirely on how you want the code to look and function.

So ... How do we get the keys for the variable names?

Same again... It depends on how you want it to work.

At its simplest, you could have a hand-curated list of variables and their associated keys.

This is easy to control, but somewhat limited and a bit error-prone.

Genie codes can only modify variables manually added to the list, and any time a variable name changes, this list has to be updated.

At the other end of the spectrum, you can get Javascript to tell you all currently defined variables, then hash their names in some way to get a key.

The benefit of this approach is that it's self-maintaining and the codes can change literally any value in the runtime.

The downside is that they can change **literally *ANY* value** in the runtime.

(Much like the original Game Genie).
> 5 votes

---
Tags: 2d, javascript, html-canvas
---


# Question
Title: Getting coordinates within a bezier space
I have created an object that is comprised of two bezier curves (constructed of an identical finite segments equal to a variable named `resolution`). The two curves are then tessellated and filled in with a shader.

I would like to adjust shading within it based on a pixel's position relative to the object's coordinates (ie. a stripe along the middle would follow the curvature of the bezier curves.

My current approach simply breaks down the curve into a finite number of segments and then colors each pixel depending on its proximity, although this does not work because the scene will lag with even one of these objects if it has a resolution of 40+. Even if I could go to some arbitrarily large resolution, I am still unsure of how to "dynamically" color a pixel depending on it's *relative* height within the polygon. If there were a function to find the x or y coordinate relative to the curve's geometry (I assume normals play a role) then I would be pleased, because even if I did optimize my code as it is it is: it would not be seamless and I would have to have an arbitrarily and wastefully high resolution to guarantee a good look.

An algorithm that's reasonably efficient for 2\> pixel accuracy for about 500,000 pixels worst-case scenario would also be equally helpful in place of a function that spits out an exact answer. I am more concerned about the effect being consistent than it being accurate as it is for visual purposes.

## Polygon with unmodified x-axis shown:

## Polygon with modified x-axis modified, f(x):

It is quite easy to brute force the solution by simply lerping between the curves A and B and filling them in until the entire polygon is filled, but a **solution** would require a function that would go backwards, translating each pixel coordinate into a point along an intermediary bezier curve as shown in f(x), ultimately letting me call f(x, y) to get the x, y within the polygon's space so that an image would fit exactly to the curvature of the bezier curves.

If the solution is significantly more simple with a quadratic bezier curve then I may go for that instead, as I am unsure if cubic is necessary.

# Answer
There is the formula to find Y and Z coord based on X value: t = (X-Pstart.x)/(Pend.x-Pstart.x);

you get the Bezier(t) Point where Bezier(t).X==X;
> 0 votes

---
Tags: shaders, algorithm, glsl, curves, beziers
---


# Question
Title: WebGL FPS is sometimes higher than max. FPS setting - why?
In lots of WebGL online games (all games I tested were made with Unity), my FPS is sometimes higher than the max, FPS setting of my PC (75), but why?

# Answer
There are multiple rates being measured here.

The game is telling you how many times it's redrawing the scene with a frame that *could* be displayed.

Every 1/75th of a second, your computer refreshes your screen and displays the most recent frame.

If the game were running at 150 FPS and your screen at 75Hz, you'd be seeing *roughly* every other frame generated by the game.

This disconnect happens because WebGL (or other window-mode games) don't take full control of the display, so the OS is still responsible for redrawing the screen as a whole. It then uses one of several methods to render the game content (sometimes it uses a buffer and treats it like any other window content, other times it offloads to the GPU for the render directly).

Which method it uses depends how the game's been written, what the GPU and OS support, whether hardware acceleration is used, etc, etc.
> 0 votes

---
Tags: performance, webgl, frame-rate, lag, unity-webgl
---


# Question
Title: How are gameplay animations described to an animator before they are made?
I'm working on a fangame project as an animator and I got a list of animations to make that looks like this:

* Idle
* Run
* Punch
* Swim
* etc.

Now, an anim like Idle or a walk cycle will be fairly obvious in how should it look like without further description, but a "Punch" will need to be defined by something more than the word itself, while run animations can have multiple variations depending on character's speed (which is notable in TPP console games due to to them using analog stick).

So this list automatically raises the following two questions:

1. How do you establish what animations will your game require? I know they will be based on the animation states, but that's all I can guess - unless I answered my own question right there and that's entirely dependent on whatever system is designed with the animation state machine in the game.
2. Is there a standard for describing gameplay animations to an animator so that he knows how should they look, and especially what are the limitations and expectations, like how long should it be, what animations should precede it and succeed, etc. In other words, in the above list, what information should each animation contain before it is handed over to the animator? Is there a industry-standard template or term for that? I'm assuming there isn't one, but I would expect some factors/data to appear over and over again, kind of like with Game Design Docs.

This is my first time making an entire set of animations for a video game, so I don't really know what questions should I ask.

# Answer
If I'm understanding correctly, you are an animator, but are writing your questions from the perspective of a project manager or team leader, rather than from your own perspective. So my answers are written from the same perspective as your questions.

> 1. How do you establish what animations will your game require?

With planning. Sit down with a notepad or your word processor, and write down all of the actions you want players to be able to take and what animations will be required.

Next, draw a state machine flowchart which includes all of the actions/animations, and any necessary transitions between them. Not only will this help you, but you can give it to the animator so they understand how everything fits together.

Later on, you'll most likely realize there are additional animations that you need which you didn't think of. That's fine; just update your flow chart.

> 2. Is there a standard for describing gameplay animations to an animator so that he knows how should they look?

With illustrations. Depending on the skill set of the team, you might give the animator storyboards, or you might even draw a rough 2D animation that conveys the motion you want the animator to reproduce in 3D.

If you don't have anyone on the team with any illustration experience, but the animations are for a humanoid character, you can record a video of someone acting out the animation. Or, you can search the web for similar animations to use as references. If you absolutely can't provide any better form of reference, you can try a detailed description, though some artists don't make much effort to follow the details of a complex description.

After working with an animator for a while, you'll most likely get into a rhythm where the animator has a good idea of how you want things to look and doesn't need as much reference material to nail down an animation.

---

Additional thoughts for you as the animator:

In some cases, an inexperienced team won't have much idea what kind of animations they'll need, and won't be able to answer many questions or provide flowcharts/illustrations. In that case, you should have a serious discussion with the team to figure out what kind of workflow they're looking for. They might be happy for you to come up with a set of animations that you think are adequate and then they'll tweak gameplay as needed to work with those animations. Or they might want you to throw together a bunch of sloppy placeholder animations and later they'll decide what they really need and ask you to refine it.

The worst case scenario is that the team is very hands on but has no idea what they actually want. In that case, you're likely to waste a lot of time making animations that never get used, or making endless revisions to certain animations (which still might never get used). In this type of situation, unless they are paying you hourly and you don't mind the work, you'll need to set some ground rules about how many animations you'll make and how many revisions you're willing to do per animation.
> 2 votes

# Answer
I'll be focusing on game play animations. Also, I'll assume there might be things they haven't figured out (given that it is a fan game, I have no idea how well organized the project is).

Before we get into that, I want to mention that cinematic animation is probably story-boarded and blocked out in engine. And also that you would have stronger direction for it (what the characters want and feel), and there is a known camera shot for every animation. *And it might require to animate to voice recordings.*

Also know there might be animations that don't get used, and animations that don't get done in time. In general we should minimize those cases... But don't see animations unused as wasted effort. They might still use them in an expansion of the game, and you are gaining experience. *And as long as you get paid, that is all good. Also unused animations might still be portfolio for you.*

---

**The job of game play animation is to communicate**

What do they communicate?

* The state of the character to the player. So you will have animations for different states, and they ideally they should be easy to read - usually that would mean good silhouette, but since the camera might not be fixed, you need to look at them from many angles and make sure it is understandable what the character is doing.
* The personality of the character. So you will have some global direction about the character that applies to all the animations. Caveat: Animation might be reused between multiple characters, so it is often key characters that get special treatment.

Without breaking immersion (so the animation needs to convey physicality and work in context with the rest of the game).

---

Sure, there are animation states. But before there are animation states, there might be states (i.e. the character controller is implemented as a state machine, and they know in advance which are the states and which are the transitions between them).

And to be begin with you want to communicate in which state the character is with animations. But also, the animations must blend together well... So they might tell you to start or end the animation in specific poses.

In fact, they might also decide it is better to create blending animations, which are not attached to a state, but to a transition between states.

I'm assuming this is beyond your role, so they would have decided this before it gets to you.

---

**How to describe animations**

I'm unaware of an industry standard to describe game play animations (and being a fan game, I don't know if they'd follow one if there were). Thus, you need to talk.

Ideally they give you animation references for what they want you do to. They might not have them, and instead convey the animation via descriptions, and gesturing in the air. But references is what you want, ask for references.

*Here being a fan game is likely to have a strength: They probably have references, because they are fans of the thing they are making the game based on, so they can reference that thing.*

Perhaps they don't know what they want, or nobody knows how or has put the effort to get a good reference, or whatever. In which case you would have to find - or make - them yourself. I would suggest to consider them as proposals, because it might not be checking if the references match what they want, but discovering together what to do instead.

What kind of references? They might be animations in other video games (if it is a fan game of another video, that should not be a problem). Or something sketched on pencil and paper - as storyboard or even a flip-book. But nothing beats video of the actions being performed (which will have correct and realistic physicality).

*Barring live action video, I submit to your consideration: toys. Put a smartphone on a base, have it record video, and do the animation with a toy in front of the camera, and use the resulting video for reference.*

With that said, don't expect references to be perfect. I remind you that they are not a replacement for the actual animation. So they come with notes attached (e.g. "it is like that, but faster", "like this, but keeping the head upright", you get the idea).

Be aware that they might be expecting to iterate with you on the animations. So you make animations that do what they ask, and you show them, and they tell you tweak them one way or the other, and repeat.

---

Yes, there might be a duration requirement. I want to put emphasis that there might not be an animation length specified for every animation. Because sometimes they don't know and will work around what you do, and sometimes the plan always was to speed it up or slow it down in engine according to what they need. But, I assure you that if you ask for a duration range (how short is too short, and how long is too long) they have a good idea.

---

As I was saying above, they should tell you if the animation needs to start or end in specific poses.

They should also tell you if the animation is a cycle. And I don't just mean if they loop (e.g. they start and end on the same pose), but if they represent an steady continuous motion.

In fact, they might want to break animations in three. For a run animation, it might be:

* Speed up
* Cycle (and this part should loop)
* Slow down

For an attack animation, it might be:

* Windup
* Strike
* Recovery

This not necessarily mean to split the animation and give three instead of one (unless they ask for that), but there will be specific times in the animation (e.g. they tell you how much time the windup should last, and so on).

---

And, yes, some animations will have variations. For example, there might be different idle fidgets that will be played at random.

It is a good idea to agree proper names to the variations, so you can communicate better. For example, in the case of running at different speeds, English has plenty of movement verbs to use, such as: stroll, walk, jog, run, sprint, dash.

---

**Is "Punch" a good description?**

"Punch" might be OK as description. It depends on the game. You have a wide range from tactic games to fighting games.

For some games any kind of hit forward is OK - even a kick might be OK, as long as it conveys that the character is hitting forward, and works well with the character personality. *But, I'd stick with what they said. They said punch, then it is punch.*

For other games you would need a description of the kind of punch... Is it a hook, an uppercut, a jab...? They probably mean a jab, but you might ask.

For some games it might even matter if the punch is skewed up or down, or even left or right. Either because there are different mechanics attached to that, or because this allows them to blend them to make the character punch in an specific direction.

However, given that they just said "Punch", it is likely that the specific kind of punch does not matter. Because in the cases it matters, there would likely be multiple punch animations, each with a different description. But, again, you might ask.

*Addendum: Consider the case where it does not matter as an opportunity to inject the personality of the character.*
> 1 votes

---
Tags: animation, animation-states
---


title: Add Existing Animation

text:
# Question
Title: Add Existing Animation
I have several animations that I am using on a GameObject. I switched the folder they were stored in, and they got detached from the gameObject. How can I add the existing animations to my gameObject without having to recreate them?

I am not looking to do this programmatically. I just want to undo the damage I have done without having to start over. Ideally, I want a "Load Animation" option from the Animator window in the editor, but that does not appear to exist :-/.

# Answer
Here is how I fixed the same issue:

1. Open the animator window
2. Click on the game object that has the animation
3. In the animator window for that game object, the original animations you set should still be there. Click on one of them.

4. In the inspector, there is a property called "Motion" where the animation from your new animation folder should be. Drag and drop it there and it should start working the same as you had it before.
> 3 votes

# Answer
Just drag the animator controller that has your animations in it to the Animator on your game object you should be able to access your animations again.
> 2 votes

# Answer
If I understand correctly, you want to add existing animations to a new animator controller on your game object but don't have the older animation controller for some reason? If so, drag and drop the existing animations onto the new animation controller in the animator window. You will have to create parameters and transitions again. If you have the old animation controller just drag and drop it onto the game object in the inspector, it will have all existing transitions and animation states.
> 0 votes

---
Tags: unity, animation, loading
---


# Question
Title: Is there a way to reimport an asset with new import options?
I'm trying to help out a friend with an Unreal issue. He has a character model that's been imported and used in a map. A bunch of work has already gone into setting up the scene before anyone noticed that the model was imported without morph targets, because for some bizarre reason Unreal's FBX importer has morph target import turned off by default and hides the option behind an "advanced options" section so you don't even notice it.

UE4 does offer the ability to reimport an asset, or even to reimport the asset with a new file, in the asset's right-click context menu, but neither of these actually fixes the problem because they don't pull up the import options dialog box that you get when importing a new model! This makes it impossible to reimport the model with the morph targets turned on.

I could import the FBX as a new asset, which would give the import options box, but the existing asset is already in use, in multiple different places, and there doesn't appear to be any easy way to tell it "replace all instances of *this* model with *that* model."

Is there any good way to fix this that doesn't involve tearing everything down and rebuilding it from the ground up?

# Answer
> 1 votes
You can re-import it using a different name then delete the existing, incorrect model.

Unreal will check that the model is in use and warn you about deleting it but one of the options is replace references.

You can now choose your newly imported character and Unreal will take care of the rest.

# Answer
> 1 votes
Open your asset by double-clicking on it in the assertbrowser, so you see it in the mesh viewer. Then in the "Details" tab, scroll down to "Import Settings" (quite far down). After you changed your settings, reimport the mesh to apply the changes.

You can reimport by selecting the "Asset" menu in the assertbrowser and selecting 'reimport', or by right-clicking on the asset in the content-browser and selecting 'reimport'.

---
Tags: unreal-4, unreal, import
---


# Question
Title: Grouping "touching" nodes of the same color together
I am trying to make a very simple game that allows the user to tap on any "block" in the scene and "pop" it. If the block is blue and touching another blue block then both blocks should be removed.

Basically I am trying to figure out how to "group" the blocks of the same color and remove them all when one of them is touched.

Does anyone have any ideas on how to accomplish this?

I tried using collision tracking to group the blocks, but that didn't seem to do the trick:

```
private func collisionBetween(box1: SKNode, box2: SKNode) {
        var blue: [SKNode] = []
        var red: [SKNode] = []
        var green: [SKNode] = []
        var yellow: [SKNode] = []
        var orange: [SKNode] = []

        if box1.name?.contains("blue") != nil && box2.name?.contains("blue") != nil {
            blue.append(box1)
            blue.append(box2)
            blueGroups.append(blue)
        }
        if box1.name?.contains("red") != nil && box2.name?.contains("red") != nil {
            red.append(box1)
            red.append(box2)
            redGroups.append(red)
        }
        if box1.name?.contains("green") != nil && box2.name?.contains("green") != nil {
            green.append(box1)
            green.append(box2)
            greenGroups.append(green)
        }
        if box1.name?.contains("yellow") != nil && box2.name?.contains("yellow") != nil {
            yellow.append(box1)
            yellow.append(box2)
            yellowGroups.append(yellow)
        }
        if box1.name?.contains("orange") != nil && box2.name?.contains("orange") != nil {
            orange.append(box1)
            orange.append(box2)
            orangeGroups.append(orange)
        }
    }

```

# Answer
> 0 votes
Turns out that this is extremely simple in Swift:

```
private func getMatches(from startBlock: BlockEntity) {
    for body in startBlock.physicsBody!.allContactedBodies() {
        guard let block = body.node as? BlockEntity else { continue }
        guard block.color.accessibilityName == startBlock.color.accessibilityName else { continue }
        if !matchedBlocks.contains(block) {
            //print("MATCH!")
            matchedBlocks.insert(block)
            getMatches(from: block)
        }
    }
}

```

The important portion here is the ".allContactedBodies()". That is a built in function for detecting any touching "nodes".

---
Tags: ios, spritekit, swift
---


# Question
Title: Store and call multiple functions consecutively
I am looking to create a "stack" of functions that I can call at will. In my game, multiple events can trigger at the same time. These things should not be shown at the same time however, and only happen 1 after the other.

These functions can come from multiple different GameObjects, but I would like to store the reference in a central place and call them from there.

**Example of what I'd want**

```
List<FunctionReference> fr = new List<FunctionReference>();

void AddFunction(FunctionReference f)
{
    fr.Add(f);
}

void CallNextFunction()
{
    if(fr.Count > 0){
        fr[0].CallAndExecuteThisFunction();
        fr.RemoveAt(0);
    }
}

```

*In a different GameObject*

```
function ExampleFunctionThatHasBeenStored()
{
    Debug.Log("Execute all things");
    StoredFunctionList.CallNextFunction();
}

```

**What I tried**

* I read about SendMessage which is heavily cautioned against, and also only invokes functions from the same GameObject.
* I read about Events, but I am unsure if this is what will solve my problem.

**How should I go about approaching this setup?** And also to keep in mind parameters involved in the call.

# Answer
What you are looking for is a C# feature called delegates.

A delegate is a variable that holds a reference to a method. You can store a reference to a method in such a variable, change which method is stored in it, and execute the currently stored method at a later time, passing whatever data you have available at that time as arguments.

The C# standard already implements some generics that cover the most common use-cases. For example the delegate `Func<TResult>` that can be used to hold a call to any function that takes no arguments but returns one. Or the delegate `Action` that represents a method that does not return anything. Both `Action` and `Func` also have variants with multiple additional parameters. For example a `Func<string, int, float, int>` can hold a function that takes an string, an int and a float as parameters and returns an int. Or a `Action<GameObject, Transform>` represents a method that has no return value but takes a GameObject and a Transform. These two families of delegate templates cover almost all use-cases. So making your own delegate types is usually optional and only required if you want some extra type safety.

For example, if you want to have a script that is supposed to contain "canned calls" to multiple functions that return integers and can then return the sum of the return values when all those functions get executed could look like this:

```
class FunctionStack() {
    private List<Func<int>> functions = new List<Func<int>>();

    void AddFunction(Func<int> function)
    {
        functions.Add(f);
    }

    int GetResult()
    {
        int ret = 0;
        foreach(Func<int> function in functions) {
            ret += function();
        }
        return ret;
    }
}

```

Feeding that class with functions can be done via methods or via lambdas:

```
FunctionStack instance = new FunctionStack();

// add a lambda expression that returns 4
instance.AddFunction(() => 4);
// add a lambda function that returns 7 + 3
instance.AddFunction(() => { return 7 + 3; });
// add a call to an existing function.
// Note the missing () behind the function name.
instance.AddFunction(someObject.SomeMethodThatReturnsAnInteger);
// if you want to call an existing function with arguments, then you need to
// wrap those in a lambda:
instance.AddFunction(() => { return Mathf.FloorToInt(transform.position.x); });

// note that none of the functions above get executed until you do this:
Debug.Log(instance.GetResult());

```
> 2 votes

---
Tags: unity, c#, software-engineering
---


title: How to get materials from objects?

text:
# Question
Title: How to get materials from objects?
```
for (int i = 0; i < waypoints.Length; i++)
        {
            foreach (Transform g in waypoints[i].GetComponentsInChildren<Transform>())
            {
                if (g.GetComponent<MeshRenderer>() != null)
                {
                    meshRenderers.Add(g.GetComponent<MeshRenderer>());
                }

                if(g.GetComponent<Material>() != null)
                {
                    materials.Add(g.GetComponent<Material>());
                }
            }
        }

```

I can get the MeshRenderer from each object children there are like 1000 MeshRenderers.

and in the editor, I can see that each child with MeshRenderer also have a material component. for example:

I want to get also the Material from each child if there is any material but I'm getting 0 items in the materials List.

later on I want to manipulate the materials but first I can't even get them to a List.

# Answer
Although the inspector lists the materials below the components of a gameObject, Materials are not components. So `GetComponent<Material>` is never going to return anything. The materials used by a Renderer are managed by the Renderer classes themselves and accessed through the scripting API of the `Renderer` class.

You can transfer the materials from one object to another like this:

```
 var materials = new List<Material>();
 object1.GetComponent<Renderer>().GetMaterials(materials);
 object2.GetComponent<Renderer>().SetMaterials(materials);

```

> later on I want to manipulate the materials

If that modification is only minor (as in you are changing a single texture or a single color), then I would recommend to keep the materials as they are, but override individual material properties for each renderer using a MaterialPropertyBlock.
> 1 votes

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


# Question
Title: In platformer video games, what is the term for the size of the character on the screen?
In 2D platformer games, what is the term or word for determining the size of the player character on the screen?

For example, the player character in *Castlevania: Symphony of the Night* is very small on the screen.

# Answer
> 3 votes
While I agree that there's no consensus to define *a character's size relative to the screen* with a specific word, you can always relate two homogeneous quantities by defining a **ratio** between them. Now you can use your brand-new *player-to-screen* width/height ratio and incorporate it in your design.

Most engines use **world units** to give meaning to spatial measurements internally, but this doesn't prevent you to define your own unit of measurement for designing levels, objects, obstacles, etc. In fact, computing a ratio can also answer "*How many of X fit in Y?*" so you're expressing the screen width/height in terms of your character size.

As a designer, you want your numbers to assume values that achieve your game design goals. Your units of measurement are your own, and you can call them whatever you want:

* "My character is 1x2 **CharSquares** when standing up."
* "This chasm is 4 **Crates** wide, and my character is 1 **Crate**. If they run at 2 **Crates/second** top, they should be able to jump over it without falling."
* "Player's avatar is 2 **Tiles** wide, and I want their maximum view distance to be 15 **Tiles** on either side. Therefore, I need to fit my camera to a total width of 32 **Tiles** horizontally, and doing so will result in a vertical viewing distance being..."

---
Tags: platformer, terminology, screen
---


# Question
Title: What are good ways to make modular corridors and interiors of buildings?
I would like to make modular corridors and some other objects in my level, to make it easier to construct them.

* Do I separate walls, floor, and ceiling or make a tube module?
* How to avoid seams between modules?
* How to deal with the edges of those elements?

Take the wall panel, should it be a polygon (no thickness) or a solid block?

# Answer
> Do I separate walls, floor, and ceiling or make a tube module?

A tube module will be fairly restrictive — you won't be able to add doors anywhere in it without swapping out the entire module, for example. You should probably go for separate surfaces unless your game's style definitely won't need it or benefits from single modules.

> How to avoid seams between modules?

* One approach is to make sure the geometry of all your modules lines up perfectly, and the edges of two modules meet perfectly — each vertex from one having the same position, down to the last digit, as its matching vertex from its neighbor. This would be suitable if you are procedurally generating a world in a custom engine or at least a custom mesh generator; if you are placing separate objects in a general-purpose engine it may not be achievable.
* If two identically-themed modules are joining, then you can have them just overlap each other a bit — as long as **the surfaces have the exact same texture at the exact same position** (you'll need a texture designed for repeating), there will technically be Z-fighting but it won't be visible.
* You can provide some kind of geometric feature to cover up seams. In real-world buildings, **molding** serves this function — small strips that cover up the joint between two flat surfaces that aren't perfectly identical or perfectly fitted to each other.

Molding can also help create transitions between different styles of modules — it won't hurt for its models to intersect the walls. Similarly, a doorway in a wall is especially good at covering up such a transition — the modules on each sides of the door will slightly intersect the wall to ensure there are no gaps.

I'm calling this stuff molding because the real-world function matches, but you don't have to limit yourself to the possibilities of real-world materials or ones that are intended for this purpose. Any object that can cover up the gap will work. Columns/pillars are also “molding” for this purpose.
* If you don't want visible molding and the textures won't match perfectly, then you could design intersecting flanges into each part:

The flanges' vertices should have the same normal as the rest of the surface so they are lit the same, not like an actual groove. The angle at which they cross should be sufficiently far from parallel to avoid Z-fighting. But no matter what, you will still have a somewhat visible seam as long as the textures don't match; the human eye is good at picking out borders where patterns change. This might be a good choice if you are intending to render “this part of the walls was intentionally painted a different color”, for example.
* In a dimly lit, or cartoon, scene you can have the junction between modules just disappear into darkness — make flanges or overlaps as above, but make the texture shade into pure black at the edge. Then it doesn't matter exactly how the geometry meets (as long as there isn't a gap) because pure black cannot reveal any details.

In any of these cases where the module is slightly large on purpose, **make sure to choose a grid size**, a standard length, and make sure that the modules are *bigger* than that by the intended overlap amount. Don't build a module of exactly a certain length and then fudge how you position them.

> How to deal with the edges of those elements? Take the wall panel, should it be a polygon (no thickness) or a solid block?

Depends on your style.

* If your game takes place entirely or mostly indoors, then leaving out back-sides will be efficient to render and allow you to easily have walls that have different styles on their two sides.
* If it is possible to get an outside view of the walls, such as in an open-topped “hedge maze” or a destroyed building, then you'll need those back sides.

In some cases it might make sense to build both — you could perhaps make double-sided walls (modeling them as solid physical objects), and then make a copy which has the back side deleted.
> 1 votes

---
Tags: unity, models, gameobject, level-design, levels
---


# Question
Title: PyGame moves object in one direction but not in the opposite one
I'm having trouble with a PyGame animation I'm writting. I have a `Ball` class that defines an object that moves on the screen and bounces on the edges. I initialize the class with a direction attribute that tells the ball in which direction to move. However, I've noticed two problems:

* The first one is that when setting the direction to `Vector2(1, -0.1)`, the ball moves in the expected direction: up and to the right. However, if I set the direction to `Vector2(1, 0.1)`, the ball just moves horizontally.
* The second issue is that I'm moving the object doing `ball.rect.center += ball.direction * dt * ball.speed`, so `ball.speed` shouldn't change the direction of motion because it is a scalar. However, it does, and I can't figure out why.

I've noticed these two issues when I saw that the ball bounces correctly on all sides except on the top edge (when it reaches that point it just starts moving horizontally). This behaviour happens for a direction equal to `Vector2(1, -0.1)` and for a speed of `300`, but not for other values (at least not that I've noticed).

Here is a minimal working example:

import pygame
from pygame.math import Vector2
import sys

class Ball:
    def __init__(self):
        self.image = pygame.Surface(size=(16, 16))
        self.image.fill("#FFFFFF")
        self.rect = self.image.get_rect()

        self.screen = pygame.display.get_surface()
        self.screen_width = self.screen.get_size()[0]
        self.screen_height = self.screen.get_size()[1]

        self.speed = 300.0
        self.rect.center = Vector2(0.5 * self.screen_width,
                                   0.5 * self.screen_height)
        self.direction = Vector2(1, -0.1)
        self.direction.normalize_ip()

    def render(self):
        self.screen.blit(self.image, self.rect)

    def move(self, dt: float):
        self.rect.topleft += self.direction * dt * self.speed

        # Bounce on the edges of the screen
        if self.rect.right > self.screen_width:
            self.direction.x *= -1
            self.rect.right -= 2 * (self.rect.right - self.screen_width)
        if self.rect.left < 0:
            self.direction.x *= -1
            self.rect.left -= 2 * (self.rect.left - 0)
        if self.rect.top < 0:
            self.direction.y *= -1
            self.rect.top -= 2 * (self.rect.top - 0)
        if self.rect.bottom > self.screen_height:
            self.direction.y *= -1
            self.rect.bottom -= 2 * (self.rect.bottom - self.screen_height)

class Animation:
    def __init__(self):
        pygame.init()

        self.resolution = (1920, 1080)
        self.pixel_depth = 32
        self.window_name =  "Bouncing Ball"
        self.fps = 50

        # Setup screen
        self.screen = pygame.display.set_mode(
            size=self.resolution,
            flags=pygame.FULLSCREEN,
            depth=self.pixel_depth)
        pygame.display.set_caption(self.window_name)

        self.clock = pygame.time.Clock()
        self.dt = 0

        # Initialize game objects
        self.ball = Ball()
        self.movement_range = (0, self.resolution[0])

    @staticmethod
    def _quit() -> None:
        """
        This method quits the animation and closes the window.
        """
        pygame.quit()
        sys.exit()

    def _check_passive_events(self) -> None:
        """
        Handle the events loop.
        """
        for event in pygame.event.get():
            # Quitting
            if event.type == pygame.QUIT:
                self._quit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self._quit()

    def run(self):
        while True:  # Main loop

            # Events
            self._check_passive_events()

            # Game logic
            self.ball.move(self.dt)

            # Screen update
            self.screen.fill("#000000")
            self.ball.render()

            self.dt = self.clock.tick(self.fps) / 1000.0
            pygame.display.flip()

if __name__ == "__main__":
    animation = Animation()
    animation.run()
```

# Answer
Okay, so I found the answer in a post from another community. It turns out I was trying to move the Rectangle using distances that were below 1 and since PyGame only allows the use of ints in the position of a Rectangle, the change didn't do anything. More details can be found here.
> 1 votes

---
Tags: movement, python, pygame
---


# Question
Title: How to prevent rendered wound from sliding on moving character?
I am trying to display a rendered wound on the character, but I still can't figure out how to display it properly without sliding on character's body.

I'm following this link on rendering the wounds on characters but I still can't figure out why it isn't working.

This is what I have so far on rendering the wound based on hit location

What have I done wrong? Any ideas is appreciated. Thanks!

p.s This is how I draw the wound based on hit location.

**UPDATE:** So I replace WorldPosition into Preskinned Position based on the comment suggested and the sphere mask won't render at all. I thought my HitLocation must be the problem, so I get back to the linked post to understands better on how to approach this, and included some C++ as well, but all those still resulting in the same results. The sphere mask keep on sliding on the body.

This is the code I have been using for both callable functions above

```
//Recursive function to have results relative to world origin
FTransform UGestureMathLibrary::GetWorldSpaceTransform(FReferenceSkeleton RefSkel, int32 BoneIdx)
{
 FTransform BoneTransform;

 if (BoneIdx > 0)
 {
  BoneTransform = RefSkel.GetRefBonePose()[BoneIdx];

  FMeshBoneInfo BoneInfo = RefSkel.GetRefBoneInfo()[BoneIdx];
  if (BoneInfo.ParentIndex != 0)
  {
   BoneTransform *= GetWorldSpaceTransform(RefSkel, BoneInfo.ParentIndex);
   UE_LOG(LogTemp, Warning, TEXT("if parent index is not equal to zero"));
  }
 }

 return BoneTransform;
}

//Reference pose bone transform
FTransform UGestureMathLibrary::GetRefPoseBoneTransform(USkeletalMeshComponent* SkelMesh, FName BoneName)
{
 FTransform BoneTransform;

 if (SkelMesh && !BoneName.IsNone())
 {
  SkelMesh->ClearRefPoseOverride();
  FReferenceSkeleton RefSkel;
  RefSkel = SkelMesh->SkeletalMesh->RefSkeleton;
  BoneTransform = GetWorldSpaceTransform(RefSkel, RefSkel.FindBoneIndex(BoneName));
  //BoneTransform = RefSkel.GetRefBonePose()[RefSkel.FindBoneIndex(BoneName)];
 }

 return BoneTransform;
}

//Bone transform
FTransform UGestureMathLibrary::GetBoneTransform(USkeletalMeshComponent* SkelMesh, FName BoneName)
{
 FTransform BoneTransform;

 if (SkelMesh && !BoneName.IsNone())
 {
  FReferenceSkeleton RefSkel;
  RefSkel = SkelMesh->SkeletalMesh->RefSkeleton;
  BoneTransform = SkelMesh->GetBoneTransform(RefSkel.FindBoneIndex(BoneName));
 }

 return BoneTransform;
}
```

Am I missing something?? Thanks again!

# Answer
I know this is a super old question, but I'm researching this exact topic and I think I can point out a mistake above. The preskinned location node needs to be used in the material used for unwrapping the mesh. That allows for baking the preskinned location, instead of the absolute world location, into that render target. The unwrapped texture from that target can then be made into a static texture. Then you can use the method, those c++ functions, for for converting the transform/location into the space that gets sent to your sphere mask. That's from the original Tom Looman post.
> 2 votes

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


title: What is a pure ECS?

text:
# Question
Title: What is a pure ECS?
What is a "pure" ECS? What makes an ECS pure or not?

---

Although the term appears to have come up since as early as 2013 in this community, it appears that often, a user asking a question feels the need to explain it. Is there a common, globally accepted definition of what a pure ECS is, so that we would not need to explain it every time?

# Answer
> 13 votes
A pure Entity - Component - System architecture means that:

* Every object in your game is an **Entity**. However, an entity itself has neither any data nor any code. It is an abstract concept not represented by any data structure. It is just an ID number. There is no "class Entity".
* All the data about the entities in your game is in **Components**. A component is a "dumb" data container without any executable functions. Each component is assigned to an entity (However, some ECS architectures do allow multiple entities to share a component and/or singleton components which do not belong to any particular entity)
* All your executable game logic code is in the **Systems**. A system might hold data which is relevant to the system itself, but no data about the entities it processes. All entity-specific data belongs into components.

However, keep in mind that seeking pureness just as an end in itself can become counter-productive. Architectural patterns are guidelines, not religious dogmas. Sometimes it can make sense to add a small utility method to a component in order to avoid code duplication between systems. Sometimes a system maintaining internal entity-aware data structures can make sense. And almost every game will have at least *some* code which isn't in a system or part of managing systems.

# Answer
> 5 votes
Here's an article explaining it quite clearly: https://www.gamedev.net/articles/programming/general-and-gameplay-programming/understanding-component-entity-systems-r3013/.

> A component can be likened to a C struct. It has no methods and is only capable of storing data, not acting upon it.
>
> An entity is something that exists in your game world. Again, an entity is little more than a list of components. Because they are so simple, most implementations won't define an entity as a concrete piece of data. Instead, an entity is a unique ID, and all components that make up an entity will be tagged with that ID.
>
> Notice that I've neglected to mention any form of game logic. This is the job of the systems. A system operates on related groups of components, i.e. components that belong to the same entity. For example, the character movement system might operate on a Position, a Velocity, a Collider, and an Input. Each system will be updated once per frame in a logical order.

Note that unlike, for example, Unity, in "pure" ECS the behavior and state are kept strictly separate (no behavior in components, no state in systems).

# Answer
> 1 votes
**Pure ECS** can also describe one of thw two ways that Unity allows developers to create projects using their--*as of 2020, still in development/in preview*--ECS development workflow: **Hybrid** or **Pure**.

## Pure ECS

In a project that is written with Pure ECS, each game object is built purely with Entities, Components, and Systems. GameObjects and Components/Monobehaviors are predominantly not used. (This is not always true as there are still certain types of objects that are unavailable in an ECS form and may still need to be created as traditional Unity GameObjects. I imagine by the first release of ECS there will be ECS form of everything needed to build most games.)

## Hybrid ECS

Alternatively, Hybrid ECS is being offered as a go-between the classic GameObject/Monobehavior pattern and the ECS pattern. In this, the developer can use GameObjects and attach a special form of Monobehavior that converts GameObjects into Entities and certain Monobehaviors into Components.

# Answer
> 0 votes
“What makes a ECS pure.” Short version In it core, the strict splitting data from code and entity strict a ID or key or handle. Component is strict pure data, POD.
Often there is not 1 component but many. Thus a container of that type component. The data accessed through the container interface.

In my opinion getter en setters on component is not pure, but that debatable. You set and get component using the container. You prepare for batch processing of that container. Manage or do Sort all alive component at beginning

Pseudo code: Parallel foreach in alive range of that container do update. That where the multithread friendliness of pure ecs and DOD comes in.

---
Tags: terminology, entity-component-system
---


# Question
Title: How can I store the current frame's MVP matrix (Or any other data about the current frame) so that I can use it in the next frame?
I've read several articles about motion blur and all were made with OpenGL. There is no equivalent of MVP matrix in C# scripts, so I wondered if the data could be stored on the GPU itself.

Is it possible?

# Answer
> 0 votes
Here's a simple script that saves the MVP matrix used to render an object each frame, and caches it in a `PreviousMVP` variable to read next frame.

You can use `Material.SetMatrix` or `Shader.SetGlobalMatrix` to provide these matrices to your shader materials.

```
public class MVPSaver : MonoBehaviour
{
    [field:SerializeField]
    public Matrix4x4 CurrentMVP {get; private set;}

    [field:SerializeField]
    public Matrix4x4 PreviousMVP {get; private set;}

    // Called when this object is about to be rendered.
    // Snapshot the MVP matrix used for that rendering.
    void OnWillRenderObject() {

        var camera = Camera.current;

        var model = transform.localToWorldMatrix;

        var view = camera.worldToCameraMatrix;

        var projection = camera.projectionMatrix;

        // Unity works with column vectors, meaning matrices
        // combine in right-to-left order, so MVP = P * V * M.
        CurrentMVP = projection * view * model;
    }

    // Called after the object has been rendered.
    // Pass the latest MVP matrix into the previous slot.
    void OnRenderObject() {
        PreviousMVP = CurrentMVP;
    }
}

```

---
Tags: unity, shaders
---


title: Cubemap rotation

text:
# Question
Title: Cubemap rotation
I have a skybox with stars cubemap So, how can I rotate stars cubemap on Z axis using "Rotate About Axis"?

# Answer
Here is a simple skybox shader graph that allows you to rotate a cubemap about the y axis by an angle you provide in degrees:

The `Axis = (0, 1, 0)` is what makes it rotate around the y axis. You can change this to a different axis, or even chain two of these nodes if you'd like to combine rotation due to time of day with rotation due to the observer's latitude.
> 0 votes

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


title: Getting the winding order of a mesh

text:
# Question
Title: Getting the winding order of a mesh
I'm doing some topological operations on my mesh and I need to know the winding order for my mesh.

Since I will be importing models from different sources I will need to know whether the winding order is clockwise and anti-clockwise so I can get normals and things like that.

Question : Is there a way that I can determine the winding order of a list of vertices.

**Edit 1:** I am using a 3D mesh

# Answer
> 0 votes
There is no way to automatically infer the winding order of a 3D mesh that will work for every possible input.

For instance, if I give you the triangle (0, 0, 0), (1, 0, 0), (0, 1, 0) alone with no other context, you don't know whether it's meant to be wound counter-clockwise (so its front faces out along the z- axis) or clockwise (so its front faces out along the z+ axis). (Assuming a left-handed coordinate system, but the coordinate system could just as well be right-handed, flipping the whole thing)

Both of these would be valid interpretations, and you'd need to ask the creator or use some knowledge about the mesh's format or what it's meant to represent to sort out which version is intended.

But there is a common special case where we can infer the correct facing with higher confidence: if your meshes represent solid objects and you have watertight manifold geometry. (This means that the mesh makes a continuous surface with no holes, gaps, loose edges, or single-sided fins)

If you have such a mesh, you can guess at its winding, then check whether that guess makes sense by seeing if it puts the front face of each polygon facing "out" of the solid rather than inside. (But note: there are rare cases where we make meshes that have been deliberately turned inside-out for various effects, so even this test isn't foolproof!)

It proceeds like this:

1. Pick a triangle/polygon arbitrarily
2. Construct that polygon's normal according to your guessed winding
3. Cast a ray through a point in that polygon, in the direction opposite its normal. Test this ray against every other polygon in the mesh (this can get expensive)

* If you get an odd number of hits (hitting the back of another polygon, then possibly the front of another then the back of another, or any number of front-back pairs), then your winding guess looks correct. This is the pattern we'd expect to see when firing into a solid shape.
    * If you get an even number of hits, then your winding guess was probably incorrect, and you should use the opposite winding instead.

You can run this test for several different sample polygons in your mesh to build up consensus, and try to weed-out outliers due to non-manifold geometry like single-sided leaf fins.

As you can see though, it's a lot more work, and has fewer guarantees, than just inspecting your geometry source format to determine what winding is standard for that type, or asking whoever made the mesh.

---

(I originally skipped this case because you said you wanted to generate normals, and didn't mention that you had them available as input. But for completeness...)

**If your mesh has normal vectors**, then you can use these as the ground truth for the intended front facing direction (provided the creator of the model isn't doing anything too weird with manually-adjusted normals...)

Say you have a triangle with points (in order) `a`, `b`, `c`

Compute the expected normal of your triangle by taking the cross product:

```
 expectedNormal = Vector3.Cross(b - a, c - b);

```

Now compare that against the normals that came with your mesh (if your mesh has normals defined per vertex, you can average the three vertex normals for a triangle to get a triangle normal. Or you can average all the `expectedNormal` values for triangles bordering a given vertex to get a vertex normal instead)

```
agreement = Vector3.Dot(expectedNormal, sourceMeshNormal);

```

If `agreement > 0` then your mesh is wound counter-clockwise when looking at it against its normal in a right-handed coordinate system, or clockwise if you're in a left-handed coordinate system. If `agreement < 0` then your mesh is wound clockwise in a right-handed coordinate system, or counter-clockwise if you're in a left-handed coordinate system. If `agreement` is zero then the test is inconclusive for this triangle (someone's cranked the input normals to be near-zero or near-parallel to the surface for some reason), and you can try again with a different part of the mesh.

# Answer
> 0 votes
First you compute any consistent vertex ordering of the triangles (or polygons), i.e. an ordering that is consistent across neighboring faces (if no such ordering exists, the mesh is not a solid, or 2-manifold).

After that order the vertices along an arbitrary axis (let’s say the x-axis). The outward-pointing vertex normals for the vertex with minimum x-value, must have a negative x-coordinate. Compute the face normals for each adjacent face and chose the orientation such that their x-coordinate is negative. If your initial ordering was consistent, you can easily flip the entire ordering, according to these face normal orientations

---
Tags: 3d, geometry, 3d-meshes
---


title: Make moon using cubemap in shadergraph

text:
# Question
Title: Make moon using cubemap in shadergraph
I'm trying to make moon with a cubemap texture in shadergraph.

I made it, but the texture is incorrect.

I'm using a cubemap from NASA as a texture and it works, but it's bigger than moon shape and thee larger I make the radius, the more of the texture appears.

I want to fit the cubemap within the moon shape.

Shader graph:

# Answer
The problem with this shader graph is that you're sampling the moon's surface cubemap with your view direction vector (the green vector on the left). What you want is the red vector on the right.

We can get that vector with a little trigonometry. I'll spare you the full derivation and just jump straight to the shader graph code that implements it:

In this first section, we transform the view vector into a coordinate space where z+ is the "to moon" direction. (You can rotate the mesh this shader is being rendered on to change where the moon sits in the sky, or replace this with your own preferred coordinate transformation)

We then break down that vector into components that get us the trig ratios we need for angle \\$a\\$ in the diagram above, and use that to get some trig ratios for angle \\$c\\$.

Then we do some math on those to get the tangent ratio of angle \\$b\\$, and use that to construct a vector in the moon surface direction. That's the vector we'll use to sample the moon cubemap. You can also normalize it to get a surface normal vector for lighting calculations, like rendering the phases of the moon.

(By default, this setup will give you a moon that's tidally locked: the same side always points toward the viewer. If you don't want this, you can rotate the moon surface direction vector before passing it to the Sample Cubemap node)

Of course, all this math is only valid for view rays that actually hit the moon. For pixels outside that narrow cone, we want to skip as much of that calculation as we can and just draw stars, then do a light feathered blend between the two. Here are the nodes that do that:

As you can see, this lets you control the size of the moon in the sky, and the moon's features scale with the moon - when the moon gets smaller, it doesn't crop the surface texture, it shrinks the whole thing together.
> 1 votes

---
Tags: unity, textures, unity-shader-graph, cubemap
---


title: Alternative method of creating Vector2

text:
# Question
Title: Alternative method of creating Vector2
Having to re-learn stuff after upgrading to Godot 4.x. I can declare an int with

```
@export var spoon:int = 224 # or
@export var spoon:= 224

```

However, I can't seem to use the same for a vector 2: @export var variablename: type = value

```
@export var canvas_size:= Vector2(224, 256)  # works
@export var canvas_size:Vector2 = (224, 256) # doesn't work

```

Results in Error: expected closing ")" after grouping expression

Where am I going wrong?

# Answer
## Yes, this does not work

I can do little more than reiterating what you discovered. This does not work:

```
@export var canvas_size:Vector2 = (224, 256) # doesn't work

```

You would have to write this:

```
@export var canvas_size:Vector2 = Vector2(224, 256)

```

But why when you can write this:

```
@export var canvas_size := Vector2(224, 256)

```

I want to point out that the proposed syntax is not really equivalent to the `int` literal, given that the `Vector2` type (despite being built-in and value type) is not primitive, but composite. So it seems to be closer to `Array` (`[]`) and `Dictionary` \[`{}`\] initializers.

---

## Why this does not work

Why does that syntax not work? Because nobody implemented it. Features start up not existing, and somebody has to program them.

Currently the parser only uses what precedes the open parenthesis to decide how to interpret the expression... But, for this syntax, deciding how to interpret the parenthesis would have to be delayed until it knows if there is a comma or not...

Furthermore, how many commas, given that the type would depend on the number of elements if it will support `Vector3` and `Vector4`.

On the same order of ideas, the integer vectors (`Vector2i`, `Vector3i` and `Vector4i`) throw another wrench on this. For example, since in `(224, 256)` all the elements are `int`s, I would expect a `Vector2i` instead of a `Vector2` (which uses `float`s).

I'm not saying it can't be done, it can be done. I'm postulating that it might not be worth it (a lot of effort for little gain). But don't take me as gatekeeper...

You can write a proposal if you really care about this feature, make your case.

---

## No, this is not new in Godot 4

By the way, I'll point out that barring `@export` it is the same situation in Godot 3, it would be like this:

```
export var spoon:int = 224 # works
export var spoon:= 224 # works
export var canvas_size:= Vector2(224, 256)  # works
export var canvas_size:Vector2 = (224, 256) # doesn't work

```

*Yes, Godot 3 had typed variables.*
> 4 votes

---
Tags: godot-4, godot-3
---