# Question
Title: Most efficient way to load assets based on player settings?
I would like to know some better coding patterns to load assets based on player settings. Say that users are allowed to select 1 of many skins for a weapon. Now when I load that weapon object, I want the assets for that skin to be loaded instead of the default.

My question is: what is a good coding pattern to store the user's skin choice, and to read/use this stored data to programmatically load a prefab or texture later?

Right now, what I have is a scroll view with buttons that show each unique skin. When the button is pressed, it saves the skin texture's file name to JSON. Then, later, when I want to figure out what to use, I read that field from JSON and call Resources.Load() on the file name.

Is there a better way to do this? This is very manual and error prone since I have to specify the texture's file name in my code for each button. Right now I'm trying to grab the texture's file name via Image.sprite.name, but this also has a level of manual work involved. It requires knowing which subdirectory of the Resources folder the sprite is in.

# Answer
> When the button is pressed, it saves the skin texture's file name to JSON.

Is the preferred skin a preference of the user? Then did you consider to use PlayerPrefs instead? It provides you with a simple, persistent key-value store.

> Then, later, when I want to figure out what to use, I read that field from JSON and call Resources.Load() on the file name.

This sounds like a perfect use-case for Addressables.

With Addressables, you get an input on top of the inspector of every asset where you can specify a key for that asset:

This *can* be the filename, or it can be any other string. You can then load that asset at runtime using that key. Advantages of addressables over Resources is:

* The assets don't need to be in a folder named Resources. You can make any asset in your project addressable. You can even move those assets around in your project. As long as you don't change the key, the addressable system will still find them.
* Addressables handle asset bundles in a transparent matter. When you registered asset bundles which contain addressable assets, then you can just use `Addressables.LoadAssetAsync` and it will automatically figure out which asset bundle contains the asset you want.
* You can even put asset bundles on the web. The addressable system will then download those asset bundles automatically.
* You can also tag addressables with Labels. This allows you to mark all your weapon skin textures and then load them all at runtime. When you need the keys of those assets, then you might want to use a two-step process where you first use `Addressables.LoadResourceLocationsAsync` to get the asset locations and then load each asset with `Addressables.LoadAssetAsync(location)`. The resource locations contain the key of the addressable, so it allows you to associate each addressable with its key. A code example can be found in the documentation article loading multiple assets, subsection "Correlating loaded assets to their keys".

So **tl;dr:**

1. Make the skins addressables. Give each addressable an unique key, and assign the label "weapon\_skin" to all of them.
2. In the menu, load all the addressables with the label "weapon\_skin", so you can instantiate a button for each of them.
3. In the menu, store the key of the chosen skins in PlayerPrefs.
4. In the game, load the addressable with the key you retrieve from PlayerPrefs.
> 3 votes

---
Tags: unity
---


# Question
Title: How can I import an AvatarCLIP animation into Unity?
I have an .fbx file containing a an avatar that is standing still.

I followed the steps in this GitHub repository section "Motion Generation" to create an animation for that avatar. What I received were an .mp4 file and a .npy file which contain the movement that I want the avatar to do.

Is there any way to connect between them so that the avatar will move like in these files? The animations are going to be applied to many different .fbx files.

I am sort of looking for something like Mixamo, but with a way of importing an animation and not only an avatar.

# Answer
> 1 votes
Try using their Avatar2FBX tool. Just before the section on Motion Generation, they have this section:

> **Convert Avatar to FBX Format:**
> For the convenience of using the generated avatar with modern graphics pipeline, we also provide scripts to rig the avatar and convert to FBX format. See the instructions here.

However I'm a bit skeptical will do everything you need as that page lists animation as **TODO** & near the bottom it notes:

> we currently only supports 'stand pose' and 'zero beta'

Their Avatar2FBX tool appears to be based on other work. If their 'bundled' version doesn't work, you could try looking for a more active or original source with the hopes that it has the functionality you're looking for.

---
Tags: unity
---


# Question
Title: How can I visually see changes made to a scene since the last git commit
I'd like to see the changes made in a scene (.unity file) before I commit them to git.

I have looked into several GIT/Unity solutions but all of them are made for merging changes and not for showing a diff with last version.

The problem with scene files is that they use GUIDs that point to other assets and when I open a diff for a scene file I can't really make anything out of it.

**For example:**

**Instead, I'd like to see something like this:**

**Is there anything existing that does this?**

# Answer
> 1 votes
> I'd like to see the changes made in a scene (.unity file) before I commit them to git.

Any decent git tool will do this *provided the scene file is not binary*; but, as you mentioned, the GUID references makes it difficult to read. If the scene is binary, serialization may be updated in `Edit -> Project Settings -> Editor -> Asset Serialization`; but, **be warned: data-loss may occur** (See Draco18s comment below.).

> I have looked into several GIT/Unity solutions but all of them are made for merging changes and not for showing a diff with last version.

Seeing the changes made to a single file is one of the core features of git log. In fact, there's a stackoverflow question on that. Basically you'd use something like

```
git log --follow path/to/scene.unity

```

to display the history of that file. Add `-1` to display the most recent changes to the specified file. Ommit `-1` and use `-p` to see the patch made for each commit that modified that file. I recommend reading through the stackoverflow question before touching the git-log documentation because it's *very long*.

> Instead, I'd like to see something like this:
>
> \[scene graph diff\]
>
> Is there anything existing that does this?

As far as I can tell, **No**. That being said, Unity for Git appears to be the natural place to find it. Since it's in alpha, you should create an issue there to address this. Since it's unique to applying git diff on unity's intrinsic scene graphs, I suspect it'l be strongly relevant there.

# Answer
> 1 votes
This git-for-unity tool might be something you could use. Not a directed graph but more visual than just a git text log https://flashg.github.io/GitMerge-for-Unity/

# Answer
> -3 votes
I would recommend you to just use Git with Bitbucket (as push origin !) as it provides a really nice GUI that lets you see graphical representation of your branch and commit history as well as changes within the text files where You can even see changes in the code in red and green plus many other nice workflow features.

---
Tags: unity, scene-graph, scene, version-control
---


# Question
Title: Alter vehicle angle to match that of ground
I am trying to align a non physics vehicle to the same angle as the floor, using blueprints in UE4.27

At first, I used normals, but this has undesired effects when going over things like speed bumps.

I have tried LookAtRotation but that only gives pitch and yaw. I only want to get pitch and roll, yaw is controlled by the vehicle.

I have a location I get from a line trace at each corner. I want to compare this to a part on the vehicle (that is perhaps at floor level) to determine what pitch and roll I need to apply to the vehicle to align it to the floor or obstacle I am driving over.

# Answer
Let's call the four points where your linecasts hit the ground `frontLeft`, `frontRight`, `backLeft`, and `backRight`.

This lets us find a vector with the amount of forward tilt (pitch) we want as:

```
forward = frontLeft + frontRight - backLeft - backRight

```

And the angle it makes with the horizontal plane is:

```
pitchRadians = asin(forward.z / length(forward))

```

Similarly for the side-to-side (roll) angle:

```
right = frontRight + backRight - frontLeft - backLeft
rollRadians = asin(right.z / length(right))

```

You may need to negate one or both and/or convert from radians to degrees, depending on the details of your coordinate system.
> 1 votes

---
Tags: rotation, unreal-4, blueprints, angles, vehicle
---


title: Procedurally generate regions on island

text:
# Question
Title: Procedurally generate regions on island
I currently have islands that look like this:

And I want to procedurally subdivide it into regions, like this:

What algorithm does what I'm looking for? Do you have suggestions on how to create coherent regions like in the bottom picture. Your help is appreciated.

# Answer
In the real world, those provincial borders will often be following geological features like rivers.

So maybe a good approach would be to model the geology of the island and have the borders fall out of this?

Red Blob Games has some good articles on this subject, with nice looking results.

His approach seems to involve using Voronoi tessellation, and define the rivers as the boundaries between the cells.

Check out the other articles on his site, he has done a lot of writing on the subject of map generation.
> 41 votes

# Answer
I would solve this problem with two passes of Voronoi diagrams:

### First Pass: Region Partitioning

The first pass would use a somewhat sparse distribution of points (i.e. the distance between the points should be relatively large) in order to roughly divide the island into regions (see the note below regarding point generation). Next generate a Voronoi diagram based on these points. This will divide the island into polygonal regions around each point as shown below:

### Second Pass: Border Randomization

Now that the island has been divided into regions, then next step is to 'rough up' the boundaries between them. To do so, generate a new layer of points using a more compact distribution of points (i.e. the distance between points should be small) and again use these points to create another Voronoi diagram. Next for each smaller region, assign it to a larger region by checking its 'seed' point. This will result in a more jagged boundaries between the larger subdivisions. Here's a close up of what it looks like with both Voronoi diagrams in place:

And here's that same area showing only the final boundaries:

### Comments on Point Generation

Regarding point generation, I like using a Poisson disc distribution in order to get a relatively nice & even distribution of points. The other common option is to get a similarly even distribution is to use Lloyd's algorithm on a set of 'regular' random points. LLoyd's is easier to code, but can take some trial & error to determine how many passes are required to give the desired result.

One potential problem with this approach is that the first pass partitioning may generate some very small regions. If you don't want them in your final result, I would simply merge them with a random adjacent region.

### Final Notes

The illustrations I provided happen to be raster images, but this technique also works with polygonal / vector representations as well.
> 28 votes

# Answer
MineCraft does this nicely, and its world generation algorithm has been analyzed and documented thoroughly.

There are various descriptions of the algorithm, one of them here: https://github.com/UnknownShadow200/ClassiCube/wiki/Minecraft-Classic-map-generation-algorithm

The core of the algorithm is a Perlin noise generator. This controls elevation directly (more or less, as the subsequent step to carve out caves can change the surface as well), as well as biome generation. Something like the biome generator is probably what you want to use to create your areas.

(An old version of it) is documented, basically it works by using two different Perlin Noise generators, one for "temperature", one for "precipitation", then choosing the biome from those two. The variables themselves (temperature and precipitation) aren't really used in the game later; for example, deserts have no rain, but the game determines this from the "desert" property, not from the original precipitation value.

There are various online tools to generate a biome map from a random seed, one of them is mineatlas.com. I guess that, internally, they use a java server which uses the internal classes of MineCraft itself; I don't know if any of their source code is available directly.
> 5 votes

# Answer
A typical algorithm used, for example, by Azgaar (source code). Is roughly like this:

1. split your landmass into smaller areas, e.g. through delauny triangulation or voronoi cells.
2. determine (randomly or otherwise) "starting" locations for your cultures, realms, religions or whatever else you want to simulate.
3. determine (randomly or otherwise) a "growth factor" for each of them. The more difference in growth factors you have, the less uniform your final map.
4. Now iterate over your realms (etc) and, depending on growth factor, make them spread into surrounding, empty tiles until the entire map is filled.
5. You probably want to end with straightening out borders a bit, by switching cells that have only one neighbour in their own colour and are otherwise surrounded by a different one to that colour.
> 4 votes

# Answer
If you are interested in doing this in vectorial format rather than raster-based approaches, I have written a blog post a while ago about pretty much exactly this.

http://blog.particracy.com/worlds-and-their-geography/

The idea is you start with a mesh (Voronoi based usually) and grow the regions concentrically from randomly seeded points that are sufficiently spaced apart.
> 3 votes

# Answer
What a fun question :) This approach is kinda based on Vornoi cells but the distance metric isn't quite Euclidian (I used the power of 1.5 instead of 2.0) and has some randomness built into it. It may jump over the water which isn't ideal.

Nearby regions can be merged together to get more interesting shapes, here I kind of used the N nearest neighbors to determine this.

If you are interested I can go into more details and share the Python code.
> 3 votes

# Answer
It just so happens that I found a VERY easy solution to this problem. I use a Flood-Fill technique as follows. First I create a number of random seed locations on the map. Then I use Flood-Fill to "grow" the seeds, randomly. The results very much mirror what was asked for. The code for this is not particularly long. Perhaps one question is, "So, how many seeds should I use?" This will depend on how small/large you would like each region to be. One easy solution is to use a number of partitions as a percentage of the number of hexes/squares in your land mass. For instance: say your land mass is 400 hexes in size and you would like your land mass divided into 10 regions, then simply divide the total size of the land mass (400) by 10 and, thus, create 40 seeds. This is also further easily modified to have a random # of regions (or a random # of regions within a given range, etc...). The following Java code should get you close. Obviously, you will have to fill in some code, but hopefully you get the idea:

```
private void Assign_Hexes_to_Regions (
    final Random RNG,
    List <Integer> frontier_hex_IDs,
    List <Integer> accompanying_frontier_region_IDs,
    final Function <Coords, List <Coords>>
    function_all_adjacent_coords
    ) {
//
//  use a Flood-Fill technique to assign EACH Hex to EXACTLY ONE Region
//
    while ( frontier_hex_IDs.size() > 0 ) {
        //
        //  Randomly select one of the UNASSIGNED Hexes
        //
        int random_index        = RNG.nextInt( frontier_hex_IDs.size() );
        int random_vertex_ID    = frontier_hex_IDs.remove( random_index );
        int random_region_ID    = accompanying_frontier_region_IDs.remove( random_index );

        Integer existing_region_ID = this.hex_ID_to_partition_ID.get( random_hex_ID );

        if ( existing_region_ID == null ) {
            //
            //  NO Region assigned (yet) to this (Random) Hex
            //
            this.Assign_Hex_ID_to_Region( random_hex_ID, random_region_ID, frontier_hex_IDs, accompanying_frontier_region_IDs, function_all_adjacent_coords );
        } else if ( existing_region_ID != random_region_ID ) {
            //
            //  This Hex was PREVIOUSLY assigned to a DIFFERENT Region.  Thus,
            //  this Hex is at a Region Boundary
            //
            this.Get_Region( existing_region_ID ).Add_Boundary_Hex_ID( random_hex_ID );
        }
    }

private void Assign_Hex_ID_to_Region (
    final int hex_ID,
    final int region_ID,
    List <Integer> frontier_hex_IDs,
    List <Integer> accompanying_frontier_region_IDs,
    final Function <Coords, List <Coords>>
    function_all_adjacent_coords
    ) {
    //
    //  Assigns the Hex to the specified Region
    //
    this.Set_Region_ID_for_Hex_ID( hex_ID, region_ID );
    //
    //  Add Adjacent Hexes to the Flood-Fill possibilities
    //
    //  note:  the Get_All_Adjacent_Coords() function determines if the Coordinates Wrap-Around or not
    //
    for ( Coords adjacent_vertex_coords : function_all_adjacent_coords.apply( this.space_subset.Get_Space().Get_Coords_from_Vertex_ID( vertex_ID ) ) ) {
        if ( this.space_subset.Get_Space().Has_Coords( adjacent_vertex_coords ) ) {
            Integer adjacent_hex_ID = this.space_subset.Get_Space().Get_Hex_ID_from_Coords( adjacent_hex_coords );
            if ( this.space_subset.Is_in_Subset( adjacent_hex_ID ) ) {
                frontier_hex_IDs.add( adjacent_hex_ID );
                accompanying_frontier_region_IDs.add( region_ID );
            }
            //
            //  do NOT Add the Adjacent Hex if it is OFF on the Land Mass
            //
        }
        //
        //  do NOT Add the Adjacent Hex if it is NOT on the Map (incl. Wrap-Around)
        //
    }
}

```

Here are 2 screenshots of a land mass with 2 different randomly-created regions using the Flood-Fill algorithm.
> 2 votes

---
Tags: procedural-generation, terrain
---


# Question
Title: How to lerp correctly between two unlimited rotations
Hi i have a start point and end point which i use to create some point between, this points are calculated with a blending rotation between point A rotation to point B rotation.

I use Mathf.LerpAngel but still I'm getting wrong result.

When rotation reaches -180 or 180 in some cases even -359.05 or 0.005 it gets flipped. Here's the result with issue : https://raw.githubusercontent.com/CycloneRing/UnityRotationLerp/main/RotationLerpIssue%20.mp4

And this is the result I want to achieve:

And here's my code (Look at Github):

```
// Extra points
for (int i = 0; i < genPts.Count; i++)
{
    float blendValue = ConvertRange(0, genPts.Count, 0.0f, 1.0f, i);
    var localEulerFrom = start.localEulerAngles;
    var leftAngleFrom = spt.angleLeft;
    var rightAngleFrom = spt.angleRight;

    var localEulerTo = end.localEulerAngles;
    var leftAngleTo = ept.angleLeft;
    var rightAngleTo = ept.angleRight;

    var localEulerBlend = LerpAngles(localEulerFrom, localEulerTo, blendValue);
    var leftAngleBlend = Mathf.Lerp(leftAngleFrom, leftAngleTo, blendValue);
    var rightAngleBlend = Mathf.Lerp(rightAngleFrom, rightAngleTo, blendValue);

    var base_left_angle = Quaternion.Euler(localEulerBlend.x, localEulerBlend.y, localEulerBlend.z + leftAngleBlend) * Vector3.right;
    var base_right_angle = Quaternion.Euler(localEulerBlend.x, localEulerBlend.y, localEulerBlend.z + -rightAngleBlend) * Vector3.right;
    var leftPos = genPts[i] + -base_left_angle.normalized * length;
    var rightPos = genPts[i] + base_right_angle.normalized * length;

    genExtraPts.Add(leftPos);
    genExtraPts.Add(rightPos);
}

```

I want it continuously keep rotation with a smooth blend. How can i achieve that?

A simple, minimal unity project is uploaded in github at https://github.com/CycloneRing/UnityRotationLerp

EDIT 1 : I tried using Quaternion as well but result is same.

```
// Extra points
for (int i = 0; i < genPts.Count; i++)
{
    float blendValue = ConvertRange(0, genPts.Count, 0.0f, 1.0f, i);
    var rotationFrom = start.localRotation;
    var rotationTo = end.localRotation;
    var localRotationBlend = Quaternion.LerpUnclamped(rotationFrom, rotationTo, blendValue);
    var base_left_angle = localRotationBlend * Vector3.right;
    var base_right_angle = localRotationBlend * Vector3.right;
    var leftPos = genPts[i] + -base_left_angle.normalized * length;
    var rightPos = genPts[i] + base_right_angle.normalized * length;

    genExtraPts.Add(leftPos);
    genExtraPts.Add(rightPos);
}

```

# Answer
You run into this type of issue when you want to rotate in a specific direction, and Unity doesn't realize this.

When you tell Unity to Lerp/Slerp between two angles, it takes the shortest path. You are running into problems is when the shortest path is no longer in the direction you want to go. In your video, the bottom gizmo is rotating clockwise. For the first 180 degrees of rotation, the double-helix is rotating in the same way - clockwise. However, once the difference in rotation between the top and bottom gizmos is more than 180 degrees, the double-helix suddenly rotates 180 degrees counter-clockwise because that's now the shortest direction to go.

