# Question
Title: How to ensure a malicious community server cannot impersonate a user?
I am using a server model similar to Steam or Minecraft:

* There are community servers run by players and a hub authentication server that I control.
* The client player logs into the game and receives a session token.
* When the player wants to connect to a server, they request from the authentication server to exchange their session token for a server session token.
* They then pass that server session token to the server which then checks with the authentication server if the token is valid, and if it is, the community server lets the client in.

My issue is, this gives the UGC server a lot of power. I know that if the UGC server is fully moddable, you can't stop a lot of stuff, but the main issue is that if a malicious admin intercepts this server session token packet from the client, the admin can use this to connect to an entirely new server pretending to be the client.

I need a solution to fix this and make a model similar to Steam or Minecraft's models. thank you.

# Answer
> 1 votes
Instead of jury-rigging your own solution, you should look at existing open-source solutions to this very problem. Like OpenID, for example.

OpenID works basically like this:

1. The client connects to the server, telling it its username.
2. The server connects the authentication provider, asking it to verify a login attempt for a specific username. This login attempt also gets an unique login id, which it tells both the client and the authentication provider.
3. The client connects to the authentication provider and tells it "I would like to perform the authentication for \[login id\]. Here are my credentials".
4. The authentication provider confirms that the credentials check out, and when that's the case responds to the server that the login with this id was successful.
5. The server lets the client into the game.

(Needless to say that all of this should happen through encrypted channels.)

Impersonation is impossible in this case because the login process requires direct communication between server and authentication provider. And because each login attempt gets an own unique ID, there is no opportunity for replay attacks.

If you would like to use this process, then please remember: **DO NOT INVENT YOUR OWN CRYPTO!** Anyone can come up with a security scheme they can't crack themselves. If possible, rely on a tried and tested open-source implementation.

---
Tags: client-server, modding, security, authentication
---


title: Dust trail when character runs

text:
# Question
Title: Dust trail when character runs
I'm making a 2D top view game (same perspective as the game *Forager*) in Unity. I want the game to be visually appealing, and want to add some details like dust particles. Whenever the character moves, I want dust-like particles trailing behind the character, almost as if the character is kicking up dust.

So something like this:

The particles are a little big in *Forager*, but this is similar.

I've used Unity's trail renderer before, but I only used it for making a straight line, and not multiple random particles like this. What should I do to achieve this effect?

Just general guidelines would be okay. I don't necessarily need a complete code, just some guidance because I don't know how to start.

# Answer
Attach a particle system to the character. Set "Simulation Space" to "World" instead of "Local", so the particles stay behind when the player with the particle system moves. You can use the "Emission over Distance" property to make the particle system only emit particles while the character is moving.

When you are using the URP or HDRP and feel adventurous, then you can alternatively use the new, graph-based particle system.
> 4 votes

---
Tags: unity, particles, trail-renderer
---


# Question
Title: Interpolate colors between vertex in a plane
So I have this plane generated with two different Perlin noises. It has mainly 3 regions, divided by color. I want to smooth out the lines, to create a "gradient" so there are no abrupt color changes:

Each zone corresponds to a biome which is decided by a PerlinNoise called Humidity and another one called Temperature, so each vertex receives a biome according to the following chart with its corresponding humidity and temperature vertices' height:

So this is my code (I commented almost every step):

```
        //CREATES the terrain material and geometry + adds the color attribute
        let TerrainMaterial = new THREE.MeshPhongMaterial({side:THREE.DoubleSide, flatShading: true,vertexColors: true});
        let TerrainGeometry = new THREE.PlaneGeometry(step, step, 16,16);
        TerrainGeometry.setAttribute( 'color', new THREE.BufferAttribute( new Float32Array(  TerrainGeometry.attributes.position.count * 3), 3 ) )
        const colors = TerrainGeometry.attributes.color;

        //The position like this is to create a grid so every tile is next to eachother
        let terrain = new THREE.Mesh(TerrainGeometry,TerrainMaterial)
        terrain.position.set(x, 0, z).multiplyScalar(step)
        this.experience.scene.add(terrain)

        // Create some variables
        const TemperatureVertices = TemperatureTerrain.attributes.position;
        const HumidityVertices = HumidityTerrain.attributes.position;
        let pos = TerrainGeometry.attributes.position;

        const lerp = (a, b, amount) => (1 - amount) * a + amount * b;

         //iteration through each vertex
        for(let i = 0; i < pos.count; i++){

            //gets temperature and humidity maps vertex height
           let temperature = TemperatureVertices.getY(i) * 2;
           let humidity = HumidityVertices.getY(i)* 2;

           //this function returns the biome according with the chart in the post by giving it temperature and humidity variables
           let BIOME = this.Biomes.determineBiome(temperature,humidity,new THREE.Vector2(x, z),i);

           //This retrieves the fractional part of the numer, ex: frac(-2.8) = 0.8 or frac(10.09) = 0.9
           var a = Math.abs(temperature) - Math.floor(Math.abs(temperature))
           var b = Math.abs(humidity) - Math.floor(Math.abs(humidity))

           //This variables determine the "blending zone", wich you will understand later
           let AMPLIFIER = 0.1;
           let AMPLIFIER1 = 0.9;

           //Instantiates the temperature and humidity variables
           let temperature_blending = temperature;
           let temperature_weight = 1;

           let humidity_blending = humidity;
           let humidity_weight = 1;

           //This is executed if the temperature is close to the next biome chart row/column
            if(a < AMPLIFIER){
                //This algorithm gives me like a percentage of how much the vertex is influenced by the other biome.
                let x = Math.abs(temperature);
                temperature_weight = (x - Math.floor(x)) / AMPLIFIER

                //here based on the temperature, I can detect what is the closer column-
                if(temperature > 0){
                    temperature_blending -= 0.5
                }else{
                    temperature_blending += 0.5
                }
                //here I repeat the process but backwards as my function has to work with negative numbers when the closest biome column is further away than the original one.
            }else if(a > AMPLIFIER1){
                let x = -Math.abs(temperature);
                temperature_weight = (x - Math.floor(x)) / AMPLIFIER

                if(temperature < 0){
                    temperature_blending -= 0.5
                }else{
                    temperature_blending += 0.5
                }
            }

            //here I repeat all the process but for humidity
             if(b < AMPLIFIER){
                 let x = Math.abs(humidity);
                 humidity_weight = (x - Math.floor(x)) / AMPLIFIER

                 if(humidity > 0){
                     humidity_blending -= 0.5
                 }else{
                     humidity_blending += 0.5
                 }
             }else if(b > AMPLIFIER1){
                 let x = -Math.abs(humidity);
                 humidity_weight = (x - Math.floor(x)) / AMPLIFIER

                 if(humidity < 0){
                     humidity_blending -= 0.5
                 }else{
                     humidity_blending += 0.5
                 }
             }

            //Once we get here, We have the original vertex biome and the closest biome to it (if it is in the blending zone: very close to another biome implying that it has to start blending with it)
           let BIOME1 = this.Biomes.determineBiome(temperature_blending,humidity_blending,new THREE.Vector2(x, z),i);

                //I am very lost from here, I also think that the way to calculate the weights is incorrect.

           //this calculate the average between both climatic factors
           let average = (humidity_weight+temperature_weight)/2

           //Here I try blending the colors between them using the average
           colors.setXYZ( i, lerp(BIOME.color.r,BIOME1.color.r,average), lerp(BIOME.color.g,BIOME1.color.g,average), lerp(BIOME.color.b,BIOME1.color.b,average));
        }

```

The result which doesn't look well:

So if you know how I can correct it, or if an algorithm already exists please tell me. Thanks a lot!

EDIT:

I got to make it work thanks to enter link description here steps. (note that the heights are rounded numbers by preset):

# Answer
> 0 votes
So you basically have a function that takes a coordinate, runs it through some noise, and outputs a biome, if I understand correctly? Biome blending is trickier than it might seem at surface value, but there's an approach I've been using that works well

* Scatter a bunch of points around your world, similar to how you would in Voronoi noise.
    + You can also use blue noise point distributions, e.g. Poisson if your world is finite and small.
* Evaluate the biome at each of those points.
* Figure out a circle size that will always contain points, use a falloff function to assign weights to nearby biomes, and perform a weighted average.

I wrote about it in more detail here: https://noiseposti.ng/posts/2021-03-13-Fast-Biome-Blending-Without-Squareness.html

Also I wouldn't suggest using actual Perlin for noise, at least not without something in place to fix its issues. A lot of sources talk about it, but it has strong cardinal axis bias. Noise should remind us of nature, not of the coordinate-space math under the hood. Better as a general rule to use Simplex or Simplex-type noise, or specifically 3D Perlin which has been rotated so that its cardinal planes are out of alignment. This library supports both: https://www.npmjs.com/package/fastnoise-lite/v/0.0.1

---
Tags: javascript, procedural-generation, tilemap, vertex, three.js
---


# Question
Title: Converting from global coordinates to local coordinates
I am trying to create a Radar/Minimap for the F1 2021 game in C#/WPF. Here is a image of what I am trying to replicate

In the image, the white car (my car) will always face the direction it is going. The blue car (other play car) will face relative to my direction.

I am given the following information

```
public float m_worldPositionX;           // World space X position
public float m_worldPositionY;           // World space Y position
public float m_worldPositionZ;           // World space Z position
public float m_worldVelocityX;           // Velocity in world space X
public float m_worldVelocityY;           // Velocity in world space Y
public float m_worldVelocityZ;           // Velocity in world space Z
public short m_worldForwardDirX;         // World space forward X direction (normalised)
public short m_worldForwardDirY;         // World space forward Y direction (normalised)
public short m_worldForwardDirZ;         // World space forward Z direction (normalised)
public short m_worldRightDirX;           // World space right X direction (normalised)
public short m_worldRightDirY;           // World space right Y direction (normalised)
public short m_worldRightDirZ;           // World space right Z direction (normalised)
public float m_gForceLateral;            // Lateral G-Force component
public float m_gForceLongitudinal;       // Longitudinal G-Force component
public float m_gForceVertical;           // Vertical G-Force component
public float m_yaw;                      // Yaw angle in radians
public float m_pitch;                    // Pitch angle in radians
public float m_roll;                     // Roll angle in radians

```

I am having trouble understanding the concept of worldForwardDir and worldRightDir, and how they differ.