For example, if you tell Unity to Lerp a quaternion from 0 degrees to 179 degrees, it will move in the positive direction (clockwise, if you're looking at the Y axis), because that's the shortest path from 0 to 179. However, if you tell it to Lerp a quaternion from 0 degrees to 181 degrees, it will move in the negative direction (counter-clockwise, if you're looking at the Y axis).

If you're only rotating one axis, the easiest thing to do is track the rotation of each end as a single float, so that it doesn't wrap at 180/-180, and use `Mathf.Lerp()`.

A highly simplified example:

```
[SerializeField] private Transform start;
[SerializeField] private Transform mid;
[SerializeField] private Transform end;
float speed = 90;
float startRotation = 0;
float endRotation = 0;
void Start() {
    startRotation = start.transform.localEulerAngles.y;
    endRotation = end.transform.localEulerAngles.y;
}

void Update() {
    endRotation += speed * Time.deltaTime;
    float midRotation = Mathf.Lerp(startRotation, endRotation, .5f);
    Debug.Log(midRotation);
    mid.transform.localEulerAngles = new Vector3(0, midRotation, 0);
    end.transform.localEulerAngles = new Vector3(0, endRotation, 0);
}

```

In this example, the `endRotation` value is always increasing and never wraps. This means that when we Lerp from `startRotation` to `endRotation`, we're always moving in the positive (clockwise) direction.

You need to store your rotation values separately rather than reading them from the transform each frame, or Unity may wrap them:

```
transform.localEulerAngles = new Vector3(0, 370, 0);
Debug.Log(transform.localEulerAngles); //"(0.00, 10.00, 0.00)"

```
> 1 votes

---
Tags: unity, c#, mathematics, rotation
---


# Question
Title: Why won't my legs rotate at the top instead of the centre
As the title suggests, I'm battling with getting the legs of my model here to rotate properly. They rotate in the middle instead of at the top where the knee joint would be. So far I've tried translating them to 0.0, 0.0, 0.0 before calling the glrotate function on my body parts but all that does is move the lower leg further away from the upper leg and keep the issue going. I can't figure this out.

Visual of Issue

```
#include <glut.h>

float angle[4];
float LightAngle;
GLuint texture;

bool LowerFrontLegDown = true;
bool LowerBackLegDown = true;

GLfloat corners[8][3] = { {-0.5,0.5,-0.5},{0.5,0.5,-0.5},
                        {0.5,-0.5,-0.5},{-0.5,-0.5,-0.5},
                        {-0.5,0.5,0.5},{0.5,0.5,0.5},
                        {0.5,-0.5,0.5},{-0.5,-0.5,0.5} };

//Two Dimensional Array for the corners of the cube

GLfloat normals[][3] = { {0.0,0.0,1.0},
                                      {1.0,0.0,0.0},
                                      {0.0,-1.0,0.0},
                                      {0.0,1.0,0.0},
                                      {0.0,0.0,-1.0},
                                      {-1.0,0.0,0.0} };

//Normal maps for the cube to apply lighting to it when the program runs

typedef struct materialStruct {
    GLfloat ambient[4];
    GLfloat diffuse[4];
    GLfloat specular[4];
    GLfloat shininess;
};

materialStruct redPlasticMaterial = {
       { 0.30, 0.00, 0.00, 1.00 },
       { 0.60, 0.00, 0.00, 1.00 },
       { 0.80, 0.60, 0.60, 1.00 },
       32.00 };

materialStruct* currentMaterial;

void setMaterial(materialStruct* materials) {
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, materials->ambient);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, materials->diffuse);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materials->specular);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, materials->shininess);
}

//Defines a material that is then applied to the model

void drawFace(int a, int b, int c, int d) {
    glBegin(GL_POLYGON);
    glTexCoord2f(0.0, 0.0);
    glVertex3fv(corners[a]);
    glTexCoord2f(0.0, 1.0);
    glVertex3fv(corners[b]);
    glTexCoord2f(1.0, 1.0);
    glVertex3fv(corners[c]);
    glTexCoord2f(1.0, 0.0);
    glVertex3fv(corners[d]);
    glEnd();
}

//Turns the corners from the two dimensional array into corner pieces for the model, allowing faces to be drawn and in turn, allowing for the model giraffe to be drawn

void ArrayCube() {
    glNormal3fv(normals[0]);
    drawFace(0, 3, 2, 1);
    glNormal3fv(normals[1]);
    drawFace(3, 0, 4, 7);
    glNormal3fv(normals[2]);
    drawFace(2, 3, 7, 6);
    glNormal3fv(normals[3]);
    drawFace(1, 2, 6, 5);
    glNormal3fv(normals[4]);
    drawFace(4, 5, 6, 7);
    glNormal3fv(normals[5]);
    drawFace(5, 4, 0, 1);
}
//Draws the faces of the model and creates a cube we can call later for the individual parts of the model.

void rotate() {
    angle[0] += 1.0;
    if (angle[0] > 360) angle[0] -= 360;

    if (LowerFrontLegDown) angle[1] -= 0.2;
    else angle[1] += 0.2;

    if (angle[1] < 315) LowerFrontLegDown = false;
    if (angle[1] > 360) LowerFrontLegDown = true;

    angle[0] += 1.0;
    if (angle[0] > 360) angle[0] -= 360;

    if (LowerBackLegDown) angle[1] -= 0.2;
    else angle[1] += 0.2;

    if (angle[1] < 315) LowerBackLegDown = false;
    if (angle[1] > 360) LowerBackLegDown = true;

    glutPostRedisplay();
}

void MainBody()
{
    glPushMatrix();
    glScalef(1.25, 0.25, 0.5);
    ArrayCube();
    glPopMatrix();
}

void LowerNeck()
{
    glPushMatrix();
    glTranslatef(0.5, 0.25, 0);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void UpperNeck()
{
    glPushMatrix();
    glTranslatef(0.5, 0.75, 0);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void Head()
{
    glPushMatrix();
    glRotatef(90, 0.0, 0.0,1.0);
    glTranslatef(1, -0.6, 0);
    glScalef(0.1, 0.4, 0.15);
    ArrayCube();
    glPopMatrix();
}

void RightHorn()
{
    glPushMatrix();
    glRotatef(0, 0.0, 0.0,1);
    glTranslatef(0.5, 1.15, 0.035);
    glScalef(0.05, 0.15, 0.05);
    ArrayCube();
    glPopMatrix();
}

void LeftHorn()
{
    glPushMatrix();
    glRotatef(0, 0.0, 0.0, 1);
    glTranslatef(0.5, 1.15, -0.035);
    glScalef(0.05, 0.15, 0.05);
    ArrayCube();
    glPopMatrix();
}

void FrontUpperRightLeg()
{
    glPushMatrix();
    glTranslatef(0.5, -0.35, 0.15);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void FrontLowerRightLeg()
{
    glPushMatrix();
    glTranslatef(0.5, -0.85, 0.15);
    glRotatef(angle[1], 0.0, 0.0, 1.0);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void FrontUpperLeftLeg()
{
    glPushMatrix();
    glTranslatef(0.5, -0.35, -0.15);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void FrontLowerLeftLeg()
{
    glPushMatrix();
    glTranslatef(0.5, -0.85, -0.15);
    glRotatef(angle[1], 0.0, 0.0, 1.0);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();

    glPopMatrix();
}

void BackUpperRightLeg()
{
    glPushMatrix();
    glTranslatef(-0.5, -0.35, -0.15);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void BackLowerRightLeg()
{
    glPushMatrix();
    glTranslatef(-0.5, -0.85, -0.15);
    glRotatef(angle[1], 0.0, 0.0, 1.0);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void BackUpperLeftLeg()
{
    glPushMatrix();
    glTranslatef(-0.5, -0.35, 0.15);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void BackLowerLeftLeg()
{
    glPushMatrix();
    glTranslatef(-0.5, -0.85, 0.15);
    glRotatef(angle[1], 0.0, 0.0, 1.0);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

void Tail()
{
    glPushMatrix();
    glTranslatef(-0.65, -0.25, 0);
    glScalef(0.05, 0.75, 0.05);
    ArrayCube();
    glPopMatrix();
}

//Each of the below functions draws an individual part of the whole model and places those parts where they need to go once the program runs

void DrawGiraffe()
{
    MainBody();
    LowerNeck();
    UpperNeck();
    Head();
    RightHorn();
    LeftHorn();
    FrontUpperRightLeg();
    FrontLowerRightLeg();
    FrontUpperLeftLeg();
    FrontLowerLeftLeg();
    BackUpperRightLeg();
    BackLowerRightLeg();
    BackUpperLeftLeg();
    BackLowerLeftLeg();
    Tail();

}

//Calls the above functions to render the final model

//The rotate function allows the camera to rotate around the model

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.6, 0.6, 0.6, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

    DrawGiraffe();
    glutSwapBuffers();
}

void init() {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    GLubyte image[64][64][3];
    int i, j, r, c;
    for (i = 0; i < 64; i++) {
        for (j = 0; j < 64; j++) {
            c = ((((i & 0x8) == 0) ^ ((j & 0x8)) == 0)) * 255;
            image[i][j][0] = (GLubyte)c;
            image[i][j][1] = (GLubyte)c;
            image[i][j][2] = (GLubyte)c;
        }
    }
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    currentMaterial = &redPlasticMaterial;
    setMaterial(currentMaterial);
    glColor3f(1.0, 1.0, 1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 2.5);
    GLfloat light_pos[] = {2.0,2.0,2.0, 1.0};
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
}

int main(int argc, char** argv)
{
    angle[0] = 0;
    angle[1] = 360;
    angle[2] = 315;
    angle[3] = 0;

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Giraffe");
    glutDisplayFunc(display);
    glutIdleFunc(rotate);
    init();
    glutMainLoop();
}

```

# Answer
> 2 votes
`glRotatef` always rotates around the origin.

When rotating around an arbitrary point `p` you should first translate by `-p`, do the rotation, and then translate by `p`.

Also when you have a hierarchical structure you will want to nest the matrix manipulation:

```
void FrontUpperRightLeg()
{
    glPushMatrix();
    glTranslatef(0.5, -0.35, 0.15);
    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    FrontLowerRightLeg(); //draw the lower leg relative to the upper leg before popping the matrix
    glPopMatrix();
}

void FrontLowerRightLeg()
{
    glPushMatrix();
    //adjust parameters to account for the coordinate being relative to the upper leg
    glTranslatef(0.5, -0.85, 0.15);

    glTranslatef(...);
    glRotatef(angle[1], 0.0, 0.0, 1.0);
    glTranslatef(...); //translate by the negation

    glScalef(0.15, 0.5, 0.15);
    ArrayCube();
    glPopMatrix();
}

```

that way when you rotate the upper leg the lower leg will move along with it with no extra code.

---
Tags: opengl, c++, glut
---


# Question
Title: How to send a JS game using a Discord bot?
I have made a JavaScript game. Now I want to make a Discord bot that embeds it in a message, so a reader can click on the embed to play the game inside the chat. Something similar to this Snake game.

Here's what the result should look like:

# Answer
> 1 votes
You can't really send a game through Discord unless you are using Discord's API.

Why?

> The game shown in the video is coded in JavaScript but is run on the bot server, not on the client. The bot appears to compose an HTML response which is then sent to the client, which is then displayed. They don't "send a JavaScript game". I doubt Discord will ever allow sending actual JavaScript to be executed on the client.

(Vaillancourt told me)

But you can run it in a browser by hosting your game on itch.io and sharing a link to its itch.io page.

---
Tags: javascript, discord
---


# Question
Title: Is it possible to create map files for a 3D game using AutoCAD and 3ds Max?
Is it possible to make maps for games using AutoCAD and 3ds Max?

I am studying architecture and I am making pretty good making 3D objects. I would like to make them for games, but I don't know what program I can use.

Is it possible to export something from CAD or 3ds to some game engine like Unity?

# Answer
"Is it possible" is a question you can answer for yourself.

Searching "Unity model file formats" takes you to this page and this one which confirm that you can use models in the following formats in Unity:

* .fbx
* .dae (Collada)
* .dxf
* .obj
* .max (Autodesk® 3ds Max®)
* .blend (Blender)

So that already answers the 3ds Max part of your question. The only remaining question is whether AutoCAD can export one of these formats that Unity can import.

So our next search is "AutoCAD export formats" or just "AutoCAD file formats". This lists .dxf as a possible save format, which matches Unity's import list.

Now let's see if there's any published advice about using the programs together in this way, by searching "AutoCAD export to Unity".

That turns up this existing Q&A, strongly advising to *not* use AutoCAD for this purpose, for reasons explained in some detail there.

Software recommendations are not on-topic for this exchange, so we can't tell you what software to use. What I wanted to do with this answer was demonstrate how you can find this information on your own. Searching "making models for Unity" will turn up tons of guides and tutorials you can peruse to get a sense of the workflow in various content creation tools, and decide which one you want to try.

Since Unity is free to install, you can even do a quick test, importing some model file you have lying around, to see if you run into any snags in the process or encounter any unwanted effects - that helps you ask a more focused question about how to deal with that specific obstacle.

Skipping this step of searching/testing for yourself can make your question appear to "not show research effort", which is one reason why questions might get down-voted. Doing this legwork will help you get the information you need, and ask high-quality questions that attract upvotes and detailed answers instead.
> 2 votes

---
Tags: unity, 3d-modeling, asset-workflow
---


# Question
Title: How do I go about creating images, which are units with traits?
Lets say there are 5 units, displayed as images on an html5-canvas. Each image (unit) has a different size. For the game I need to know the size of that unit, and also it's middle point.

How and where do I save this data? If I load the image, do I save that image data in a, f.e., an array of objects, where each object has that image attributes?

What do I do if that unit dies, do I delete that object from the array? And do I just create a object when I create a new unit again?

What structure can I use here? An array of objects doesn't seem very efficient to me (I don't even know if it works, not very experienced).

I had something like this in mind:

```
let unit_imgs = [
    {
        width,
        height,
        midpoint,
    },
    {
        width,
        height,
        midpoint,
    },
    { ... },
];

```

Any other, better, ways to do this?

# Answer
> 0 votes
> Any other, better, ways to do this?

Separate logic and presentation: make an array of units to process their logic and a dictionary of images so that units could reference them.

Whenever you need to update canvas just iterate over your units, for every single one find an image it refers to and draw it.

---
Tags: javascript, html-canvas
---


# Question
Title: Change environment saturation based on exposure to "light source" - Unity
I am trying to make a game where particular "light sources" bring color to an otherwise grey world. I am extremely new to the world of custom graphics processing. I assume it will require a custom shader of some description but don't know how to go about adding variables to shaders which can be read at runtime.

Pretty much pull the saturation out of everything unless its hit by something which behaves much like light does (objects block it from hitting things behind it; there is a gradient of distance vs intensity; some sort of single bounce would be nice but understand that is computationally expensive.) Honestly would be fine with it being a standard light source which gets detected. If that surface/pixel hit by that light source, don't mess with the saturation.

You can get pretty close to what I want with post-processing and a luminosity-saturation curve but then it gets affected by other light sources.

Using the URP at the moment, but if that has to change, then so be it. The entire games' feel revolves around this.

Many thanks in advance if anyone can point me in the right direction, or even in the direction of some good tutorial material. Unity's docs with regard to graphics are all over the place and not particularly helpful to those who are new.

# Answer
I'd handle this in passes.

Your first pass renders your scene with shader replacement, rendering everything in plain diffuse white with no normal maps/etc, and no ambient term. Place your saturation-casting lights and your conventional lights on their own separate layers, and configure your camera for this pass to use only the saturation-casters. Output the result to a RenderTexture. You'll end up with a greyscale map in this texture, where bright areas should become high-saturation and dark areas low-saturation.

Your next pass renders your scene as usual - the camera for this pass should ignore the layer containing the saturation-casting lights.

Lastly, apply a post-process to the output of this pass, to tweak its saturation before outputting to the screen, using the greyscale texture saved in the first pass as a saturation multiplier.
> 0 votes

---
Tags: unity, shaders, lighting
---


# Question
Title: I cannot understand this change of basis problem
I know we need to get the inverse of transformation matrix first to get the coordinate relative to other frames. Explanation is in this video.

I am reading directx11 book. And the following ones are the problem and solution in this book.

> 17. Suppose that we have frames \\$A\\$ and \\$B\\$. Let \\$p\_A=(1,-2,0)\\$ and \\$q\_A=(1,2,0)\\$ represent a point and force, respectively, relative to frame \\$A\\$. Moreover, let \\$Q\_B=(-6,2,0)\\$, \\$u\_B=\left(\frac{1}{\sqrt 2},\frac{1}{\sqrt 2},0\right)\\$, \\$v\_B=\left(-\frac{1}{\sqrt 2},\frac{1}{\sqrt 2},0\right)\\$ and \\$w\_B=(0,0,1)\\$ describe frame \\$A\\$ with coordinates relative to frame \\$B\\$. Build the change of coordinate matrix that maps frame \\$A\\$ coordinates into frame \\$B\\$ coordinates, and find \\$p\_B=(x,y,z)\\$ and \\$q\_B=(x,y,z)\\$. Draw a picture on graph paper to verify that your answer is reasonable.
>
> $$\begin{align} p\_B &= \begin{bmatrix}1&-2&0&1\end{bmatrix} \begin{bmatrix} \frac{1}{\sqrt 2}&\frac{1}{\sqrt 2}&0&0 \\ -\frac{1}{\sqrt 2}&\frac{1}{\sqrt 2}&0&0 \\ 0&0&1&0 \\ -6&2&0&1\end{bmatrix} \\ &= \begin{bmatrix}\frac{3}{\sqrt 2}-6&-\frac{1}{\sqrt 2}+2&0&1\end{bmatrix} \\ &\approx\begin{bmatrix}-3.88&1.29&0&1\end{bmatrix} \end{align}$$

I cannot understand how the coordinate relative to frame \\$B\\$ can be figured out by multiplying the coordinate relative to frame \\$A\\$ to the transformation matrix, not a inverse one.

Is there any material to study more or did I understand the problem in wrong way?

# Answer
> 0 votes
Note that the given \\$Q\_B, u\_B, v\_b, w\_b\\$ vectors are defined "with coordinates relative to B". That means they're already baking-in the inverse of frame B.

Whoever wrote down that \\$Q\_B\\$ position vector in "coordinates relative to B" had to find the origin of A in the world, and inverse-transform that point by frame B to find the corresponding point in frame B's coordinates, and similarly for the other offset vectors.

All this problem has really done is just give you the rows of the matrix \\$M = A(B^{-1})\\$ and asked you to assemble them and use the resulting matrix to transform two vectors.

They don't give you any description of A and B in terms of a third coordinate system, so you don't have the inputs you'd need to compute the inverse of B on your own anyway. All you have is the relative transformation from points in A to B.

If you took the inverse of matrix \\$M\\$, you'd get \\$M^{-1} = B(A^{-1})\\$, the relative transformation from points in B back to A.

---
Tags: mathematics, directx, linear-algebra
---


# Question
Title: Displaying a Scratch Project (.SB2) file within a Delphi EXE FIle
I would like to Display a Scratch Project (.SB2) file within my Delphi EXE file. I would like to know if it is possible to display and build the Scratch Project into your Delphi Project.

I wish to make a small game in Scratch and then use the game within my Delphi Application without the need of the Scratch 2 IDE. Perhaps a 3rd party delphi tool or component or something that can help me achieve this would also be very nice. So basically I want to host the Scratch game within my Delphi app.

Is this possible? How can this be done? (I am using Delphi 10.3.2 Rio and Scratch 2 Offline Editor)

# Answer
> 2 votes
Turbowarp.org can convert scratch projects to .exe if that is what you mean. You need to upload your project and go to package project. Scroll down and there will be a bunch of things you can convert your project to.

For .exe I would use the Electron \[Your Computer Type\] Application.

---
Tags: delphi, scratch
---


title: Storing game data on user end?

text:
# Question
Title: Storing game data on user end?
A thought occurred to me after seeing this question: Storing data - think character data for an online game - on the user\`s computer is definitely less safe (maybe an understatement) than on a server under your control, but...

* Is such a mechanism feasible? (while preventing cheating and such, of course...) If yes - why is it not used? Is it just me who hadn't seen it?

Some elaboration and ramblings:

A hypothetical advantage to this would be a need to store VERY little data on the server itself while still being able to handle a HUGE bookkeeping for the character, recording amounts of data you wouldn't dream of while storing the data on your server (think looking back on the exact date of your first attack in a game... sweet, useless, nostalgia :) ).

(Of course, there's a limit to how much you would do this way as well - your user isn't likely to condone a 1GB game save file... or they would... who knows. Maybe an option for what data to keep could give users the choice between conservative and extensive logging of their adventures?)

Take the following example: I think that an attempt to:

* Store a hash of the user's data on the server.
* On the next run, request the data from the user\`s end.
* Hash it.
* Compare the hashes.

is bound to fail.

The user could change the data on his end after the verification. I'm assuming there will always be a 'hole' somewhere even if the programmer utilizes tons of checks throughout the game, verifying every action.

This could very well be a reason for not doing this... just remember I'm asking about feasibility, not practicality.

There are some more considerations, of course:

The user's data being at their hands can be less safe and less available. They could lose it, have it stolen, forget their flash drive containing the file at home etc etc.

But it could also mean that the server has very little data on it to be compromised - say, if all of the user's data will be in their file, and the server will only be able to verify its authenticity via hashing mechanism and whatnot.

It will also be very easy to back up a server containing so little data.

The mechanism for the user should be a simple encryption/signature of the data file... or is that bound to fail as well?

# Answer
Yes, you can create a hash of the player's savegame. But it comes with some drawbacks.

Any online game which is supposed to not allow rampant cheating needs an authoritative server which handles all game mechanics. In order to do that, the server needs the whole savegame data. That means the client needs to upload the whole savegame to the server on login anyway. By calculating a cryptographic hash on the server and saving that hash on the server, the server can make sure that the savegame isn't tampered with.

During the gameplay, the server sends regular incremental updates to the clients save-state so it can save them. Each of these small updates should also include the new cryptographic hash of the savegame calculated on the server.

However, this scheme has two problems:

1. When the player loses their savegame, they lose their whole progress. This can be quite devastating, because online games are often played for a very long time. Maybe you could offer some kind of cloud backup service, but that begs the question why you aren't storing the savegame on your game-server to begin with.
2. Imagine the server sends an update and the client crashes while receiving it. Now the save-state on the client is still the old, but the server already expects the new. So the server will not allow the client to login anymore. A possible solution might be to also allow older savegames by having the server keep the past `n` signatures, but then a cheater could just crash their client whenever a bad event in the game happens to undo it.

But the actual question is why you would do this at all. Storage space isn't that expensive and I could hardly think of an online game where you would save more than a few kByte of data per player. Single player games with a large open world can create quite large savegames, but in an online game the world-state is shared between all players, so you only need to save it once, not once per player.
> 3 votes

# Answer
user2962533 says this is an answer, so here it is.

> Long story short: Always assume that the client is a lying, cheating bastard.

i.e. assume that local saves are corrupt, invalid, cheated, shared, hacked and otherwise containing wrong, outdated, or cheated values. No matter how it's encrypted, hashed, or verified, the client executable can always *itself* be hacked to incorrectly report the hash of the data it's sending or do any number of untoward things with the data. If you have to send the save data itself to the server, you haven't saved network bandwidth at all you've simply moved it around.

There's no advantage to using local saves except to provide an offline/single-player experience. Which is a good thing! Players like it when they can play in a completely offline experience, even when they can't use that same data in an online experience.

Some games (such as Borderlands) don't give a crap if the data is cheated, and this is a perfectly valid way to handle a game *so long as* there is no competitive aspect (high score lists, etc). Dungeon Defenders 1 had this problem where items would get hacked in and then sold in the in-game markets resulting in people who legitimately obtained the items to feel that theirs had been de-valued. This was possible because there was little/no central server authority (host client had authority, server only maintained save data).

Dungeon Defenders Eternity attempted to fix this. Server had authority over not only saves, but game instances, including item drops etc. (although the game was still received quite negatively by the community for several unrelated reasons).

> Long story short: Always assume that the client is a lying, cheating bastard.
> 2 votes

# Answer
There are two different scenario's for keeping data *on the client* safe *from the client*

**The client is not allowed to see the data**

I'm assuming that you mean encrypted to prevent unauthorized inspection by the end user? If so then the answer is no. This cannot technically be done. It's the reason those DRM systems all get 'cracked'... They were broken to begin with. You cannot share a secret with someone and then order them to forget it.

The reason is that the game (which is running in an environment under the user's control) *needs access* to that information. So you would need to supply the encryption key to the user (or at least to the game running on the user's machine) so there is no way to keep it secret as advanced users can inspect the memory of the running game, dump it to file, set breakpoints etc. If that key is in there, they will be able to get it out somehow.

**Protect data on the client from changes by the client**

Now if you only need to protect against changes, you may be able to get away with storing *some* of the data only on the client. Say you want to allow the user to select a photo, but you want to make sure it is not an offensive or pornographic image or something. You could let the user upload the photo to the server, then approve or reject it and only it it's approved, store a hash of the approved photo on the server, *then throw the actual image data away*. The server would send the hash + location/id of the photo to the clients, which would then fetch the actual image data from the other peer client. But they would *verify* that the photo wasn't replaced by some other one by checking whether the hash of the photo matches the hash the server sent and only accepting it (and showing it in the game) if it does.

So in this scenario, the user would be able to change the photo, but could not trick the server or other clients into accepting those changes.
> 1 votes

# Answer
I just needed to make the data more difficult to temper than usual, so I ended compressing it with the LZ algorithm using the light weight lz-string JavaScript library.
> 0 votes

---
Tags: client-server, savegame
---


title: How do you make a hold note like in FNF

text:
# Question
Title: How do you make a hold note like in FNF
I want to make a longnote like in the game Friday Night Funkin.

If you don't know FNF this is the long notes: https://www.youtube.com/watch?v=dXZ5Zmnk6Yg

Code:

```
if (Input.is_action_pressed("up")) or (Input.is_action_pressed("down")) or (Input.is_action_pressed("right")) or (Input.is_action_pressed("left")):
        mouseheld = true
    else:
        mouseheld = false
    if (isLongNote == true) and (Input.is_action_just_pressed("up") and touching == true and sprite.rotation_degrees == 0) or (Input.is_action_just_pressed("down") and touching == true and sprite.rotation_degrees == -180) or (Input.is_action_just_pressed("right") and touching == true and sprite.rotation_degrees == 90) or (Input.is_action_just_pressed("left") and touching == true and sprite.rotation_degrees == -90):
        createAEffect()
        print(mouseheld)
        if mouseheld == false:
            Singletons.bad()
            queue_free()
        print(mouseheld)
        # COMMENT HERE
        if mouseheld == true:
            print('rlly good')
            Singletons.sick()
            queue_free()
        else:
            print('...')
            Singletons.good()
            queue_free()

```

The problem is at where I put a comment, I tried to put a yield function (basically wait a second and see if the mouse is still held) but the yield function (yield(get\_tree().create\_timer(1)), "timeout") didn't work (for some reason doesnt work inside of a function)

Is there a better way to do this?

# Answer
> 0 votes
I used a system like this

```
if holdNote > time:
        print('t')
        holdNote = 0
        holdTheNote = false
        Singletons.sick()
    if holdTheNote == true:
        holdNote += delta
    if holdTheNote == true and ((Input.is_action_pressed("up") == false and sprite.rotation_degrees == 0) or (Input.is_action_pressed("down") == false and sprite.rotation_degrees == -180) or (Input.is_action_pressed("right") == false and sprite.rotation_degrees == 90) or (Input.is_action_pressed("left") == false and sprite.rotation_degrees == -90)):
        if holdNote < (time * 0.75):
            print('t2')
            Singletons.bad()
        if holdNote >= (time * 0.75):
            print('t32')
            Singletons.good()
        holdTheNote = false
        holdNote = 0
    if (isLongNote == true) and (Input.is_action_just_pressed("up") and touching == true and sprite.rotation_degrees == 0) or (Input.is_action_just_pressed("down") and touching == true and sprite.rotation_degrees == -180) or (Input.is_action_just_pressed("right") and touching == true and sprite.rotation_degrees == 90) or (Input.is_action_just_pressed("left") and touching == true and sprite.rotation_degrees == -90):
        createAEffect()
        holdTheNote = true

```

---
Tags: godot
---


# Question
Title: Can I remake a game and freely distribute it? or at least privately keep the remake?
So I want to remake an old game and I don't know if it's possible to give my remake for free, and I'm planning to copy the assets like sounds and art, so can I give my remake to friends?

If not, can I **still** make it as a hobby project and privately keep my project?

# Answer
> 8 votes
If the game, assets, etc. do not belong to you (ie. you did not create them yourself without copying from another source, or pay to obtain a licence to those assets), you do not have permission to redistribute them. Not even for free. Not even if you conclude the game is "old" or "abandoned" - if it was made in the last 70 years (which covers all video games), it's still protected by US copyright laws and likely by similar laws in other jurisdictions.

With regard to doing so "privately" - well, if you keep it private, how would a rights-holder or law enforcement know to chase you down? That doesn't necessarily make it legal or ethical - just from a practical standpoint, you might be able to evade consequences as long as what you intended to be private remains so. If the game were to leak outside of your private circle, that could again open you up to legal risks.

If you want to substantially recreate an old game for enjoyment or learning purposes, a safer way to do so is to create an *homage*. Use the original game as inspiration, but change things to make them your own. Make or source your own art and sound assets that you have licence to use. Experiment with tweaks to the mechanics. Write your own story, etc. Make it your own creative work, even if it borrows heavily from the conceptual structure of the original. This puts you on much better legal footing to share the game, show it off as a portfolio piece, or possibly even sell it.

---
Tags: copyright
---


# Question
Title: Unity Hub crashing on startup (black screen) because of missing projects
My Unity Hub is suddenly refusing to open. The first time I launch it I get an error message:

> The Hub as \[sic\] encountered a critical error and must close. You can report a bug using our bug reporter tool

Reporting the bug seemingly does nothing, unless it sends the telemetry in the background with no visual feedback. Launching the Hub again opens a black window.

I have some projects on a network attached drive that I am not always connected to. The last lines of %AppData%\UnityHub\logs\info-log.json are related to one of those projects:

```
{"timestamp":"2022-08-19T16:20:17.526Z","level":"error","moduleName":"App","message":"[\n  \"Failed to start Unity Hub, reason: Error: EPERM: operation not permitted, open '\\\\\\\\192.168.0.202\\\\[path to project]\\\\hubInfo.json'\"\n]"}
{"timestamp":"2022-08-19T16:20:17.526Z","level":"error","moduleName":"App","message":"[\n  \"Error: EPERM: operation not permitted, open '\\\\\\\\192.168.0.202\\\\[path to project]\\\\hubInfo.json'\"\n]"}
{"timestamp":"2022-08-19T16:20:17.527Z","level":"error","moduleName":"ErrorBox","message":"[\n  \"EPERM: operation not permitted, open '\\\\\\\\192.168.0.202\\\\[path to project]\\\\hubInfo.json'\\n\" +\n    \"Error: EPERM: operation not permitted, open '\\\\\\\\192.168.0.202\\\\[path to project]\\\\hubInfo.json'\"\n]"}

```

but there is also the following error:

```
{"timestamp":"2022-08-19T16:20:16.441Z","level":"error","moduleName":"LicensingSdkService","message":"[\n  \"Failed to connect to pipe: 'Unity-LicenseClient-[my Windows username], pid: undefined'\"\n]"}

```

I've seen forum posts about Unity Hub not launching when external drives containing projects are disconnected, so I am suspecting my NAS setup to be the culprit here. My questions are:

* Does Unity Hub really break if a project you opened once is no longer available? Or is my issue the licensing thing?
* Is there a workaround? Maybe making the Hub "forget" the project... which I think you can do in the GUI... but... well you get the issue. :)

# Answer
The problem here is that

> Unity requires the use of memory-mapped files to work correctly, which in some operating systems doesn't work well or at all over network shares; due to that, opening projects from network shares is not supported. \[source\]

This thread in the Unity forums has a solution that worked for me (thanks to DMGregory for sharing the thread as a comment!). You can make Unity Hub forget about your network shared project with the following steps:

> 1. Open Registry Editor (search it in your start menu)
> 2. Find the folder called HKEY\_CURRENT\_USER/Software/Unity Technologies/Unity Editor 5.x
> 3. Find RecentlyUsedProjectPaths (Be informed that there can be multiple if you have many projects on your Hub's list
> 4. Double click or Right Click/Modify to see its path which matches the one that caused the error and delete it
> 5. Try to launch again, if it does not work, re-install Unity Hub too.

I agree with the poster of the thread that this issue resulting in a fatal crash is very weird, and at the very least Unity should warn that projects on network shares are unsupported.
> 1 votes

---
Tags: unity
---


# Question
Title: Blank 2.2 KB sized PNG costs 2.1 MB in Unity? What does this represent? What to do?
I am starting to work on optimization for my app. I need to understand the information Unity displays about file sizes. For example, just to prove a point, here is a 2.2 KB completely blank PNG which in Unity when set to use as a UI image (for UI Toolkit) registers as 2.1 MB:

What does that represent? I have heard it is the size in RAM this will take while this image is in use. Is that correct?

I think Unity applies its own compression on these images during build. But does it mean this empty graphic would use 2.1 MB RAM during runtime if displayed?

I am building for mobile so it is important for me to get system resource use as low as possible. These sizes seem not to depend on the content of the image but rather just the pixel size (height and width) so I suspect the best principle is to make all files for this usage as small physically as possible using Sprite/splicing instead to fill space.

Or would an equally stretched sprite take up the same space at runtime?

# Answer
PNG compression works by predicting the next pixel from the pixels that came before.

If the image is completely blank, ie. every pixel is *exactly the same* as the pixel that came before, then that prediction is *very easy*, so you can get tiny file sizes even for high-resolution images. That makes it a misleading benchmark to use here.

The trouble is, GPUs cannot read PNGs. They need to be able to seek to different spots in the texture at random, but to do that with a PNG, you'd need to read and do calculations on the data for all pixels before the one you're trying to read before you could determine its colour.

So PNG textures need to be decompressed to use for rendering. One way to do that is to unpack them to literal RGBA8: 8 bits per colour channel, 32 bits per pixel (bpp).

Working that out for your image, that's 1490 x 376 pixels x 32 bpp = 17 928 680 bits = 2 240 960 bytes = 2.137 MiB.

This seems to indicate that because you've set the texture type to "Editor GUI and Legacy GUI", Unity is assuming you need lossless handling of this image, so selecting "Automatic" under the import format options is defaulting to RGBA8.

That 2.137 MiB is the amount of video RAM it will take to use this texture in your scene. If you need to edit the texture from a C# script, then you'll also need a corresponding 2.137 MiB of main RAM for the CPU-side copy of the texture.

There are also GPU compression formats that work differently \- typically using a fixed number of bits per pixel (bpp). This is important for realtime rendering - the fixed bitwidth of each block of pixels means you can calculate exactly what memory offset to seek to when you want to sample a specific part of the texture, rather than needing to scan and decompress all the pixels leading to that one as PNG does. This means we can work with them directly from their compressed format, rather than decompressing them to full 32 bpp RGBA data.

For instance, if we store this texture in DXT-5, it will break the image into 4x4 blocks, rounding your image size up to 1492x376, then compress each block to 8 bits per pixel. That's about 547.84 kiB, or about a quarter of the size as uncompressed. You can play with the options in the format and compression drop-downs to find the right trade-off between memory size and visual quality for your needs.

Increasing the rendered size of this texture by displaying it on a scaled-up sprite does not increase the amount of RAM it takes to store. So reducing resolution is a great way to save on texture memory - SDF textures make great use of this, by helping you get crisp lines even on scaled-up textures, when you want a flat-colour/gradient vector art look.
> 51 votes

---
Tags: unity, textures, sprites, memory-efficiency, unity-ui
---


# Question
Title: I want to delay 3 sec to load next level after the collision in C#
I need to delay the load new level by a few second. Please help.This is the script I need to use:

```
void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Enemy")
    {
         score = score + 50;
         Destroy (gameObject);
         /*Here I need to wait for 3 sec then it should load the next level*/
         SceneManager.LoadScene(nextLevel);
    }
}