Furthermore, I am wondering if it is even possible at all given the information above that I can transform the worldPosition coordinates into something usable by a 2D canvas.

# Answer
My guess would be that `m_worldForwardDirX/Y/Z` is a unit vector pointing forward from the white car in world coordinates, and `m_worldRightDirX/Y/Z` is a unit vector pointing right.

If you take the position of the blue car and subtract the position of the white car, you have a difference vector in world coordinates. If you project this vector on `m_worldRightDir` you get the relative x coordinate of the blue car, and if you project it on `m_worldForwardDir` you get the y coordinate. These x and y coordinates are the x and y of the blue car in your radar view.

Projecting a vector on another vector is done by taking the dot product of the two vectors.
> 0 votes

# Answer
Figured out the solution. Based off of Elliot's answer from this post How do I convert from the global coordinate space to a local space?

```
var deltaX = Car.m_worldPositionX - PlayerCar.m_worldPositionX;
var deltaZ = Car.m_worldPositionZ - PlayerCar.m_worldPositionZ;
double deltaYaw = Car.m_yaw - PlayerCar.m_yaw;

var radius = Math.Sqrt(deltaX * deltaX + deltaZ * deltaZ);
var phi1 = Math.Atan2(deltaZ, deltaX);
var phi2 = -PlayerCar.m_yaw;

var deltaPhi = phi1 - phi2;

var X = -(radius * Math.Cos(deltaPhi));
var Y = -(radius * Math.Sin(deltaPhi));

```
> 0 votes

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


# Question
Title: How to import files with texture in Blender?
I downloaded a Blender model from Google and it came with two folders: a "source" folder where is located the .blend file and a "textures" folder with all the image textures.

Whenever I open the .blend file, only the model shows without the textures. How would I be able to open the file with all the textures already implemented?

# Answer
> 0 votes
You can ask blender to look for the files it's missing by going to: `Info > File > External Data > Find Missing Files`. It will ask you to select the folder you want to be searched.

For more information you can look at this answer on the blender stackexchange: https://blender.stackexchange.com/a/5372/35312

You could also try to put the texture folder inside the source folder, and if that doesn't work to put the texture files and the blend file in the same folder.

---
Tags: blender
---


# Question
Title: Why the transform is never moving and reaching the last fifth last waypoint?
I have 5 waypoints ,each waypoint tagged and named as "Teleporter".

The Mover the blue cube is start moving to the first waypoint and then should move between all the other waypoints. but it's stopping on the waypoint before the last one.

And this screenshot show when the Mover stopped. The red's are the waypoints the Mover already visited.

This script is attached to the Mover :

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

public class Waypoints : MonoBehaviour
{
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;
    public List<Transform> positions;

    private int index = 0;