```

I have tried this code but this doesn't update my score and don't wait and don't even load the next level:

```
void OnCollisionEnter2D(Collision2D col)
{
    Debug.Log ("Collision");
    if (col.gameObject.tag == "Enemy")
    {
        score = score + 50;
        Destroy (gameObject);
        StartCoroutine (WaitForIt (3.0F));
    }
}

IEnumerator WaitForIt(float waitTime)
{
    yield return new WaitForSeconds(waitTime);
    SceneManager.LoadScene(nextLevel);
}

```

# Answer
> 5 votes
You are destroying the GameObject on which this script is running as soon as it collides with an enemy. (`Destroy (gameObject);`)

That means it can't wait 3 seconds before loading the next scene - in 3 seconds' time, it will no longer exist and so it can't run any scripts at all!

You'll want to either delay the object's destruction until after the delay, or move the delay logic into a script you don't destroy (like a game state manager of some kind)

**Edit:** here's an example...

We can put a ScoreManager somewhere else in our scene, on an object we don't plan to destroy:

```
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class ScoreManager : MonoBehaviour
{
     // This lets other scripts in the scene find this single instance without searching.
     static ScoreManager _instance;
     public ScoreManager GetInstance() { return _instance; }

     // Inspector variables so we can view our score, and configure scene loading.
     public int score;
     public string nextSceneName;
     public float waitTime;

     // Ensure the instance is ready by the time it's needed.
     void Awake()
     {
         _instance = this;
     }

     // This replaces the work that the ball was doing previously.
     public void ScorePointsAndEndScene(int pointsScored)
     {
         score += pointsScored;
         StartCoroutine(WaitAndLoadScene());
     }

     IEnumerator WaitAndLoadScene()
     {
         yield return new WaitForSeconds(waitTime);
         SceneManager.LoadScene(nextSceneName);
     }
}