    // Start is called before the first frame update
    void Start()
    {
        if (moveToFirstPositionOnStart == true)
        {
            transform.position = positions[index].position;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (go == true)
        {
            Move();
        }
    }

    void Move()
    {
        transform.position = Vector3.MoveTowards(transform.position,
                                                positions[index].position,
                                                speed * Time.deltaTime);

        if (transform.position == positions[index].position)
        {
            //index += 1;
        }

        if (index == positions.Count)
        {
            index = 0;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Teleporter")
        {
            other.GetComponent<Renderer>().material.color = Color.red;

            index += 1;
        }
    }
}

```

I first tried to increase the index by 1 in this checking part :

```
if (transform.position == positions[index].position)
        {
            //index += 1;
        }

```

but it didn't reach the last waypoint so I tried and this is what I want to do in general to increase the index inside the OnTriggerEnter event but the same problem.

It's never reaching the last waypoint.

I also notice that when it's reaching the fourth waypoint and stop there that it's giving exception : ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. on the line :

```
transform.position = Vector3.MoveTowards(transform.position,
                                                    positions[index].position,
                                                    speed * Time.deltaTime);

```

Tested it again and this is working fine with this changes but with the OnTriggerEnter it's not working something inside the OnTriggerEnter make a problem not sure why and what.

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

public class Waypoints : MonoBehaviour
{
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;
    public List<Transform> positions;

    private int index = 0;

    // Start is called before the first frame update
    void Start()
    {
        if (moveToFirstPositionOnStart == true)
        {
            transform.position = positions[index].position;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (go == true)
        {
            Move();
        }
    }

    void Move()
    {
        transform.position = Vector3.MoveTowards(transform.position,
                                                positions[index].position,
                                                speed * Time.deltaTime);

        float distance = Vector3.Distance(transform.position, positions[index].position);
        if (distance < 0.01f)
        {
            other.GetComponent<Renderer>().material.color = Color.red;

            index += 1;
        }

        if (index == positions.Count)
        {
            index = 0;
        }
    }
}

```

# Answer
> 1 votes
Well, you get the exact error what went wrong. Your index counts to high and you try to access an element in the array that does not exist, your script crashes (and stops moving).

Now why it does not work with your OnTriggerEnter is, it counts the index to 5. And in your update you try first to move to index 5 in your List (which does not exist since it has only 5 entries and lists are zero based).

If you want to have it working with your OnTriggerEnter, either put this piece

```
if (index == positions.Count) {
   index = 0;
}

```

at the start in your `Move` or at the end in your `OnTriggerEnter` condition.

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


# Question
Title: How to apply brightness/contrast adjustment to a texture's pixels?
I'm trying to use a non-shader method to convert a (single-frame) Texture2D to one with different brightness/contrast.

Attempt so far uses: https://stackoverflow.com/posts/15408608/revisions

I'm not quite sure how to convert their 2 dimensional array to work with `Color32[]` or `Color[]` \- here is an attempt so far, but it does not compile because there is no `*` operator defined between `float[][]` and `Color32[]`.

    public static Texture2D BrightnessContrast(Texture2D tex,float brightness=1f,float contrast=1f,float gamma=1f)
    {

        float adjustedBrightness = brightness - 1.0f;
        // create matrix that will brighten and contrast the image
        float[][] ptsArray ={
        new float[] {contrast, 0, 0, 0, 0}, // scale red
        new float[] {0, contrast, 0, 0, 0}, // scale green
        new float[] {0, 0, contrast, 0, 0}, // scale blue
        new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha
        new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}};

        Color32[] pixels = tex.GetPixels32();

        for (int i = 0; i < pixels.Length; i++)
            pixels[i] = ptsArray * pixels[i];

        tex.SetPixels32(pixels);
        tex.Apply();

        return tex;
    }
```
</code></pre>

# Answer
> 1 votes
This is not a good use of a matrix. Just write it as a plain old float multiplication / addition (or power, if you're using gamma, which *cannot* be represented as a matrix operation).

```
public static float AdjustChannel(float colour,
           float brightness, float contrast, float gamma) {
    return Mathf.Pow(colour, gamma) * contrast + brightness;
}

public static Texture2D BrightnessContrast(Texture2D tex,
           float brightness=1f, float contrast=1f, float gamma=1f)
{
    float adjustedBrightness = brightness - 1.0f;

    Color[] pixels = tex.GetPixels();

    for (int i = 0; i < pixels.Length; i++) {
        var p = pixels[i];
        p.r = AdjustChannel(p.r, adjustedBrightness, contrast, gamma);
        p.g = AdjustChannel(p.g, adjustedBrightness, contrast, gamma);
        p.b = AdjustChannel(p.b, adjustedBrightness, contrast, gamma);
        pixels[i] = p;
    }

    tex.SetPixels(pixels);
    tex.Apply();

    return tex;
}

```

---
Tags: unity, c#, image-processing
---


title: Problem load data from playerpref

text:
# Question
Title: Problem load data from playerpref
So I want to make a merge idle game, but I have a problem loading data from `playerprefs`, I have an item that I bought from the store so `obj counts` are increasing but at the same time I want to check another item bought from the store, for example, I buy `obj1` twice, and `obj2` 3 times so `obj counts` are total of those items 2+3=5.

## What I've tried:

* I'm using for loop for that, but I am confused about how to check for another item.
* using a nested loop, still doesn't work.

## Conditions have met:

* when I bought from the store the `obj count` increased.
* when the object merged `obj count` decreased;
* save current object with `playerprefs.set("currItemBought+index,itemBought),`
* save current current obj index when buy obj.

## What I want:

* every time I start the game again I load data from the playerprefs then the object that spawns must be the same from I bought for example when I buy obj2 twice then when re-start, obj2 must spawn twice, or another example when I buy `obj1` once and `obj2` 3 times so when re-start must spawn `obj1` once and `obj2` 3 times so total `obj count` is 4.

## Preview:

https://youtu.be/vCi0I-YFwfQ

## My Script:

**Load Data**

```
    //load Data
    public void LoadData()
    {

        if (PlayerPrefs.HasKey("objCount"))
        {
            // get tier to save

            objCount = PlayerPrefs.GetInt("objCount");
            currHighesTier = PlayerPrefs.GetInt("tier");

            Debug.Log(objCount);
            Debug.Log("tier: " + currHighesTier);

            for (int i = 0; i < objCount; i++)
            {
                if (currHighesTier == i)
                {
                    SpawnObject(currHighesTier);

                }
                else
                {
                    SpawnObject(0);
                }
            }
        }
        else
        {
            objCount = 1;
            PlayerPrefs.SetInt("objCount", objCount);

            SpawnObject(0);
        }
    }

```

**Buy Item**

```
public void Buy_Object(int index)
    {
        currCharacter = UI_Manager.instance.characterDB.GetCharacter(index);

        for (int i = 0; i < UI_Manager.instance.shopItemsContainer.childCount; i++)
        {
            if (index == i)
            {
                if (Coin >= characters.characters[index].basePrice * (UI_Manager.instance.shopItemsContainer.GetChild(index).GetComponent<CharacterItemUI>().itemBought + 1))
                {
                    objCount++;
                    PlayerPrefs.SetInt("objCount", objCount);

                    Add_Coin(-characters.characters[index].basePrice * (UI_Manager.instance.shopItemsContainer.GetChild(index).GetComponent<CharacterItemUI>().itemBought + 1));

                    UI_Manager.instance.shopItemsContainer.GetChild(index).GetComponent<CharacterItemUI>().itemBought++;
                    PlayerPrefs.SetInt("currItemBough" + index, UI_Manager.instance.shopItemsContainer.GetChild(index).GetComponent<CharacterItemUI>().itemBought);

                    SpawnObject(index);

                }
                else
                {
                    Debug.Log("Not enough coin");
                }
            }
        }

    }

```

**Evolve when merging**

```
private void Evolve()
    {
        //Set object count
        GameManager.instance.objCount--;
        PlayerPrefs.SetInt("objCount", GameManager.instance.objCount);

        UI_Manager.instance.shopItemsContainer.GetChild(tier).GetComponent<CharacterItemUI>().itemBought--;
        PlayerPrefs.SetInt("currItemBough" + tier, UI_Manager.instance.shopItemsContainer.GetChild(tier).GetComponent<CharacterItemUI>().itemBought);

        evolve_particle.Play();

        LevelProgressUI.Instance.AddXP((tier + 1) * 25);

        tier++;

        gameObject.name = "Obj" + tier;

        GameManager.instance.CheckTier(tier);

        SetObject();
    }

```

**Check Tier**

```
 public void CheckTier(int tier)
    {
        if (tier > highestTier)
        {
            highestTier = tier;

            PlayerPrefs.SetInt("tier", highestTier);

            StartCoroutine(UI_Manager.instance.NewTier());

            characters.characters[tier].isUnlocked = true;

            UI_Manager.instance.UpdateUI(tier);
        }
        else
        {
            PlayerPrefs.SetInt("tier", tier);
        }
    }

```

\`Sorry for the preview I use youtube due to 1-minute videos. from the video when I restart the game the obj that was bought twice only spawned once.

# Answer
Your main error is, you do not iterate over all stored objects. `objCount` has the total amount stored which is not really helpful for loading the data.

Here is a small example how you could improve your LoadData. `Obj` is not really helpful as a description. And `PlayerPrefs.getInt` has an overload where the second parameter is the default value that you get when the key does not exists.

```
enum Spawnable {Seed, Sprout, Flower, Tree}

public void Start() {
    PlayerPrefs.SetInt("Item_" + Spawnable.Seed, 3);
    PlayerPrefs.SetInt("Item_" + Spawnable.Sprout, 1);
    PlayerPrefs.SetInt("Item_" + Spawnable.Tree, 2);
    LoadData();
}

void LoadData() {
    Spawnable highestTier = 0;
    int totalSpawnCount = 0;
    foreach (Spawnable toSpawn in Enum.GetValues(typeof(Spawnable)).Cast<Spawnable>()) {
        int spawnAmount = PlayerPrefs.GetInt("Item_" + toSpawn, 0);
        highestTier = spawnAmount > 0 ? toSpawn : highestTier;
        for (int amount = 1; amount <= spawnAmount; amount++) {
            Debug.Log(toSpawn);
            totalSpawnCount++;
        }
    }
    Debug.LogFormat("Highest Tier is {0}", highestTier);
    Debug.LogFormat("Total amount of spawned items is: {0}", totalSpawnCount);
}

```

The improvement is, all your objects are in order in a descriptive list and your evolve function might benefit from it as well.

The initial data is set as example in `Start` but it is missing the `Flower` to demonstrate how missing values are handled. The console is telling you how many objects are spawned from each type, you can just switch it to your own instantiate logic.
> 2 votes

---
Tags: unity
---


# Question
Title: Smoothing multiple combined vector translations
I am currently working on my arm/weapon rig for an fps game written in a custom engine. I am to the point where I am implementing the movement of the arms/weapon (hereby referred to as weapon), for example to illustrate movement while walking, movement when swinging arms with mouse, and movement when jumping. I am doing this by calculating vectors for each of these independently and then adding them together to produce a `finalVec` which is the location of the weapon rig in the scene.

So for example, if I want to move the weapon back by `0.03` units and down by `0.013` units at a speed of `0.1` units per second I create a Tweener as such:

`this->weaponPullBackTweener = std::make_unique<vel::Tweener>(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, -0.013f, 0.03f), 0.1f);`

I then call a method on this class every tick passing in the frame delta time and it produces a vector between the first and second initialization parameter. I use this same methodology for producing the other aforementioned vectors (minus the arm sway which is more complicated since it uses mouse input), and add them together, then set weapon translation to their summation as below:

```
glm::vec3 finalVec = sightPos;
finalVec += pullBackPos;
finalVec.x += swayXYPos.x + walkPos.x;
finalVec.y += swayXYPos.y + walkPos.y + jumpPos.y;

armRig->getTransform().setTranslation(finalVec);

```

This produces the following result which can be viewed in this video. It works, but since each vector completes it's cycle at a different rate, the result can be a bit jarring (most apparent when switching weapon from hip to iron sight aiming).

I've been attempting to come up with a solution to this for awhile now, and I seem to keep hitting a wall (as I am quite novice at game development). Therefore I am reaching out to see if anyone here would be able to suggest a methodology for correcting this, or implementing it in a different way as to smooth out the movement.

One thing that came to mind was maybe instead of using the vectors directly, finding the direction for each and then adding the directions together and using a constant velocity, but then since each needs to run at a different speed, they would end up not ending where they should end, unless I'm over/under thinking that potential solution?

# Answer
I saw your demo and it looks very cool! I had a little trouble interpreting the question so I am going to restate it and you let me know if I misunderstood you: Your goal is to tween (change over time) several vectors from a start value to an end value. And the issue is that the duration of these changes is not equal.

In other words, you want vector A to become vector A' over t seconds. And at the same time, you want vector B to become vector B' over t seconds (same t).

I think the issue here is that the magnitude of the translation varies between the cases. Instead of tweening based on deltaTime I would suggest lerping the position instead.

```
nextVal = lerp( curVal, goalVal, deltaTime * speedFactor );

```

Ideally, this approach can be applied separately to each vector and if the third argument is equal to 0.1 then all the vectors will progress 1/10 of the way to their goal. This may work well for a continuous operation where goal is constantly changing. But depending on your use case, you may have better results if you set a variable called lerpProgress and you reset it to 0 every time you have a new goal position and then increment lerpProgress overtime.

```
lerpProgress = Math.Clamp01( lerpProgress + deltaTime );
nextVal = lerp( curVal, goalVal, lerpProgress  );

```

And just to be clear here, you would be computing a nextVal for any of the vectors you are moving but lerpProgress would be shared.
> 0 votes

---
Tags: c++, vector, glm
---


# Question
Title: Scripting Language To Renderer Architecture
I am currently designing the scripting side of our engine. The idea is an entity-component system. That means most of the coding is done via jobs.

The language we are using is compatible to C. The actual implementation does not matter for this question. Basically, the application - written in C++ - calls the entry point for our scripting environment. User code is added to this environment, generating one library for client code and our code. Via some engine magic we then make the assembly aware of the jobs that were written by users. So far so good.

The design decision we are currently struggling with is how the scripting interacts with the renderer.

For that, a short brief of our architecture:

* Every module (Rendering, Audio, Physics) is laid out into dynamic libraries, so our scripting language can interact with them.
* Rendering is API-agnostic. Currently we have OpenGL and Dx12 in the making, OpenGL will get removed by Vulkan on the long run.
* The scripting language handles everything. Only the high-performance critical systems are C++ dynamic libraries.

That having said, when interacting with the renderer we have two concepts. We want to decide which one to implement, but are unsure. The techniques here are simplified, in the actual engine there are of course some managers etc. going on.

* 1. Every mesh instance issues a drawcall once per frame.
    + The renderer has a `draw` method
    + Requires fewer instructions
    + Every mesh calls `draw` for themselves, once per frame
    + Does mean that some meshes will be drawn before other entities even had their logic running
* 2. Every mesh instance issues a draw request once per frame.
    + The renderer has a `render` method
    + The assembly calls `render` after all jobs is finished
    + The GPU can run every drawcall at once
    + The GPU can only start rendering once the whole frame is finished on the assembly side.

Each of the systems has their pros and cons. Personally, system 2 makes the most sense to me as the renderer is fully responsible for rendering and only gets instructed. Furthermore, APIs like DX12 and Vulkan are already command-based, so this follows the API rules in some way.

Though I have seen many people do the drawcalls on a per mesh basis. There might be some advantages to that, but I feel like architecture 2 is more robust and scalable.

# Answer
> 1 votes
The second approach is better in general (with the exception of code that generates a new mesh each frame). The reason is that queueing request allows you to execute them in batch. And that opens plenty of optimizations. For example, use a single render call for many identical meshes. And if you are switching shaders, you can make of the render calls for each shader together, minimizing the number of times you switch shaders. You might even compile multiple meshes in a single buffer, so they can be a single call despite not being identical.

Just one note: make it transparent for the developer writing the scripts, they don't need to know about these or other similar optimizations (which would differ per rendering backend, by the way). And if it is going to be transparent, you can start by implementing the first approach (which is easier to implement), locking the interface, and switch to the second approach, without breaking scripting. In general, changes to the renderer should not break scripting. Design with that in mind.

Perhaps you are deciding between a push or a pull interface. For example, if the script will call a method to request something to be rendered, you have a push interface. On the other hand, if you have the script define a function that the rendering system calls and return whatever should be rendered, you have a pull interface.

Well, you say you are going to use an entity-component-system architecture. Thus, I believe it follows that scripts could attach a mesh component, and then you have the renderer system runs for each entity that has a mesh component attached and draw it queue it for rendering.

---
Tags: c++, architecture, scripting
---


# Question
Title: Converting UV coordinates to planar projection algorithm
I'm using an engine that implements a texture mapping technique where the texture map for each triangle is defined by a point(P) and 2 vectors(M, N) instead of per-vertex texture coordinates P defines the origin of the texture, M defines the horizontal end of the texture and N the vertical end The technique is better explained here: https://nothings.org/gamedev/ray\_plane.html

Now, given a triangle ABC and a UV for each vertex of the triangle i needed to compute the PMN values for those UV coordinates, thankfully an answer that describes an algorithm from UV -\> PMN already exists: https://gamedev.stackexchange.com/a/185429/147479

However i am now wondering if it's possible to construct different combinations of PMN(that would yield a correct result, small error margin is fine and expected)

Example using the UV -\> PMN algorithm: the triangle ABC with positions {20, -75, -40) {-30, 15, 60} {-5, 26, 63} and UV coordinates {0.2, 0.4} {0.2, 0.9} {0.8, 0.5} could yield the PMN coordinates {30, -75, 16} {32, -37, 90} {4, -13, -80} and the error rate could be 0.0005(which is acceptable) the error rate can be determined by running the UV -\> PMN algorithm, then converting the constructed PMN coordinates back to UV(algorithm described in the question i linked) and comparing the two (original UV's and the constructed ones from doing UV -\> PMN -\> UV)

A different combination could be something like {110, 54, -15} {44, -82, 16} {-14, -102, 130} it just has to match(small error margin is fine) the original UV coordinates (if it was converted back to UV coordinates)

Implementation of the algorithm DMGregory proposed:

```
            Vector3D pPrime = new Vector3D(65, -35, 77); // arbitrary point i picked
            while (true) {
                Matrix4d mat = new Matrix4d(
                        p.getX(), m.getX(), n.getX(), pPrime.getX(),
                        p.getY(), m.getY(), n.getY(), pPrime.getY(),
                        p.getZ(), m.getZ(), n.getZ(), pPrime.getZ(),
                        1, 1, 1, 1
                );

                //determine whether 4 points lie on the same plane or not
                if (mat.determinant() > 0.001) { // check against epsilon just in case
                    break;
                }

                double x = ThreadLocalRandom.current().nextInt(-200, 200);
                double y = ThreadLocalRandom.current().nextInt(-200, 200);
                double z = ThreadLocalRandom.current().nextInt(-200, 200);
                pPrime = new Vector3D(x, y, z);
            }

            Vector3D d = divide(pPrime.subtract(p), pPrime.subtract(p).getNorm());
            Vector3D mPrime = pPrime.add(m.subtract(p))
                    .subtract(d.scalarMultiply(m.subtract(p).dotProduct(d)));

            Vector3D nPrime = pPrime.add(n.subtract(p))
                    .subtract(d.scalarMultiply(n.subtract(p).dotProduct(d)));

```

Picking M, N values close to whole numbers:

```
            float eps = 0.07f;
            int i = 1;
            while (true) {
                List<Vector3D> newPMN = computeNewPMN(p, m, n);
                Vector3D pPrime = newPMN.get(0);
                Vector3D mPrime = newPMN.get(1);
                Vector3D nPrime = newPMN.get(2);

                double fractMX = mPrime.getX() % 1;
                double fractMY = mPrime.getY() % 1;
                double fractMZ = mPrime.getZ() % 1;

                double fractNX = nPrime.getX() % 1;
                double fractNY = nPrime.getY() % 1;
                double fractNZ = nPrime.getZ() % 1;

                boolean closeTo0 = abs(fractMX) < eps && abs(fractMY) < eps && abs(fractMZ) < eps && abs(fractNX) < eps && abs(fractNY) < eps && abs(fractNZ) < eps;
                float eps1 = 1f - eps;
                boolean closeTo1 = abs(fractMX) > eps1 && abs(fractMY) > eps1 && abs(fractMZ) > eps1 && abs(fractNX) > eps1 && abs(fractNY) > eps1 && abs(fractNZ) > eps1;
                if (closeTo0 || closeTo1) {
                    System.out.println("Found valid at " + i);
                    // do stuff with pPrime, mPrime, nPrime
                    break;
                }
                i++;
            }

```

where `computeNewPMN`contains the code mentioned above

# Answer
> 1 votes
Here's an algorithm to take the \\$PMN\\$ triangle given by my original answer, and replace it with an alternative \\$P^\prime M^\prime N^\prime\\$ of your choosing.

First: pick a new point \\$P^\prime\\$ arbitrarily. It needs to be outside the plane of \\$PMN\\$, but other than that you can put it anywhere you like. I expect you'll get less rounding errors the closer \\$P^\prime - P\\$ aligns with the normal to the plane of \\$PMN\\$ though.

Next, calculate the direction of displacement from \\$P\\$ to your new \\$P^\prime\\$:

$$\vec d = \frac {P^\prime - P}{||P^\prime - P||}$$

Use this to project \\$M\\$ and \\$N\\$ to a new plane through \\$P^\prime\\$, perpendicular to \\$\vec d\\$:

$$M^\prime = P^\prime + (M - P) - \vec d \left(\left(M-P\right)\cdot \vec d \right)\\ N^\prime = P^\prime + (N - P) - \vec d \left(\left(N-P\right)\cdot \vec d \right)$$

---
Tags: projection, linear-algebra, uv-mapping
---


# Question
Title: Ball's spin speed seems to change erratically after AddForceAtPosition impulse
I'm trying to make a billiard game, and trying to add "spin" (aka English) functionality. The way I'm using to add spin is by using AddForceAtPosition(). Here's the code:

```
if (Input.GetKeyDown(KeyCode.I))
{
    rb.AddForceAtPosition(-transform.forward * force, transform.position + offset, ForceMode.Impulse);
}

```

With offset being a vector3, that is currently (0,-0.5,0) , to simulate a bottom spin (aka Spin back/Screw back). But it's giving me very unrealistic results :  , the ball continues to gain torque even when there is absolutely no force being applied to it. As you can see in the code, it's a GetKeyDown() action, hence the force is only applied once. I'm using ForceMode.Impulse, but I don't get any better results with other force modes. Force value : 3 (tried multiple values, same results) Anyone knows why it happens? Thanks.

# Answer
As Zibelas suggested in the comments, this is due to the wagon-wheel effect:

> The wagon-wheel effect (alternatively called stagecoach-wheel effect or stroboscopic effect) is an optical illusion in which a spoked wheel appears to rotate differently from its true rotation. The wheel can appear to rotate more slowly than the true rotation, it can appear stationary, or it can appear to rotate in the opposite direction from the true rotation.

Here your ball is rotating *so* fast, the stripe that was facing the camera last frame rotates all the way around to the far side of the ball by the next frame, and what we see facing the camera is the *other* half of the stripe. But our eye will assume we're still looking at the same part of the stripe, which is not that far from where we last saw it, so we perceive a reduced speed of rotation based on that cue.

As the ball's rotation slows down, the other half of the stripe starts falling further and further behind where its counterpart was on the previous frame, which means we see a larger and larger visible change between frames, and paradoxically it looks like the ball is *speeding up*. But it's just an artifact of the mismatch between the strobing of the frame rate and the rotation period of the ball.

(One way to confirm this: write a script that logs the angular velocity of the ball, of the magnitude of that vector, on each frame. You'll see that numerically it's only decelerating, even if it *looks* like it's accelerating on screen)

Reducing your offset from the center can give it a more gentle spin, so you don't hit the extreme rotation rates where this effect appears.

Or, if you need high spin rates for your gameplay, you can use shader tricks to smear the visuals when they're moving too fast for a camera to capture them in a single frame's exposure. This motion blur will hide the cues our eyes are picking up on to perceive the wrong spin rate, so that the effect isn't distracting for your players.
> 0 votes

---
Tags: unity, physics, billiards
---


# Question
Title: Need help with locking the Y axis on camera
I am working on a small 2D platformer in Unity for my school project and I would like to lock my camera on Y axis (so it can move horizontally, but when the character jumps it doesn't follow the jump). I have found something on the internet, but I'm struggling with implementing it into my Smooth Camera Follow code that I currently have:

```
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform target;

// Update is called once per frame
void Update()
{
    if (target)
    {
        Vector3 point = GetComponent<Camera>().WorldToViewportPoint(target.position);
        Vector3 delta = target.position - GetComponent<Camera>().ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
        Vector3 destination = transform.position + delta;
        transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);

    }
}

```

# Answer
This is pretty trivial. Just save the locked `y` value you want into a variable, then override the y component of your `destination` point with that saved value.

```
public float dampTime = 0.15f;
private Vector3 _velocity = Vector3.zero;
public Transform target;

private Camera _camera;
private float _fixedHeight;

void Start()
{
    // Do this once, so you're not searching for the component
    // multiple times every frame.
    _camera = GetComponent<Camera>();

    // Cache camera y position.
    _fixedHeight = transform.position.y;
}

void Update()
{
    if (target)
    {
        // Don't need the full viewport point if all you want is the z.
        float depth = Vector3.Dot(
                       target.position - transform.position,
                       transform.forward
        );
        // I recommend caching depth too, and re-using the cached value,
        // to ensure rounding errors don't accumulate.

        Vector3 viewportFocus = new Vector3(0.5f, 0.5f, depth);
        Vector3 worldFocus = _camera.ViewportToWorldPoint(viewportFocus);

        Vector3 delta = target.position - worldFocus;
        Vector3 destination = transform.position + delta;

        // Override destination height.
        destination.y = _fixedHeight;

        transform.position = Vector3.SmoothDamp(
                                transform.position,
                                destination,
                                ref _velocity,
                                dampTime
        );
    }
}

```
> 1 votes

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


# Question
Title: Why does speed times delta-time give slow movement?
I'm using glfw's `glfwGetTime()` function to calculate my time between frames i.e `deltaT` but when I multiply my desired movement speed by `deltaT`, and subsequently put that product into my translate vector it moves the character extremely slow.

My fps is right now is around 1300fps average so `deltaT` should be around 800 microsecond, times my desired speed of 128 units/second I should be able to move my character from 0 to 336 in about 2.6 seconds. But for reference that operation is taking about 20 seconds at the moment.

`glfwGetTime()` returns a timestamp in seconds... never really seen this happen before if anyone has any idea or further insight about using deltas for input smoothing I would much appreciate.

This is the implementation function for taking a key event and updating the transform matrix.

```

void Layer::update(std::deque<Event>* eventStack, double deltaT)
{
    float Vy{0.0f};
    float Vx{0.0f};

    std::deque<Event>::iterator it = eventStack->begin();
    while(it != eventStack->end())
    {
        if((*it).getKey() == GLFW_KEY_UP && ((*it).getAction() == GLFW_PRESS || (*it).getAction() == GLFW_REPEAT))
        {
            Vy += 16.0f;//if specified key event is in stack, do something
            it = eventStack->erase(it++); //then erase the event from the stack, it's been handled
        }
        else if((*it).getKey() == GLFW_KEY_RIGHT && ((*it).getAction() == GLFW_PRESS || (*it).getAction() == GLFW_REPEAT))
        {
            Vx += 16.0f;//if specified key event is in stack, do something
            it = eventStack->erase(it++); //then erase the event from the stack, it's been handled
        }
        else
        {
            it++;
        }
    }

    transformation = glm::translate(transformation, glm::vec3(Vx * deltaT, Vy * deltaT, 0.0f));

    Vy = 0.0f;
    Vx = 0.0f;
}