```

Now your ball script can just worry about destroying itself, leaving the score & scene management to your other script:

```
void OnCollisionEnter2D(Collision2D col)
{
    Debug.Log ("Collision");
    if (col.gameObject.CompareTag("Enemy"))
    {
        ScoreManager.GetInstance().ScorePointsAndEndScene(20);
        Destroy(gameObject);
    }
}

```

# Answer
> -1 votes
I suggest you use Invoke. It's pretty simple, and the documentation is pretty clear, too.

http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

# Answer
> -1 votes
I have solution in how to delay 3 second after reload level but I dont try to have a score here: You must have an object which has collision with your main Object Ex: Obstacle and main Object is Rocket(tag:Player) This script is link to Obstacle (3f is 3s)  then this is script is link to Rocket

---
Tags: unity, timer, scoring
---


# Question
Title: Simple deform modifier (bend) preserve UVs
What is the best way to minimise stretch when bending a plane? I'm making a road kitbash to use in Unity and would like the road markings to remain a consistent size when the road bends (I'm using more complex markings than just lines). Here I've added a texture to a straight and curved section to illustrate the problem:

I've tried adding and sliding edge loops lengthwise but they have no effect. I've tried skewing the UVs (scaling the longer edge smaller and vice versa) which does correct the scale problem, but then the shapes rotate and don't line up with a straight section if placed next to it.

Here's an example of what I'm trying to achieve - the markings are correctly oriented perpendicular to the road and are all of the same size:

I achieved this using a bunch of planes in an array, but as there will be thousands of markers in the scene, I'd prefer to use larger meshes for long sections of road to keep the draw count down. Also, the road has an asphalt texture and any stretching would be noticeable close up; again, this could be solved with separate meshes for the roads, but I'd then need transparent textures for the markings, which would add tons of overdraw. I could use UV islands, but again, extra draw calls.

# Answer
After much torturing of UV maps I conclude it's usually not going to be possible to get a neat result - mapping a 2D image on a non-linear plane (or 3D shape) will always yield stretching somewhere.

One solution is to hide the stretching in your scene, either rotated away from the camera or obscured by other objects.

In this case I solved the issue by using separate meshes for the markings that sit on top of the asphalt mesh with a transparent shader. That way I could planar map the asphalt, and as the markings are in thin strips, stretching could be minimised even around corners, as manipulating the UV map is much easier when you have less UVs to work with.
> 0 votes

---
Tags: unity, blender, uv-mapping
---


# Question
Title: Calculate normal and plane orientation using 4 3D points
I have 4 points as `Vector3` in 3D space that shape a plane. How can I calculate the plane normal direction these four points create together, and express it as a `Quaternion`?

# Answer
> 1 votes
First, we'll average together the vertical and horizontal edges of your quad to get two vectors, pointing in the directions of the x and y axes of the transform gizmo in your diagram:

```
var x = C - A + D - B;
var y = C - D + A - B;