```

And here is where I calculate my fps and `deltaT`

```
void Window::update()
{
    glfwSwapBuffers(_window);
    glfwPollEvents();

    double thisTime = glfwGetTime();
    _deltaT = thisTime - _lastTime;
    _lastTime = thisTime;
    _elapsedTime += _deltaT;
    if(_elapsedTime >= 1)
    {
        std::stringstream ss;
        ss << "FPS: " << _frames;
        glfwSetWindowTitle(_window, ss.str().c_str());

        _frames = 0;
        _elapsedTime = 0;
    }
    else
    {
        _frames++;
    }

}

```

# Answer
> 1 votes
The issue wasn't actually delta-time related at all, but rather an issue of only updating the velocity when a key event occurred, in discrete steps less frequent than the actual game frame rate.

My solution was to implement an EventHandler class which would still maintain an event buffer as before but also would update a set of booleans for each movement related key. These booleans can be polled at any time so that smooth frame by frame movement can be calculated without losing the ability to have interrupt events such as "press ESC to enter pause menu"

Here is the EventHandler update method

```
void EventHandler::update()
{
    std::deque<Event>::iterator it = eventStack.begin();
    while(it != eventStack.end())
    {
        if((*it).getKey() == KEY_UP)
        {
            if((*it).getAction() == KEY_PRESS)
            {
               upKeyPressed = true;
            }
            if((*it).getAction() == KEY_RELEASE)
            {
               upKeyPressed = false;
            }
            it = eventStack.erase(it++);
        }
        else if((*it).getKey() == KEY_DOWN)
        {
            if((*it).getAction() == KEY_PRESS)
            {
               downKeyPressed = true;
            }
            if((*it).getAction() == KEY_RELEASE)
            {
               downKeyPressed = false;
            }
            it = eventStack.erase(it++);
        }
        else if((*it).getKey() == KEY_LEFT)
        {
            if((*it).getAction() == KEY_PRESS)
            {
               leftKeyPressed = true;
            }
            if((*it).getAction() == KEY_RELEASE)
            {
               leftKeyPressed = false;
            }
            it = eventStack.erase(it++);
        }
        else if((*it).getKey() == KEY_RIGHT)
        {
            if((*it).getAction() == KEY_PRESS)
            {
               rightKeyPressed = true;
            }
            if((*it).getAction() == KEY_RELEASE)
            {
               rightKeyPressed = false;
            }
            it = eventStack.erase(it++);
        }
        else
        {
            it++;
        }
    }
}

```

And here it is implemented when we want to move the geometry

```
void Layer::update(double deltaT)
{
    float Vy{0.0f};
    float Vx{0.0f};

    if(EventHandler::upKeyPressed)
    {
        Vy += 128.0f;
    }
    if(EventHandler::downKeyPressed)
    {
        Vy -= 128.0f;
    }
    if(EventHandler::rightKeyPressed)
    {
        Vx += 128.0f;
    }
    if(EventHandler::leftKeyPressed)
    {
        Vx -= 128.0f;
    }

    transformation = glm::translate(transformation, glm::vec3(Vx * deltaT, Vy * deltaT, 0.0f));

    Vy = 0.0f;
    Vx = 0.0f;

}

```

Thank you to DMGregory for the idea.

---
Tags: input, glfw, deltatime
---


# Question
Title: How can I add ease in out for object rotation?
Now when I set the rotateText flag to true the object will rotate on the y and then when I set the rotateText flag to false the rotation will stop and the object will rotate back to it's original rotation.

but I want to add to it maybe using animationcurve and lerp or some other way ease in out for the rotation. so if the flag rotateText is true it will start slowly smooth to rotate to max rotation speed and when the flag is false it will slowly smooth rotate down to speed 0 until stop.

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

public class MyRotationTests : MonoBehaviour
{
    public Text textName;
    public float rotationSpeed;
    public bool rotateText = false;
    public string textToDisplay;

    private Quaternion originalRotationValue;

    private void Start()
    {
        textName.text = textToDisplay;
        originalRotationValue = textName.transform.rotation;
    }

    private void Update()
    {
        Vector3 namePos = Camera.main.WorldToScreenPoint(this.transform.position);
        textName.transform.position = namePos;

        if(rotateText)
        {
            textName.transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime);
        }
        else
        {
            textName.transform.rotation = Quaternion.Slerp(textName.transform.rotation,
                originalRotationValue,
                Time.deltaTime * rotationSpeed);
        }
    }
}

```

# Answer
This is empirical formula for easing in and out.

\\$1-sin(\frac{\pi}{2}(1-t))\\$

\\$sin(\frac{\pi t}{2})\\$

\\$t\in\[0,1\]\\$

Example code:

```
float time, easeDuration;

private void Update()
{
    const float HALF_PI = Mathf.PI / 2;

    time += Time.deltaTime;
    var t = Mathf.Clamp01(time / easeDuration);

    if(rotateText)
        t = 1 - Mathf.Sin((1-t) * HALF_PI); // ease in
    else
        t = Mathf.Sin(t * HALF_PI); // ease out

    float realRotationSpeed = rotationSpeed * t;
    // Use realRotationSpeed instead of rotationSpeed
}

```
> 1 votes

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


title: Size of an object based on a variable

text:
# Question
Title: Size of an object based on a variable
The code shown below is meant to change the size of a bullet based on a changing variable. But when I put this code in the create tab, the size of the bullet stays the same, regardless of the variable's value.

```
image_xscale = global.Pwr;
image_yscale = global.Pwr;

```

# Answer
> 1 votes
Place this code in the step of your object, not the create tab.

```
image_xscale = global.Your_variable;
image_yscale = global.Your_variable;

```

---
Tags: image, game-maker-studio-2
---


# Question
Title: Optimal way to find the closest entity to player with a restricted set of functions
The scripting engine of Skyrim (and Fallout 4) has an *interesting* function called FindClosestActor(x,y,z,radius). If you call it with x,y,z center coordinates and a radius, it returns the closest Actor (entity) in the given radius and if it fails to find any, it returns nothing.

The most common use-case would be for such a well-named function is to find Actors around the Player in a specific radius. Lo and behold, Player is also an Actor therefore you always get Player as the result of the function, making it completely impractical.

There are exactly two functions that can be used for finding an Actor in a given radius. Their (pseudo-)signature is the following:

```
FindClosestActor(x,y,z,radius) -> Actor | None
FindRandomActor(x,y,z,radius) -> Actor | None

```

**Question:** How can I find the closest Actor to the player in a close to optimal (least function calls) way using `FindClosestActor` and optionally `FindRandomActor`? How can we overcome the defective behavior of `FindClosestActor`?

##### Method I refuse to utilize

It relies on random too much. What if it was badly written internally? I think the only useful property of this algorithm is that if there are more than 1 Actor most of the time, it returns a non-Player Actor with 2 function calls with a 75+% reliability.

```
closestActor = FindRandomActor(playerX,playerY,playerZ,radius)
for i in 0..iterationLimit
  tmp = FindRandomActor(playerX,playerY,playerZ,radius))
  if distance(tmp, player) < distance(closestActor, player)
    closestActor = tmp

```

##### Idea #1:

Legend:
A1, A2: Actors where A2 is closer to the Player than A1
R: position where we find the closest actor
RP: Distance between R and P
P: Player
B: circle around P at distance "base radius"

1. Let R be an arbitrary midpoint between P and (circle) B and RP is the distance between R and P.
2. We run FindClosestActor(R, RP) and rotate R by some degrees (50° increments seem reasonably round) around P and repeat the process until we arrive to the original R position. During this process, we collect Actors and select the one that is the closest to P (which is A2).
3. If we reached the minimum Actor-Player distance limit, we return with the closest Actor we have at the moment.
4. Let R be the midpoint between A2 and P and repeat from step 2.

There are two issues with this algorithm.

* The degree increment means I can't perfectly cover the whole circle
* It looks pretty brute force. Even for 2 Actors, you might need 8 calls which is a lot

##### Idea #2:

Still not convinced that such a nondeterministic algorithm would be reliable but at least this one spends calculation time on really close Actors first.

```
closestActor = None
for i in MinRadius..MaxRadius
  for j in 0..iterationLimit
    tmp = FindRandomActor(playerX,playerY,playerZ, i))
    if tmp is not player
      closestActor = tmp
      break "for i..."

```

# Answer
I'm not familiar with CreationKit, but it looks like `FindAllReferencesWithKeyword` might be a better way to solve the problem. The documentation gives an example that returns all of the actors within a certain distance of the player & then removes the player from the results:

```
Actor Player = Game.GetPlayer()
ObjectReference[] kActors = Player.FindAllReferencesWithKeyword(ActorTypeNPC, 2048.0)

int playerIndex = kActors.Find(Player as Actor)
kActors.Remove(playerIndex)

```

After that, it should just be a matter of searching through the array for the closest element:

```
int closestElement = 0
float closestDistance = Game.GetPlayer().GetDistance(kActors[0])
int currentElement = 1
while (currentElement < kActors.Length)
  if(Game.GetPlayer().GetDistance(kActors[currentElement]) < closestDistance)
    closestElement = currentElement
    closestDistance = Game.GetPlayer().GetDistance(kActors[currentElement]
  endIf
  currentElement += 1
endWhile

```

Again, I'm not familiar with this scripting language, so there might be some syntax errors in the code above. I checked against examples in the reference, but I'm if it looks like I made a mistake on something, feel free to comment &/or edit in a correction.
> 2 votes

---
Tags: algorithm, geometry, optimization, skyrim-modding
---


# Question
Title: How to display the current rotation speed in the Update and how to limit the rotation speed to specific max rotation speed?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Rotations : MonoBehaviour
{
    public Text textName;
    public float rotationSpeed;
    public bool rotateText = false;
    public string textToDisplay;
    public float displayCurrentSpeed;

    public float rotationDuration;
    public float startAngle;
    public float stopAngle;
    public AnimationCurve curve;

    private float currentRotationTime;

    private void Start()
    {
        textName.text = textToDisplay;
    }

    private void Update()
    {
        Vector3 namePos = Camera.main.WorldToScreenPoint(this.transform.position);
        textName.transform.position = namePos;

        if(rotateText)
        {
            /*currentRotationTime += Time.deltaTime;
            var progress = curve.Evaluate(currentRotationTime / rotationDuration);
            var currentAngle = startAngle + (stopAngle - startAngle) * progress;

            textName.transform.rotation = Quaternion.Euler(0f, currentAngle, 0f);
            */

            if (currentRotationTime < 3f)
            {
                currentRotationTime += Time.deltaTime;
                textName.transform.Rotate(0, rotationSpeed * currentRotationTime, 0);
            }
        }
    }
}