```

The z direction is then

```
var z = Vector3.Cross(x, y);

```

We can turn this into a quaternion using:

```
var planeOrientation = Quaternion.LookRotation(z, y);

```

---
Tags: unity, c#, vector, quaternion, linear-algebra
---


# Question
Title: Using a JS Query to work as an HTML Anticheat?
So, I have a project, its a "cookie clicker" by definition, and I wish to work out how I can protect the game from users being able to edit `<button id="cooker" onclick="cookieClick(1)"></button>` and setting `(1)` to like `(123129)`.

I tried a few things first: JQuery: I tried using an old on() function with a dom searching function, and then to run an alert saying "Dumb Hacker! Im corrupting your save data" and then of course it would run Function `clearDat()` then function `corrupt()` which clears the localstorage data and sets it to an invalid value (usually wounds up as NaN) which prevents them from Playing.

Unfortunately the cookieclicker was editing the program so hastily, that it was "changing" the button above, and I wound up getting a million alerts (And because I was using a windows based HTML editor, I was getting WINDOW alerts, which i had to spam esc and try to delete the alert function and rerun the whole game, it was a pain)

I also tried a similar method using an old JS function, but it wound up not working.

I think you may see where im getting at, I'm really stuck in a pickle.

Heres the current code: https://hatebin.com/tgsdqzhzlc

# Answer
> 0 votes
Try to set the `onclick` function in your JS code. Example (pure browser JS):

```
document.querySelector("#cooker").onclick = () => { cookieClick(1); } // need to get loaded behind the button in the code

```

with JQuery, this would be

```
$(document).ready(()=>{// make sure assign this only after loading the button in the browser
    $("#cooker").click(() => { cookieClick(1); }); // hook button with function
});

```

In addition, I recommend you to obfuscate your code with a tool like this.

To recreate the button and make it harder to cheat, try something like this:

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TestPage</title>
</head>
<body>
    <div --button-position><!--Here Spawns your Button--></div>
    <script>
        // OBFUSCATE THIS
        (()=>{
            // HERE ARE YOUR FUNCTIONS
            function recreateButton(){
                const div = document.querySelector("[--button-position]"),
                 btn = document.createElement("button");
                div.innerHTML=""; // KILL OLD THINGS
                btn.id = "cooker";
                btn.innerText = "Click"; // TEXT IN THE BUTTON
                btn.onclick = () => {
                    alert("You clicked the button");// DO WHATEVER YOU WANT TO DO ON BUTTON CLICK
                };
                div.append(btn);
            }
            recreateButton(); //CREATE BUTTON FIRST TIME, CALL THIS FUNCTION IF YOU WANT TO RECREATE IT, LIKE ON CLICK, OR EVERY 10 SEC
            // HERE YOUR CODE TO EXECUTE ON LAUNCH
        })();
        // UNTIL HERE
    </script>
</body>
</html>
```

NOTE: you can only make it harder to cheat, but **not** impossible, because all of the code will be running on client.

---
Tags: javascript, anti-cheat, clicker
---


title: Simulate Keyboard Button Press

text:
# Question
Title: Simulate Keyboard Button Press
I am trying to simulate an SDL keyboard button press (using C). I have looked up the SDL info pages online but I still don't have anything that consistently works.

I have the following (removed the interrupt handling, creation of windows etc.)