```

Using the animationcurve is working fine but I want to make that the speed will increase slowly to maximum speed and that it will keep rotating on that maximum speed.

The problems is how to limit the rotation speed to maximum ? and how to display the current rotation speed to see the rotation speed get increasing ?

Doing :

```
if (currentRotationTime < 3f)

```

Is not limiting the maximum rotation speed.

# Answer
This seems to be working as I wanted. Though I wonder if I did it right and if there is a way to get to exactly speed 3.

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

public class Rotations : MonoBehaviour
{
    public Text textName;
    public float rotationSpeed;
    public bool rotateText = false;
    public string textToDisplay;
    public float currentSpeed;

    public float rotationDuration;
    public float startAngle;
    public float stopAngle;
    public AnimationCurve curve;

    private float currentRotationTime;

    private void Start()
    {
        textName.text = textToDisplay;
    }

    private void Update()
    {
        Vector3 namePos = Camera.main.WorldToScreenPoint(this.transform.position);
        textName.transform.position = namePos;

        if(rotateText)
        {
            if ((rotationSpeed * currentRotationTime) < 3f)
            {
                currentRotationTime += Time.deltaTime;
                textName.transform.Rotate(0, rotationSpeed * currentRotationTime, 0);
            }
            else
            {
                textName.transform.Rotate(0, rotationSpeed * currentRotationTime, 0);
            }

            currentSpeed = rotationSpeed * currentRotationTime;
        }
    }
}

```

Edit

Tried to remove the same rotation but then it will not keep rotating when it's reaching 3. I don't want it to stop when reaching to 3 but to keep rotating nonsotp at the reached speed 3.

```
currentSpeed = rotationSpeed * currentRotationTime;

            if (currentSpeed < 3f)
            {
                currentRotationTime += Time.deltaTime;
                textName.transform.Rotate(0, rotationSpeed * currentRotationTime, 0);
            }

```
> -1 votes

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


# Question
Title: Can I disable auto-correct on text fields in Godot?
## Background

I'm working on a word game and I found it kind of nice to use a hidden `LineEdit` as my text input. I hide it off screen, force focus on it, and then connect to its `text_changed` and `text_entered` signals to allow the player to type in and submit words. It works cross-platform and allows the user to use their keyboard for input instead of me having to build one myself.

## Problem

On mobile, the auto-correct of my keyboard causes some unwanted behavior in my game. It seems that when it offers spelling suggestions, it will mutate the contents of the text box in some ways I'm not expecting. It doesn't mess things up *too* much, but I'd like to just disable it.

## Research

I found that HTML has some attributes for inputs that appear to disable auto-correct. And I know from my personal experience that text inputs on some apps don't let me use auto correct like password fields.

I tried using the `LineEdit#secret` property, since it seemed like password fields might prefer to not use auto-correct, and it doesn't appear to make a difference.

# Answer
I don't think the option you are looking for is implemented in Godot. Be welcome to write a proposal.

I'm not sure what you are trying to build, but you might find useful to invoke the virtual keyboard with `OS.show_virtual_keyboard` (this method does nothing in desktop platforms).
> 0 votes

---
Tags: input, godot, text
---


# Question
Title: First Person shooter look direction abstraction for InputController, AIController and NetworkController
# The problem

Suppose I have a game where there are multiple Input Controllers:

* `LocalPlayerController`: Reads inputs from the keyboard/mouse/gamepad.
* `RemotePlayerController`: Reads input from the network packets.
* `AiController`: Takes decisions based on the environment.

My `Character` entitity could be a human player, or an NPC. It currently exposes methods like `moveForward`, `moveBack`, `strafeLeft`, `strafeRight`.

Those methods are called by each controller acordingly:

```
class LocalPlayerController {
    public void update(Character character) {
        if (Input.getKeyDown(W)) character.moveForward();
        if (Input.getKeyDown(S)) character.moveBack();
        if (Input.getKeyDown(A)) character.strafeLeft();
        if (Input.getKeyDown(A)) character.strafeRight();
    }
}

```

The same for the other kind of controllers:

```
class RemotePlayerController {
    public void update(Character character) {
        // Read network packets and call those 4 methods
    }
}

```

```
class AiController {
    public void update(Character character) {
        // Makes a decision based on the environment and call those 4 methods
    }
}

```

# The question

I know I can abstract the character movement (`moveForward()`, `moveLeft()`, etc) and interaction (`shoot()`, `openDoor(door)`, etc).

**Question: What would be the best approach to abstract the eyes/head looking direction?**

**Options:**

* **Option 1**: Have methods/properties that move the head direction based on yaw/pitch. For example: `setYaw(yaw)`, `setPitch(pitch)`, `getYaw()` and `getPitch()`. Inside each setter, they would limit the pitch and yaw to a maximum per game tick like `delta_yaw = max(delta_yaw, MAX_DELTA_YAW)`
* **Option 2**: Have methods/properties that set the look at target in world space where the head should look at. For example: `setHeadLookAt(target)`, `getHeadLokAt()`. Inside the class would store the current look at target xyz and rotate towards that point acording to a `MAX_DELTA_YAW`, `MAX_DELTA_PITCH`, etc.
* **Option 3**: Another different approach?

The first option seems suited for a `LocalPlayerController` because that's the naive way you normally read the mouse coordinates in the screen and adjust the deltaYaw and deltaPitch based on the deltaX and deltaY of the mouse.

The second option seems more suited for an `AiController` because normally you want your Ai to look to a certain target.

**What would it be the best option?** Please justify your answer with examples of **pros** and **cons** of each option acording to different input methods (mouse, AI, network).

# Answer
In general, it depends on the game. You say:

> The first option seems suited for a `LocalPlayerController` because that's the naive way you normally read the mouse coordinates in the screen and adjust the `deltaYaw` and `deltaPitch` based on the `deltaX` and `deltaY` of the mouse.

But not on every game you don't.

---

Let us keep in mind that both sound like high level abstraction to manipulate some transforms, plus animation. In fact, that is likely also true for the other movement methods.

Now, there is a common ground between `setYaw(yaw)` \+ `setPitch(pitch)` and `setHeadLookAt(target)`, and that is `setHeadLookDirection(direction)`. You can easily make a `direction` vector from `yaw` and `pitch`, and you can easily make a `direction` vector from a `target`. So you can implement your options 1 and 2 on top of it.

I'm not claiming this is the best option. I say it depends on the game and stand by it. However, if you are in a situation where both make sense. Well, both make sense, so have both, except have them as abstraction over a common ground.

Following what I can see of your architecture, you could wrap the character in another object - or otherwise define extensions for it - that allow you to use the preferred approach for the controller.

---

With that said, I'm not convinced this is the best way to decouple an entity from whatever controls it. If you change the methods on your character, you need to update the controller that use them, so what you have is loosely coupled, not decoupled. If they were decoupled, they could change independently. And, to be clear, loosely coupled is OK. But if you want truly decoupled, keep reading.

By the way, upon reading what I wrote below, I think I might be overengineering this - again, it depends on the game, I'm imagining a battle with many AI agents and cooperative multiplayer. Which might not be what you had in mind, so take it with a grain of salt.

This is the idea:

* Make all the attributes of the character read-only. No setters.
* Have the controllers create and send command objects. These could be serialized to be send to the network, or for storage and playback. This also means it does not matter from where the command objects come from.
* Then the engine will queue these command objects for the character, or characters. This also means there can be multiple controllers for a character - if that is something you want. Or a controller can control multiple characters at once.
* Have the character pull command objects from the queue. Some command objects will be primitive for the character, and the character executes them right away. For the rest, the character will give them to a translation service that queues other commands. So you can have commands as high level as necessary.
* Have a service locator that will allow the character to pick the service to translate commands. And the service locator could be injected on the creation of the character. This means that different characters might translate the same commands differently. Some might translate them to nothing, i.e. ignore the commands.

Now, the Director AI can create and send an command object that says "attack position X", and the individual characters can translate that to "go to position X" and "attack nearby enemies". And translate "go to position X" - via a path-finding service - to a series of move commands, or it could be ignored if the character cannot move or is too far away. And "attack nearby enemies" could translate to "if there is an enemy (find cover and attack)", which would make the character remember to execute "find cover" and "attack" when it becomes aware of an enemy (and, if you think about it, we might use the same command system as sensor system). And "find cover" can translate to another series of move commands via a cover service, and "attack" can translate to "aim" and "shoot" commands. So that "attack position X" can boil down to the same actions a player could make.

Consider also that you may even implement a chain of command where a character sends command objects to other characters. And it would just work that killing the commander will imply the soldiers don't get new orders.

That is how decoupled looks like.
> 1 votes

---
Tags: architecture, multiplayer, ai, input, first-person-shooter
---


# Question
Title: How to get/edit the script of the built-in "Character Controller" component?
I was using Unity's Character Controller component, but I found it very limited and wanted to tweak some things.

I thought about creating my own character controller from scratch, but it would be much easier if I could start with Unity's Character Controller script and just tweak what I need.

How can do that?

# Answer
The shipped CharacterController is located in the `UnityEngine.PhysicsModule.dll`. Now depending on the IDE you are using, you could still take a look at the source. For Rider the shortcut to search for everywhere is double left shift. Entering CharacterController and opening the file is decompiling as good as it can for a readable format. That does not mean you can make changes to the file and expect it to work.

But after taking a look at the soure, you will notice that there is no actual logic in the Controller. A quick google brought this one up: Source for CharacterController where the post claims, that Unity is just using the PhysX from the physics engine and wrote a wrapper for it.

You could now write a wrapper for the wrapper and just cherry pick the functionality you want or go right away with your own CharacterController. If you want to take a look at the full source of it, it should be available here: NVIDIAGameWorks PhysX
> 3 votes

---
Tags: unity, character-controller
---


# Question
Title: If I can add a Text above my player/object without a canvas then what do I need the canvas for?
In all tutorials they are using canvas for the text to put the text above the player/object.