```
while(1){
    SDL_Event user_event;
    user_event.type = SDL_SCANCODE_LEFT;

    SDL_PushEvent(&user_event);
    SDL_PumpEvents();

    const Uint8 *state = SDL_GetKeyboardState(NULL);

    if (state[SDL_SCANCODE_LEFT]) {
        printf("LEFT PRESSED");
    }
    if (state[SDL_SCANCODE_RIGHT]) {
        printf("RIGHT PRESSED");
    }
}

```

I never see the 'LEFT PRESSED' string printed out, although when I press the right arrow key (from keyboard) I see the respective output generated. It appears like the left key press is never being pushed on the state var.

Any help would be greatly appreciated.

# Answer
I believe you are constructing your `SDL_Event` incorrectly.

`SDL_Event` is a union, with the `type` field (`SDL_EventType`) used for determining what fields are actually in use. For keyboard events, use the `SDL_KEYDOWN` event type, and the `key` field (`SDL_KeyboardEvent`) for the keyboard specific data.

So the following should work:

```
SDL_Event e;
e.type = SDL_KEYDOWN;
e.key.type = SDL_KEYDOWN;
e.key.timestamp = 0;
e.key.windowID = 0;
e.key.state = SDL_PRESSED;
e.key.repeat = 0;
e.key.keysym.scancode = SDL_SCANCODE_LEFT;
e.key.keysym.sym = SDLK_LEFT;
e.key.keysym.mod = KMOD_NONE;

```

To be certain, you can use a debugger to capture what SDL itself does on keypress, so you can simulate this keypress in your custom event.
> 1 votes

# Answer
I use SDL quite a bit but I never use the PumpEvents function. I find that SDL\_PollEvent() is the best way to go for SDL input.

Check out the following code, hopefully this helps you with your problem:

```
bool getKeyState(const char* key)
{
    bool status = false;

    const Uint8* keyboard = SDL_GetKeyboardState(NULL);

    if (keyboard[SDL_GetScancodeFromName(key)]) {
        status = true;
        // If you want to print out the key press details
        //std::cout << "Key pressed: " << SDL_GetScancodeName(scanCode) << " (Scancode: " << scanCode << ")" << std::endl;
}

    return status;
}

int main()
{
    bool running = true;
    SDL_Event events;

    while (running)
    {
        SDL_PollEvents(events);

        if (getKeyState("C"))
        {
            // will trigger if C is pressed, put your action here
        }
    }

}

```
> 0 votes

---
Tags: sdl, c, keyboard, sdl2
---


# Question
Title: How to achieve 2.5D billboard sprite effect? (Don't Starve-like)
I'm trying to re-create the same effect of sprites/billboards that all entities in a game such as Don't Starve have.

What is the best way of doing this in Unity? Certain things come to mind:

1. Have a script that at all times perfectly rotate the object to directly face the camera. This seems very inefficient.
2. Hard-code the rotation of all objects at a certain angle so that they look flat to the camera. This seems inconvenient since I want to use my Q and E keys to rotate the camera 90 degrees (to be able to view the world from 4 directions).
3. Some sort of billboarding tool that Unity already has?

Since my camera rotation can change, I need all of the sprites to rotate in real time, so that at all times they face the camera. Are sprites even used for this, or is something else used to display the entities? (like billboarding, I'm not very familiar with how it works).

For context, I am planning to just use a regular 3D world where the camera will be angled down to look at the entities, and I want to achieve an effect similar to this:

# Answer
If you need to change rotation potentially every frame, then a script that runs every frame is pretty much the way to go.

In the example screenshot there are maybe 30 sprites on screen. It would be very difficult to cause a noticeable performance impact from doing *anything* a mere 30 times per frame. So as TomTsagk says in a comment, you should definitely test out this simplest, most direct option first, and profile it to verify whether there's any real problem that might force you to do something more complex.

If your camera only rotates in discrete hops, you could set up this script to run only when the camera moves (so, in the same script where you listen for the Q/E key press to start the camera move, you also fire off the billboarding update). Then at least it's not running redundantly when the camera angle stays fixed.

You want to orient the sprites or quads to face along (the negation of) the camera's forward vector. That means you don't need to change the sprite rotation when the camera translates, only when it rotates.

Technically, you could also accomplish this by abuse of a particle system, which have built-in billboarding options. Those compute new billboarded quads for every particle every frame without significant performance impact, even for thousands of simultaneous particles on screen. But the indirection of routing all your sprite positioning and animation updates through a particle buffer is likely to get onerous and sap more productivity than it is worth.

Lastly, you could implement the billboarding effect in a shader, repositioning the vertices to snap them to face the camera just before rasterizing the sprite. This is a little complicated to do without breaking sprite batching though, as the vertices would somehow need to figure out where the sprite's pivot is, to rotate the billboard around that. Normally that info has already been baked down by that stage of the pipeline, so it would be extra work to reconstruct.

So, I'd say: try the simple rotation script first. Profile it. If you find it has an unacceptable cost, update your question with your findings and we can explore potential fixes. But those fixes are themselves complicated enough to be a net drain on your productivity if they're not truly needed.
> 1 votes

---
Tags: unity, camera, sprites, 2.5d, billboarding
---


# Question
Title: How to make a collision object within a viewport detect mouse inputs?
I am working on a 2D game with a spatial node (a 3d node) inside a viewport. Nodes within the viewport should be able to detect user input from what I can find online, but for some reason it doesn't seem to work for me.

My tree holds the viewport in a viewportcontainer. The node within the viewport handles the effects of detection. In a standalone scene, the node detects mouse inputs without any problems.

The code of the spatial script:

```
extends Spatial

func _on_Area_input_event(camera, event, position, normal, shape_idx):
    if (event is InputEventMouseButton):
        print(get_parent().name)

```

Furthermore, I made sure that:

* `Handle Input Locally` within the viewport is `true`
* `Disable Input` in Gui within the viewport is `false`
* `Object Picking` in the viewport is `false`
* The viewport container is not blocked by any other nodes

# Answer
What you are doing is correct for `_input`. I have covered it in another answer.

Turns out that the requirement for `_input_event` (and the `"input_event"` signal) are different:

* Set `gui_disable_input` ("Disable Input" in "Gui") to false.
* Set `physics_object_picking` ("Object Picking" in "Physics") to true.

---

You also want to make sure that any `Control` that overlaps the area you are interested in has `mouse_filter` ("Filter" in "Mouse") set to "Ignore". Including the `ViewportContainer` itself. This is because `Control`s will take priority (even if the `Control` is behind what you are trying to interact with).
> 0 votes

# Answer
I had a similar problem and was able to forward the input events to the viewport in an attached script like this: (The reference to the viewport may need to be adjusted)

```
func _input(event):
    var viewport : Viewport = get_child(0)
    viewport.physics_object_picking = true;
    viewport.unhandled_input(event)

```

The script must be added to the viewport. `physics_object_picking` must be `true`. It doesn't work with `_unhandled_input`. The forwarding must be done in the `_input` function.

See also: this confirmed error report.
> 0 votes

---
Tags: 3d, godot, mouse, viewport, gdscript
---


title: Imitate simplified bird-flight behavior

text:
# Question
Title: Imitate simplified bird-flight behavior
I am developing a first-person player movement in which the player should "fly" in the direction of his local forward vector.

This is working perfectly fine, however, when I turn the player to face other direction (rotate the y rotation axis), the force that has been added till this point, keeps significantly affecting the rigidbody so it moves the object towards the wrong direction, and it takes a lot of résistance force to move towards the "new" direction I am facing.

I'd optimally love to have a bit of "drifting" affect, so it maintains a realistic touch. I'm trying to achieve a behavior that is pretty much identical to a car behavior, so when the object is turning towards a direction, the object will actually almost instantly move towards this direction, maintaining its current velocity.

To make it clearer, here's an illustration of the current behavior:

Here's an illustration of the desired behavior:

This is the current code I'm using:

```
        //Add force up
    playerRB.AddForce(Vector3.up *  wingForceUpMultiplier * forceUserInput, ForceMode.VelocityChange);
       //Add force forward
    playerRB.AddForce(forwardDirection * wingForceForwardMultiplier * forceUserInput, ForceMode.VelocityChange);

```

I am not necessarily looking for a complex-physics solution, it can be a simple workaround if there is any.

# Answer
> 0 votes
If you want the velocity to rotate with the character it is easiest to just set the velocity manually, rather than control it with forces. The "best way" to code that is probably goind to depend on how you are rotating the character itself (for example, if you are using a `Quaternion`, you can just multiply the `rigidbody.velocity` by the same `Quaternion`.

A simple solution might be to do something like this right before the step where you add forces:

```
playerRB.velocity = forwardDirection * playerRB.velocity.magnitude;

```

But a more interesting one would be to handle this where the character is rotated:

```
void rotateCharacter(){
    Vector3 previousVelocity = playerRB.velocity;
    //now whatever code you use to rotate the character...
    playerRB.velocity = (forwardDirection*(1-driftAmount) + previousVelocity.normalized*driftAmount) * previousVelocity.magnitude;
}

```

Where `driftAmount` would be a value between 0 and 1, that controls how much inertia your character retains when turning (0 is no inertia, 1 is the character keeps moving as if it hadn't turned).

---
Tags: unity, physics, rigidbody
---


# Question
Title: How would I save texture along with other data in binary file in Unity?
So I have a save method that can save data to a binary file and another function that saves just the texture. I would like to save both of them in a same file. I guess I would need to create a serialization surrogate for the Texture2D (I did this for some other types like Vector3 and Quaternion) but I can't find anywhere how would I do it for texture. I am currently saving texture like byte array and I guess that could help but I am not sure how to add it to other data.

Here is my code for saving the data:

```
public static bool Save(string fileLocation, string saveFilename,object saveData)
{
    BinaryFormatter formatter = GetBinaryFormater();

    if (!Directory.Exists(fileLocation))
    {
        Directory.CreateDirectory(fileLocation);
    }

    string path = fileLocation + "/" + saveFilename + ".save";
    FileStream file = File.Create(path);
    formatter.Serialize(file, saveData);
    file.Close();

    Debug.Log("Save to: " + path);
    return true;
}

```

And here is the one for the texture:

```
public static bool SaveTexture(string fileLocation, string filename, Texture2D textureToSave)
{
    if (!Directory.Exists(fileLocation))
    {
        Directory.CreateDirectory(fileLocation);
    }

    byte[] byteArray = textureToSave.EncodeToJPG();
    string savedFilename = fileLocation + "/" + filename + ".jpg";

    File.WriteAllBytes(savedFilename, byteArray);
    Debug.Log("File saved at: " + savedFilename);

    return true;
}

```

# Answer
One problem with binary file formats is that it is difficult to tell where one block of data ends and another block starts.

A common method is to prefix every variable-length block of data with an integer which states its length in bytes, and then read that many bytes. So your file would consist of:

* 4 bytes stating the length of the binary data in bytes
* The data
* 4 bytes stating the length of the texture in byte
* The texture

An alternative approach is to begin the file with a fixed length index which lists all the file positions where the chunks start and end. This has the advantage that you can load individual chunks by seeking within the file. If you only need a small part of the file, for example for a preview image, you don't need to process the whole file from start to end.

You can get the length in byte created by a BinaryFormatter by not passing it a FileStream but a `MemoryStream`. You can then check the number of bytes with the `.Length` property and you can write it to a file using `memoryStream.CopyTo(fileStream);`.

Untested code, but it should kind of work like this:

```
// serialize the saveData object to memory
MemoryStream memory = new MemoryStream();
formatter.Serialize(memory, saveData);
memory.Seek(0, SeekOrigin.Begin);
// Create the file
FileStream file = File.Create(path);
// write the length of the save data
file.Write(BitConverter.GetBytes(memory.Length));
// write the actual save data
memory.CopyTo(file);
// write the length of the texture
file.Write(BitConverter.GetBytes(byteArray.Length));
// write the texture
file.Write(byteArray, 0, byteArray.Length);
// close the file
file.Close();

```

For reading the file, you can load individual bytes from a FileStream using the Read method. In order to convert 4 bytes into integers, you could again use the BitConverter with the `BitConverter.ToInt32` method, or you might consider to wrap the FileStream in a BinaryReader, because that allows you to use methods like `.ReadInt`.
> 1 votes

---
Tags: unity, c#, file-format
---


# Question
Title: How to get vertices array from UIElements Label class (using reflection)?
I am trying to access the per letter vertices array in the UIElements (UI Toolkit) Label Unity class.

# Background

A Label of this type can be created for example with:

```
using UnityEngine.UIElements;

Label label = new Label();
label.text = "This is a test";
label.style.unityFontDefinition = FontDefinition.FromFont(Resources.Load<Font>("font-path"));
label.style.fontSize = 40;
VisualElement rootVE = gameObject.GetComponent<UIDocument>().rootVisualElement;
rootVE.Add(label);

```

(To use this you must go Game Object \> UI Document, then right click in assets, create blank UI Document, and drag it onto game object's "source asset field" with this script.)

# Objective

I am trying to get the per letter vertices of a Label of this nature. I was instructed by a Unity developer:

**"The vertices of letters are currently internal as this area is still subject to change and we are not ready to expose it publicly. If you need the data you could access it through reflection, and it is located here (as of 2022.2) : m\_Label.uitkTextHandle.textInfo."**

# Problem

I can get `uitkTextHandle` but can't find `textInfo` within it. I have tried:

```
foreach (var propertyInfo in typeof(Label).GetProperties(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)) { //gives uitkTextHandle
            Debug.Log("PROPERTIES " + propertyInfo.Name);
        }

foreach (var propertyInfo in (typeof(Label).GetProperty("uitkTextHandle", System.Reflection.BindingFlags.NonPublic| System.Reflection.BindingFlags.Instance)).GetType().GetMembers(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)) { //NO TEXTINFO FOUND
            Debug.Log("PROPERTIES " + propertyInfo.Name);
        }

```

And while I can get the `uitkTextHandle` this way, I cannot cast it to access textInfo within it (as it is a protected class) and I otherwise can't find any textInfo inside it.

```
        var uitkTextHandle = typeof(Label).GetProperty("uitkTextHandle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(testLabel, null);

```

Am I doing something wrong perhaps, or might the Unity Admin have given me the wrong information? This is my first time using Reflection so I am not sure.

How would I get the vertices array that they say I should be able to this way in a format I can use? What am I still missing?

Thanks.

# Answer
I'm not familiar with these classes, so it's possible that something else is the probelm, but having worked with Reflection before my first instinct is that the `BindingFlags` are to blame. See, the thing is by default you only get `public` members, but if you specify `BindingFlags.NonPublic`, like you are doing, then you **only** get `NonPublic` ones.

So, to get all the members in that instance, you need `BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance`.

Pretty annoying, if you ask me.
> 1 votes

---
Tags: unity, c#, user-interface, code-reflection
---


# Question
Title: Applying texture in a circular rotation to 2D object
I am trying to apply texture along the ring by using shaders. I am trying to avoid unnecessary mesh creation. I am trying to achieve it by using Shader Graph in Unity however I couldn't make it work by modifying Vertex position. I assume that it has to be done by changing vertices since the texture should appear in a circular shape.

To be more clear; I am trying to create this line by only using Checkerboard or checkboard-looking assets.

What I tried was to create the x,y positions with sin(x) and cos(y) with a time to create circular vertices however wasn't successful.

Does anyone have any idea how to achieve this shader?

# Answer
> 1 votes
How about this?

I'm assuming you want this on a quad. Of course, for a different mesh it would be a different story. To answer what I think is the deeper question here, when you are trying to map a texture to your mesh in a weird way, you don't want to modify the vertices' positions, but instead the UV coordinates.

---
Tags: unity, 2d, shaders, textures
---


# Question
Title: How to add a save/load game function to a Lua/C++ game engine
I'm curious what the best approach would be to save the current state of my game. The lua scripts contain the gamestate, but also some gameplay related info that doesn't need to be stored as part of a savegame.

Should I split my lua scripts into a 'saveable state' part and pure gameplay stuff like dialogs?

What would you recommend for a store/restore mechanic? I could serialize the info to JSON and just store it as a textfile, and on load set all the values in the lua state I suppose?

A alternative could be to have C++ load all relevant info from the Lua state, and store it in some format..but that seems more work than just serializing some lua tables.

As an example, here is one object inside a level that contains both gameplay logic (`onOpen`) and state info (`opened`):

```
skull = {
            opened = false,
            rect = { 64, 29, 14, 16 },
            sprite = "entrance_door_skull",
            dialogs = {
                look = "It's the skull of some creature. Its meaning seems quite clear: death lurks inside.",
            },
            onOpen = function(self, scene)
                if not self.opened then
                    addMove("skull", 1000, 0, -12, function ()
                        SceneGameEntrance.actionItems.skullKey.isVisible = true
                    end)
                    addDialog("As if by magic, the skull rises.")
                    self.opened = true
                else
                    addDialog("It is already open.")
                end
            end
        }

```

# Answer
The way I've done it in the past in `C++` is to create a `struct` that only holds the information that a save needs.

For example, if you have a game where you need to save/load what levels has the user completed, you can make a struct like so:

```
struct MySaveData {
    int level1Complete;
    int level2Complete;
    ...
};

```

Then when you want to save your game, you'd need to create a `struct` of type `MySaveData`, and fill in all the details of the current state, then save the `struct` itself in the desired location. Loading would work in a similar way, where you load data from a file and apply them to an object of that `struct`, then tell the game how to behave based on it.

You can also create a `class` instead with its own functions to automate some of the process.

Admittedly this is a not very scalable solution, and in a big game it wouldn't be very usable, but hopefully it can give you a head start for a more complex implementation.
> 1 votes

# Answer
As already pointed out, you should use a struct containing the data required for a single save. Usually however, this is very easy to cheat on, and if you want a more hardened approach, this is a much better way (I have used it myself in a game):

1. Instead of using a single struct, use JSON and serialize that JSON into a binary file. I don't know which language you're using, but I was using C99. I know for sure libraries exist for most (If not all) programming languages.
2. If possible, make that file inaccessible by changing its permissions. This is very platform specific and also involves process permissions, which I won't go into depth either.

You can go on to think of more ways to make sure your game can't be worked around. Although as long as it doesn't interact with other players, you may not even care at all about all this and just want stuff to work. If that's the case, the existing answer will be enough.
> 0 votes

---
Tags: c++, lua
---


# Question
Title: Baked AO in Substance Painter shows dark lines along some convex edges
A default cube exported from Blender shows this issue(several vertical lines are dark) of baked AO in Substance Painter. I encountered this issue from texturing a model with a layer of dirt where I surprising found some lines have much more dirt than others. After some tests I found out it was the AO problem. Eventually I tried to use this default cube from Blender to see if there would be any issue. Again there was but I really don't know why. I never change export settings in Blender and here are my Substance painter project and bake settings

# Answer
I think I find out the reason. If I click the button on the right of "High Definition Meshes" and select the exact same mesh from local disk then bake again AO and it solved. It's weird that I tried using "Use Low poly Mesh As High Poly Mesh" which I thought it would work from its literal meaning however it didn't. But If I only have one mesh do I have to select itself as high poly mesh every time just for baking AO? It's confusing.
> 0 votes

---
Tags: blender, ambient-occlusion, substance-engine
---


# Question
Title: Trying to debug slow DrawIndexed calls. 0.1+ms CPU usage per call
I have just been reworking my rendering pipeline. There is an issue I had noticed cropping up during this work but now its become constant and I cant figure out the cause.

Every call to `DrawIndexed` is costing 0.1ms - 0.2ms in CPU time. Even when there's no state change to explain it. I can just duplicate the call to `DrawIndexed` call 5 times in a row in the code (to eliminate the chance something else in the loop is impacting it) and all calls will have the same cost when looking in NVIDIA NSight (see below).

I have had frames where I will draw 100 times from the same vertex buffer with different offsets (each being a chunk of the map) and its the same. You can see in this trace there is a few without any state changes showing this behavior.

If I instead render the whole buffer at once the CPU usage is the same but the GPU barely changes, which makes sense, there is so few triangles there's almost nothing to do.

I've tried changing just about everything I can think of to try to tease out what's going on but nothing seems to to impact it.

Any ideas would be greatly appreciated.

I should just mention I am running a pretty high end system 9900k, 3090.

# Answer
Micro-timing of Direct3D calls is not an accurate way of measuring the CPU overhead of the API. There's a number of work queues involved to minimize kernel mode transitions.

Take a look at Microsoft Docs. It's a old article, but it's still relevant.
> 1 votes

---
Tags: directx11, performance
---


# Question
Title: How to use PUBG API to invite players to my lobby or custom game?
Is there a way to use the PubG API to invite some players to create a party or to invite to a custom game.

With this API it's possible?

# Answer
No, this is not possible according to the FAQ:

> Are custom Games available using the API? Can I use the API to create them?
>
> No, creating and controlling custom games is not possible with the API. However, data from custom games played within the last two weeks is available. Custom matches will show up alongside normal matches and they will have the attribute "isCustomMatch" set to "true".
> 1 votes

---
Tags: api
---