Why not just make empty GameObject as child of the object you want to add the text above and add to the empty GameObject TextMesh and that's it ? What the canvas is giving me for this case when I want to put text above any object ?

# Answer
> 5 votes
The TextMesh component (or its superior alternative TextMeshPro) is perfectly fine if a naked text is all your want to show. That's what it's for. But a world-space canvas has benefits when you have more than one UI-element to attach to an object. Like, for example, a panel with a border and a background which contains the name, a health bar and a couple status icons. The main benefit in that use-case is that you can utilize the layouting capabilities of the canvas. You can design the layout of the canvas in 2d and then place the whole canvas as a single sprite-like object in 3d space.

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


title: How to change the pivot in Unity?

text:
# Question
Title: How to change the pivot in Unity?
I have a cube created in Unity scaled 5 times. The pivot of the cube is by default in center.

I would like to change the pivot to the one of the vertices.

How to do that ?

# Answer
unity does not import object pivot from 3ds-max or... but unity uses its own generated pivot point. if you want to switch position between global and pivot you can choose using options upper left of app screen.

simplest way to make a pivot for your object is to make an empty object and make you model object child of that object just by dragging it and drop it on that empty object. and move you child model object to be in right position. after that you can use transform of parent object so child object rotates on parent object position as pivot.
> 5 votes

# Answer
The pivot can be changed in Unity. The following code demonstrates how.

```
 public void PivotTo(Vector3 position)
 {
     Vector3 offset = transform.position - position;
     foreach (Transform child in transform)
         child.transform.position += offset;
     transform.position = position;
 }

```

I come across the code here when trying to rotate my game object around its center.
> 5 votes

# Answer
You can parent an empty GameObject to the cube you created and position it however you like, this will allow you to control any pivot you like if you use the parent game object.
> 3 votes

# Answer
I use this free asset to have the pivot be changed on a mesh, while in Unity (without needing to go back to 3ds max to fix it).

https://github.com/yasirkula/UnityAdjustPivot
> 3 votes

# Answer
Unfortunately in Unity modifying the actual pivots is not possible out of the box You can try out my asset here:

https://assetstore.unity.com/packages/tools/utilities/pivot-modder-152501

It allows you to modify pivot position and rotation conveniently from within the unity editor, it also provides you with various useful options like pivot snapping which allows you to manipulate the pivot more precisely. It also fits right within the inspector and needs no addition of components and opening windows from the editor.
> 2 votes

---
Tags: unity, pivot
---


# Question
Title: Planar projection texture mapping algorithm to UV coordinates algorithm explanation
I am using an engine that uses a texture mapper where instead of providing per-vertex UV coordinates a 3D point(P) and 2 vectors(M, N) is provided, the texture coordinates can be directly computed from the basis vectors.

Note: from this point onwards I'll refer to PMN as 3 vectors instead of a point and 2 basis vectors

P is the origin of the texture, M the horizontal end of the texture, and N the vertical end

Then 3 new 'magic' vectors are computed:

```
M.sub(P)
N.sub(P)
A = P.cross(N)
B = M.cross(P)
C = N.cross(M)

```

Then for each pixel(x, y):

```
S = Vector3f(x, y, 1)
float a = dot(S, A)
float b = dot(S, B)
float c = dot(S, C)

float u = texture.width * a / c
float v = texture.height * b / c
color = texture.pixels[u + v * texture.width]

```

The algorithm & derivation is explained more in depth here: https://nothings.org/gamedev/ray\_plane.html

Now i have found an algorithm that converts PMN vectors to per-vertex UV coordinates:

```
                        Point3D a = ... // first vertex of the triangle
                        Point3D b = ... // second vertex of the triangle
                        Point3D c = ... // third vertex of the triangle

                        Point3D p = ... // origin of the texture
                        Point3D m = ... // horizontal end of the texture
                        Point3D n = ... // vertical end of the texture

                        Point3D pM = m.subtract(p);
                        Point3D pN = n.subtract(p);
                        Point3D pA = a.subtract(p);
                        Point3D pB = b.subtract(p);
                        Point3D pC = c.subtract(p);

                        Point3D pMxPn = pM.crossProduct(pN);

                        Point3D uCoordinate = pN.crossProduct(pMxPn);
                        double mU = 1.0F / uCoordinate.dotProduct(pM);

                        double uA = uCoordinate.dotProduct(pA) * mU; // u coordinate of the first vertex
                        double uB = uCoordinate.dotProduct(pB) * mU; // u coordinate of the second vertex
                        double uC = uCoordinate.dotProduct(pC) * mU; // u coordinate of the third vertex

                        Point3D vCoordinate = pM.crossProduct(pMxPn);
                        double mV = 1.0 / vCoordinate.dotProduct(pN);
                        double vA = vCoordinate.dotProduct(pA) * mV; // v coordinate of the first vertex
                        double vB = vCoordinate.dotProduct(pB) * mV; // v coordinate of the second vertex
                        double vC = vCoordinate.dotProduct(pC) * mV; // v coordinate of the third vertex

```

I am looking for an explanation on how this PMN -\> UV conversion method works.

I am also interested in how the algorithm using PMN works as i still don't intuitively understand how these texture coordinates are computed from the basis vectors, so an explanation of that would also help me a lot but is not necessary as i mostly want to understand how the PMN -\> UV conversion method works

A very specific question that i have about the PMN texture mapping algorithm, is what do the a, b, c values define for each pixel? Every article i've found that describes this algorithm has simply referred to them as "magic coordinates" similarly A, B, C is simply referred to as "magic vectors" which isn't very helpful for anyone actually wanting to understand each part of the algorithm instead of just implementing it.

# Answer
> 1 votes
Points PMN define a plane, and a parallelogram in that plane. You can imagine taking your texture and rotating/stretching/skewing it to fit that parallelogram. For a tiling texture, you can then repeat that parallelogram of texture to completely cover the plane.

For any other point A, B, or C, or any arbitrary point X in between them, we can project it onto that PMN plane. Imagine a light shining along the direction normal to plane PMN, from whatever side our point X is on, falling perpendicularly onto plane PMN. Wherever the shadow of X lands on the plane, which we tiled with our distorted texture, that's the spot it takes its texture coordinate (and corresponding texel colour) from.

---
Tags: projection, linear-algebra, uv-mapping
---


# Question
Title: How do you use configuration files to describe the contents of an entity in an ECS-system?
One of the advantages that's often brought up when talking about ECS-systems is that they allow a higher degree of flexibility in regards to Data vs Code. Without the limitation of hard-coded types, you can mix-and-match from your component types to create different compositions of components at runtime, for example using configuration files.

This all sounds great, but I'm not sure I fully understand what this looks like in practice, code-wise. Should the configuration files for entity types (be able to) just list all the component types an entity contains? In that case, how do we match the identifiers in the configuration files to the correct component types? Would it look something like this?

```
{
    "name" : "goblin-grunt",
    "composition" : [
        "render-comp",
        "physics-comp",
        "hostile-mob-comp"
    ]

}

```

And then something like this (pseudo-code):

```
switch(composition)
{
case PhysicsComp::id:
    ...
    break;
case RenderComp::id:
    ...
    break;
...
}

```

This to me looks a bit messy to maintain, since you would have to update that switch-statement for every new component type, as well as having to add a `static constexpr` `id` field for every type.

But maybe this is generally how it's done?

# Answer
> Should the configuration files for entity types (be able to) just list all the component types an entity contains?

No. As it's been pointed out in the comments, *"You'd presumably want to store more than just the type of each component, but also the values of its relevant parameters/properties/fields."*

So, for example, your JSON file could look like this:

```
{
    "name" : "goblin-grunt",
    "composition" : [
        "render-comp" :
          [ "model" : "goblin-grunt.obj",
            "base-scale" : 1.2 ],
        "physics-comp" :
          [ "model" : "goblin-grunt.phy",
            "base-scale" : 1.2 ],
        "hostile-mob-comp" :
          [ "behaviour": "aggressive",
            "walk-speed": 1,
            "run-speed": 1.7,
            "max-pursue-distance": 50 ]
    ]
}

```

Now the "fun" part comes in how you compose your entity with those components *in the code*.

> This to me looks a bit messy to maintain, since you would have to update that switch-statement for every new component type, as well as having to add a static constexpr id field for every type.

Yes, and there are other ways.

And those ways will depend on how you write your data, and where you need it once it's loaded. Using reflection in c++ can be a challenge, and I suppose you'll need to spend a lot of time to implement one that works for you/your project/your team if you want to go that way.

Alternatively, you can use a parser function/object that you'll write yourself for each component type.

But you don't have to use a `switch` the way you've shown us.

I would suggest you explore the following pattern (I'm sure it has a name but I don't know what it is so I can't web-search for it and refer to it). Roughly, you have a singleton (unique object/globally accessible) class, let's call it `ComponentParsersRegistry` which will act as a hub for all the component parsers your infrastructure has.

Then you'll have classes that will instantiate themselves at program start up (those are created in the .cpp files, they're in the global scope). Upon construction, those classes will make the `ComponentParsersRegistry` aware that they exist and associate a "string" (e.g. "render-comp") to a parser function for that component, which will take a JSON object as input and return an optionally populated component.

The code goes roughly like this:

In `ComponentParsersRegistry.h`:

```
class ComponentParsersRegistry : private boost::noncopyable
{
public:

  static ComponentParsersRegistry& GetInstance() {
    if ( not TheInstance )
      TheInstance = new ComponentParsersRegistry();
    return *TheInstance;
  }

  std::map<std::string, std::function<std::unique_ptr<Component>(const JSON::Object&)> mParsers;

private:

  ComponentParsersRegistry() = default;

  static ComponentParsersRegistry* TheInstance; // Make sure you initialize this to nullptr in the cpp.

}

```

In `ComponentRender.h`:

```
struct ComponentRender : public Component
{
  /// Configuration
  /// @{
  std::filesystem::path mModelPath;
  double mBaseScale { 1.0 };
  /// @}

  /// Run-time stuff
  /// @{
  myNs::Matrix mTransformMatrix;
  myNs::ModelNode mLoadedModelNode;
  /// @}
}

```

In `ParserComponentRender.h`:

```
#include "ComponentParsersRegistry.h"
#include "ComponentRender.h"

struct ParserComponentRender
{
  ParserComponentRender() {
    ComponentParsersRegistry::GetInstance().mParsers["render-comp"] = std::bind( ParserComponentRender::parse, this, std::placeholders::_1);
  }

  std::unique_ptr<Component> parse( const JSON::Object& aJSONObject )
  {
    auto componentRender = std::make_unique<ComponentRender>();

    // try and parse the JSON into the struct.

    if ([there are no parsing issue])
      return std::move( componentRender );

    // issues with the parsing.
    return nullptr;
  }
}

```

In `ParserComponentRender.cpp`:

```
// instantiate the object
ParserComponentRender parserComponentRender(); // This will invoke the ctor and register the parser into the hub.

```

In `EntityParser.cpp`:

```
#include "ComponentParsersRegistry.h"

void EntityParser::parseEntityFromJSON( Entity& aEntity, const JSON::Object& aEntityJSONObject )
{
  for ( const auto& [key, value] : aEntityJSONObject )
  {
    if ( auto it = ComponentParsersRegistry::GetInstance().mParsers.find(key);
         it != ComponentParsersRegistry::GetInstance().mParsers.end() )
    {
      std::unique_ptr<Component> component = it.second(value);
      if (component)
      {
        aEntity.mComponents.emplace_back(std::move( component ) );
      }
    }
  }
}

```

This design will let you add new parsers locally without the need to interfere with other parts of the parsing. Now please keep in mind that I don't know how you've designed your structure yet, and a single part of the code can't be taken independently from the rest of the code. Here I assume that you store your Components in your Entity, but that might not be the case in your own implementation, and so you'll need to change how you're doing this.
> 1 votes

---
Tags: c++, software-engineering, serialization, entity-component-system
---


# Question
Title: Is a platform an entity in 2D Platform in ECS pattern?
I've been coding a small 2D platformer applying ECS pattern. However, I'm struggling with a issue. When building each platform from tilemap and such platforms need to be collided by other entities, are they considered as entity itself so that the respective system can handle such entities? For example: a platform must have a different behavior from other platforms even if it's in a fixed position like collisions, wet floor, etc.

My main concern is about performance and memory since the game is for very low-end devices (64MB in RAM, 333 MHz CPUs *maximum*), so due to the map being made with platforms (entity for each) using a collision system (verify if the player collides with map objs, etc) it could slow down the performance, couldn't it?

# Answer
> Is a platform an entity in 2D Platform in ECS pattern?

Yes, it is. *

Keep in mind that although you design your objects with tiles, only the graphical part needs to have "one sprite per tile". For example, although a platform is composed of four tiles, you do not have to have four physics "blocs" for this platform, you can extend a single physics box to four graphics boxes, this will 1) make your physics handling much easier, 2) reduce the amount of checks done, and 3) reduce the size taken by the physics objects.

Additionally, being a platformer, remember that the player will only see your character and what's around it; they don't care about what's not being shown on their screen, and so should you: when you check your character against other physics entities, you can completely and safely ignore what's not displayed, so this will speed up your physics loop.

---

* There is no ECS police so you can eventually decide whatever you want.
> 1 votes

---
Tags: 2d, entity-component-system, platform
---


# Question
Title: How could I make the array size readonly in inspector in Unity with a custom attribute?
How could I make the array size readonly in inspector in Unity with a custom attribute?

Here is my `ReadOnly` attribute:

```
using game_editor.drawers;
using UnityEditor;
using UnityEngine;

namespace editor.drawers
{
    [CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
    public class ReadOnlyDrawer : PropertyDrawer
    {
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            return EditorGUI.GetPropertyHeight(property, label, true);
        }

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            GUI.enabled = false;
            EditorGUI.PropertyField(position, property, label, true);
            GUI.enabled = true;
        }
    }
}

```

```

    using UnityEngine;

    namespace game_editor.drawers
    {
        public class ReadOnlyAttribute : PropertyAttribute
        {

        }
    }

```

Here is how I use it:

```
public class MainObject : MonoBehaviour
{
    [ReadOnly]
    [SerializeField]
    GameObject[] prefabs;
}

```

The problem right now is that I still can edit my array size (the `MainObject.prefabs` array in this case) in editor. How could I modify my `ReadOnlyDrawer` to prevent that?

I do not know the array length beforehand. So, the `OnValidate` solution like this one:

```
private const int SIZE = 5;
 public int[] ints = new int[SIZE];

 void OnValidate()
 {
     if (ints.Length != SIZE)
     {
         Debug.LogWarning("Don't change the 'ints' field's array size!");
         Array.Resize(ref ints, SIZE);
     }
 }

```

(source) won't work in my case.

Also, I want to use this attribute thorughout my project in different places. So, I do not want to create a custom inspector, I just want to utilize the drawing attribute.

# Answer
I had to figure out how to do this. I am building a custom inspector with UI Toolkit, and this is the code in that context:

```
[CustomEditor(typeof(MyComponent))]
public class MyComponentInspector : Editor {
    public override VisualElement CreateInspectorGUI() {
        var inspector = new VisualElement();

        var myArray = new PropertyField(
            this.serializedObject.FindProperty("myArray")
        );

        inspector.Add(myArray);

        // Wait for property field to be populated before modifying it.
        // Source: https://forum.unity.com/threads/solved-how-to-force-update-visual-element-on-the-current-frame.727040/#post-4984787
        _ = myArray.schedule.Execute(() => {
            // Get size field of array
            IntegerField sizeField = myArray.Q<IntegerField>();

            // Disallow changing array size in inspector
            sizeField.SetEnabled(false);
        });

        return inspector;
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Creating a room with custom options that persist to other players
I am using Photon for networking in my project. I am creating a room with PhotonNetwork.CreateRoom(). I pass in the room name as well as a set of room options where the room options just specify the number of players as well as a set of CustomRoomProperties. These CustomRoomProperties do not show up for other players when they try to join the room. The CustomRoomProperties hashtable is completely empty even though the room options sent in with the room creation are populated with them. Shouldn't the CustomRoomProperties persist when the room is created so that the values can be used for when others try to join the room? I essentially want to be able to make sure the room that the person is attempting to join has a matching custom room property value.

Below is an example of how I create room options and assign them to the room I create:

```
var options = new RoomOptions() { MaxPlayers = gameController.MaxPlayers };
options.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable();
options.CustomRoomProperties.Add("myTestKey", "myTestValue");
PhotonNetwork.CreateRoom("roomName", roomOptions:options);

```

# Answer
It turns out that the roomOptions.customRoomPropertiesForLobby property needs to contain the key for the custom property in order for it to be viewed from the lobby. So I just needed to add the line below when creating the RoomOptions and it allowed me to view that property from the other clients' perspective:

```
options.customRoomPropertiesForLobby = new string[1] { "myTestKey" };

```

So my code is as follows in the end:

```
var options = new RoomOptions() { MaxPlayers = gameController.MaxPlayers };
options.customRoomPropertiesForLobby = new string[1] { "myTestKey" };
options.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable();
options.CustomRoomProperties.Add("myTestKey", "myTestValue");
PhotonNetwork.CreateRoom("roomName", roomOptions:options);

```
> 0 votes

---
Tags: unity, photon
---


# Question
Title: Why does my model disappear as I get closer?
As I get closer, the model I made disappears. how can i fix this situation?

# Answer
I solved the problem. **Scene Camera** \> "Uncheck **Dynamic Clipping**".
> 1 votes

---
Tags: unity
---


title: Composing Neo Geo music

text:
# Question
Title: Composing Neo Geo music
I was listening to some of Neo Geo game music on Youtube the other day and it made me think about creating new music in this style.

If I wanted to make a retro-style game today, how would I compose/sequence new music to make it sound like a Neo Geo game?

# Answer
> 2 votes
Whenever I create music for a gaming project I always first use a MIDI program to compose (I use Guitar Pro, but there are a vast many you can use, most of which are free). Depending on the style of music I want, sometimes MIDI alone is good enough for me. Most of the instruments are cheesy and digital enough to fit my needs. But if you want to get a real 8 bit sound, I run my midi tracks through this program: GXSCC (I apologize for a geocities link, but that's actually where it is still hosted).

# Answer
> 1 votes
The Neo Geo's distinct sound is due to its sound chip, the Yamaha YM2610 a.k.a. OPNB, which is part of Yamaha's OPN family of sound chips. In terms of "instruments", it has the following:

Each has a distinct sound:

**FM synthesis**: this type of instrument produces sounds by generating sine waves and applying various operations on them, such as filters and envelopes. You may be familiar with platforms like the SEGA Megadrive / Genesis, or the NEC PC-98 (home of Japanese games like Touhou). These also used OPN sound chips, and have the same distinct sound coming from FM synthesis instruments. Although FM synthesis is capable of creating a wide variety of sounds, it is difficult to achieve a specific sound with them, such as emulating real instruments, so they can give off an "electronic" or "tinny" sound.

**SSG square wave**: the square wave is what most people associate with chiptune music and 8-bit consoles like the NES. The OPN SSG is rather limited in comparison however, because it only generates square waves, whereas other types of waves are possible in typical PSGs like the sawtooth or triangle waves.

**SSG noise**: also found on many PSGs, this is typically used for simple percussion.

**PCM**: this is a more typical instrument, which plays an audio sample. The fact that there is only one PCM channel that allows variable pitch means that the PCM channels are mostly used for drums (fixed pitch) and the occasional, monophonic instrument using realistic samples, such as voices, wind/brass instruments or a lead melody.

In essense, the OPNB's sound is mostly FM synth instruments, supplemented by PCM drum samples and the occasional PCM instrument or SSG noise instrument.

To replicate this distinct sound, you have to learn about FM synth instruments. Making them from scratch can be an art unto itself, but you can somewhat get around it by taking instruments from existing tracks. From here you can go one of two routes:

**Emulate the OPNB sound chip**

There are some music trackers that emulate the OPNB, including its limitations such as limited number of channels. Example: DefleMask. You will be able to authentically recreate the sound, but the learning curve can be high, because music trackers work quite differently to typical DAWs.

**Use plugins that recreate OPNB instruments in your favorite DAW**

Example: ADLplug. Depending on your experience, DAWs tend to be easier to use and more flexible. Without the hard limitations of the OPNB chip, your music can sound less authentic, but you'll have the flexibility in using more channels, for instance.

---
Tags: music, arcade
---