# Question
Title: How can I use the flags logic to turn on/off the lights and rotations?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeColors : MonoBehaviour
{
    public List<Transform> objectsToRotate = new List<Transform>();
    public bool turnOnRotationLights = false;
    public float rotationSpeed;
    public Light[] lights;
    public Material material;
    public Vector3 targetAngle = new Vector3(-90f, 0f, 0f);

    private bool rotationLightsOn = true;

    // 0,31,191
    // 255,0,0

    // Start is called before the first frame update
    void Start()
    {
        if (turnOnRotationLights)
            StartCoroutine(SetTrue());
    }

    // Update is called once per frame
    void Update()
    {
        if(turnOnRotationLights == true && rotationLightsOn == true)
        {
            StartCoroutine(SetTrue());

            rotationLightsOn = false;
        }
        else
        {
            rotationLightsOn = true;
        }

        if (rotationSpeed == 0)
        {
            for (int i = 0; i < objectsToRotate.Count; i++)
            {
                Transform t = objectsToRotate[i].transform;
                float newAngle = Mathf.LerpAngle(t.localEulerAngles.x, targetAngle.x, Time.deltaTime);
                t.localEulerAngles = new Vector3(newAngle, 0, 0);
            }
        }

        if (turnOnRotationLights)
        {
            for (int i = 0; i < objectsToRotate.Count; i++)
            {
                objectsToRotate[i].Rotate(new Vector3(Time.deltaTime * rotationSpeed, 0, 0));
            }
        }
    }

    public void setHighlight(bool highlight)
    {
        if (highlight)
        {
            material.EnableKeyword("_EMISSION");
            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            material.SetColor("_EmissionColor", new Color(0, 31, 191));
        }
        else
        {
            material.EnableKeyword("_EMISSION");
            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            material.SetColor("_EmissionColor", new Color(255,0,0));
        }
    }

    IEnumerator SetTrue()
    {
        setHighlight(true);

        yield return new WaitForSeconds(0.5f);

        StartCoroutine(SetFalse());
    }

    IEnumerator SetFalse()
    {
        setHighlight(false);

        yield return new WaitForSeconds(0.5f);

        StartCoroutine(SetTrue());
    }
}

```

It was working fine without the two flags turnOnRotationLights and rotationLightsOn this is how the code looks like before adding and using this two flags :

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

public class ChangeColors : MonoBehaviour
{
    public List<Transform> objectsToRotate = new List<Transform>();
    public float rotationSpeed;
    public Light[] lights;
    public Material material;
    public Vector3 targetAngle = new Vector3(-90f, 0f, 0f);

    // 0,31,191
    // 255,0,0

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(SetTrue());
    }

    // Update is called once per frame
    void Update()
    {
        if (rotationSpeed == 0)
        {
            for (int i = 0; i < objectsToRotate.Count; i++)
            {
                Transform t = objectsToRotate[i].transform;
                float newAngle = Mathf.LerpAngle(t.localEulerAngles.x, targetAngle.x, Time.deltaTime);
                t.localEulerAngles = new Vector3(newAngle, 0, 0);
            }
        }

        for(int i = 0; i < objectsToRotate.Count; i++)
        {
            objectsToRotate[i].Rotate(new Vector3(Time.deltaTime * rotationSpeed, 0, 0));
        }
    }

    public void setHighlight(bool highlight)
    {
        if (highlight)
        {
            material.EnableKeyword("_EMISSION");
            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            material.SetColor("_EmissionColor", new Color(0, 31, 191));
        }
        else
        {
            material.EnableKeyword("_EMISSION");
            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            material.SetColor("_EmissionColor", new Color(255,0,0));
        }
    }

    IEnumerator SetTrue()
    {
        setHighlight(true);

        yield return new WaitForSeconds(0.5f);

        StartCoroutine(SetFalse());
    }

    IEnumerator SetFalse()
    {
        setHighlight(false);

        yield return new WaitForSeconds(0.5f);

        StartCoroutine(SetTrue());
    }
}

```

but there are two problems :

* When running the game the lights and rotation start at the beginning.
* I can't control the lights and rotation on/of while the game is running in runtime.

I want :

* When the game start also start the lights and rotation if the public flag is true.
* While the game is running in runtime to be able to turn off/on both lights and rotation.

The way I used it with the flags it's not working good. When I turn it off at runtime only some orations stop and the lights keep on and it's all messed.

# Answer
When you have something which is animated and which does different animations depending on its state, then that sounds like something you might want to consider doing with the animation system instead of coding yourself. It allows you to design complex animations using visual tools instead of writing code, and then allows you to switch between those animations with just a single C# method call.

1. Add an animator to the light-prefab
2. Create an animation controller for that animator
3. Create two states for it: off and on.
4. Create a bool-parameter. Let's call it "on".
5. Create transitions between those two animations which are triggered by the state of that bool-parameter.
6. Make the on-animation looping.
7. Design the on-animation as described in the manual. That would be mostly the rotation looping from 0° to 360° over the course of 0.5 seconds and the light source being on on both points of that rotation curve while it's off on the off-animation.
8. Now all programming you need to do is `GetComponent<Animator>().SetBool("on", true)` to switch the light on and `GetComponent<Animator>().SetBool("on", false)` to switch it off again.
> 1 votes

# Answer
I would switch the two Coroutine for one InvokeRepeating. You can supply how often it should be invoked and it will continue until you stop it. Now your lights won't toggle on Start anymore if your lightSwitch is off. If you want to start it at a later time, you can call StartLights and Stop it anytime with StopLights. Since your rotation is handled in Update, all we need to do is have a bool for that around your whole logic and switch to trigger if you want to stop or start it.

```
public bool lightSwitch;
public bool doRotation;

void Start(){
  if (lightSwitch)
    StartLights();
}

void Update(){
  if (doRotation){
    // whole rotation code
  }
}

void ToggleLight() {
  lightSwitch = !lightSwitch;
  LightLogic();
}

void ToggleRotation() {
  doRotation = !doRotation;
}

public void StopLights() {
   CancelInvoke();
}

public void StartLights() {
   InvokeRepeating("ToggleLight", 0f, 0.5f);
}

public void LightLogic() {
  material.EnableKeyword("_EMISSION");
  material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
  if (lightSwitch) {
    material.SetColor("_EmissionColor", new Color(0, 31, 191));
  } else {
    material.SetColor("_EmissionColor", new Color(255,0,0));
  }
}

```
> 0 votes

# Answer
This is working

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

public class ChangeColors : MonoBehaviour
{
    public List<Transform> objectsToRotate = new List<Transform>();
    public float rotationSpeed;
    public Material material;
    public Vector3 targetAngle = new Vector3(-90f, 0f, 0f);
    public bool go = false;

    private bool lightsOn = true;

    // 0,31,191
    // 255,0,0

    // Start is called before the first frame update
    void Start()
    {
        if (go)
            StartCoroutine(SetTrue());
    }

    // Update is called once per frame
    void Update()
    {
        if (rotationSpeed == 0)
        {
            for (int i = 0; i < objectsToRotate.Count; i++)
            {
                Transform t = objectsToRotate[i].transform;
                float newAngle = Mathf.LerpAngle(t.localEulerAngles.x, targetAngle.x, Time.deltaTime);
                t.localEulerAngles = new Vector3(newAngle, 0, 0);
            }
        }

        if (go)
        {
            for (int i = 0; i < objectsToRotate.Count; i++)
            {
                objectsToRotate[i].Rotate(new Vector3(Time.deltaTime * rotationSpeed, 0, 0));
            }
        }

        if (go && lightsOn)
        {
            StartCoroutine(SetTrue());

            lightsOn = false;
        }

        if(go == false)
        {
            lightsOn = true;
        }
    }

    public void setHighlight(bool highlight)
    {
        if (highlight)
        {
            material.EnableKeyword("_EMISSION");
            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            material.SetColor("_EmissionColor", new Color(0, 31, 191));
        }
        else
        {
            material.EnableKeyword("_EMISSION");
            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            material.SetColor("_EmissionColor", new Color(255,0,0));
        }
    }

    IEnumerator SetTrue()
    {
        setHighlight(true);

        yield return new WaitForSeconds(0.5f);

        if (go)
            StartCoroutine(SetFalse());
    }

    IEnumerator SetFalse()
    {
        setHighlight(false);

        yield return new WaitForSeconds(0.5f);

        if (go)
            StartCoroutine(SetTrue());
    }
}

```
> 0 votes

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


# Question
Title: How do I set horizonal Field of View by code as in Inspector?
I have a camera that I have set to

```
RenderType = Base
Projection = Perspective
FOV Axis = Horizontal
Field of View = 75
Physical Camera = False
Clipping Planes Near = 0.3, Far  = 1000

```

If I set Field of View values during gameplay in the Inspector, it works as expected.

For example, I type 75, and the camera behaves as I think it should. I'm comparing with Resident Evil 4. It has a camera cheat, and if I select FOV 75 in this cheat, the Resident Evil 4 camera behaves like my Unity game camera.

However, when I set the camera.fieldOfView to a 75 by code, the Inspector shows 104, and the code does not look as it looks when I type 75 in the Inspector.

\_camera.fieldOfView however returns 75.

What is going on here, and how do I fix it?

Thank you!

# Answer
> 0 votes
Perhaps I got a solution. Not sure yet but it looks ok so far:

```
private void pSetFOV(float f)
{
    f = 2 * Mathf.Atan(Mathf.Tan(f * Mathf.Deg2Rad * 0.5f) / _camera.aspect) * Mathf.Rad2Deg;
    _camera.fieldOfView = f;
}

```

---
Tags: unity, camera
---


# Question
Title: Bitmap BMP Reading Question: I need to read (large) 8MB 32BPP BMP Files into Memory so they may be queued for game play
```
class Surface
{
protected:
    Surface();
    virtual ~Surface();

    class IMAGE // create a discreet type to be used to instantiate queue template
    {
    public:
        // single bitmap image width and height
        unsigned short width, height;
        unsigned int size;      // single bitmap image size
        DWORD* buffer;          // buffer to hold a width X height _size_ image
…

class Bitmap : protected Surface
{
public:
    class BMP_32
    {
    public:
        BMPHeader       HeaderSection;
        BMPInfo         InfoSection;
        BMPColorTable       ColorTableSection;

…

void Bitmap::BMP_32::Read(Bitmap::BMP_32& a_bmp32, IMAGE& an_image, SURFACE& a_surface, const char* file_name)
{
…
fread(&a_bmp32.HeaderSection.FileType, sizeof(a_bmp32.HeaderSection.FileType), 1, fp);
…
fread(&a_bmp32.InfoSection.HeaderSize, sizeof(a_bmp32.InfoSection.HeaderSize), 1, fp);
…
fread(&a_bmp32.ColorTableSection.RedIntensity, sizeof(a_bmp32.ColorTableSection.RedIntensity), 1, fp);
…

an_image.buffer = new DWORD[IMAGEBUFFERSIZE];

…
// The following three examples render the same output visually:

// DWORD dwords_read = fread(an_image.buffer, sizeof(DWORD), an_image.size, fp);  // dwords_read = 2,073,600

DWORD dwords_read = fread(an_image.buffer, (SCREEN_WIDTH * SCREEN_HEIGHT), 4, fp);   // dwords_read = 4
// DWORD dwords_read = fread(an_image.buffer, ((SCREEN_WIDTH * SCREEN_HEIGHT) * 2), 2, fp);  // dwords_read = 2

```

Background Detail: I am building up a class framework to read in 32BPP BMP files, that I am creating on a backsurface, which I then bltfast to the frontsurface and flip to GDI. The 32BPP background BMP that I am reading in is 8294400 in size, but the most I am able to read using “fread()” is 2073600, which is exactly 25% of the original artwork. I am using Visual Studio 2019 Community Edition and fread(&MyBuffer, arg2, arg3, stream) extensively. My application is an MFC application.

I have a need to read in the entire BMP Pixel Data Section into memory, because I am saving this into a queue Abstract Data type. Once I have the BMP in memory the I/O is done to disk and I just make calls to update the backsurface, bltfast and flip to update my scene. I am creating a class library for the BMP code.

Question: Is fread() hitting an upperbound on size limit? If so can someone suggest how I might be able to overcome this problem. If so I am hoping to make a minor substitution for this fread() API call for another C++ call. I cannot do anything too fancy with multiple buffers or doing a lot of I/O, as I have tried that approach already without success.

# Answer
> 0 votes
I found the following to work well. from working code that I wrote some time back, which I now converted to utilize 32BPP BMP files and x64.

For the 32BPP header file I used the following link:
https://solarianprogrammer.com/2018/11/19/cpp-reading-writing-bmp-images/

In case your wondering I am using DirectX 7.0

```
class Bitmap
{
public:

    class BMP32
    {
    public:

        BMPHeader       HeaderSection;
        BMPInfo         InfoSection;
        BMPColorTable   ColorTableSection;
        BYTE* buffer;           // buffer to hold a BMP raw pixel data

        BMP32() {
            memset(&HeaderSection, 0, sizeof(HeaderSection));
            memset(&InfoSection, 0, sizeof(InfoSection));
            memset(&ColorTableSection, 0, sizeof(ColorTableSection));
            buffer = NULL;
        }

        virtual ~BMP32() { if (buffer != NULL && InfoSection.ImageSize != 0) delete buffer; }
        void Read(BMP32& a_bmp32, const char* file_name); // read that will read 32BPP
    };
...

class Surface...

class IMAGE     // create a discreet type to be used to instantiate a queue of surfaces
    {
    public:
        int width, height;      // single bitmap image width and height
        unsigned int size;      // single bitmap image size
        DWORD* buffer;          // buffer to hold a width X height _size_ image
        IMAGE() { buffer = NULL; width = 0; height = 0; size = 0; }
        virtual ~IMAGE() { if (buffer != NULL && size != 0) delete buffer; }    // don't leak memory!
    };

...

void ReadGFX(const char* file_name, PALETTEENTRY scene_palette[MAX_COLORS_PALETTE]); // read in all 32 bit bmp images from the gfx (aka the sprite library) file name passed to this method

// What we want to do here is to read a file containing one or more
// bmp files. each bmp read will be written into a ddraw surface.
// The bmp file consists of a header ( width  height and size ) and data ( size bytes )
void Sprite::ReadGFX(const char* file_name, PALETTEENTRY scene_palette[MAX_COLORS_PALETTE])
{

    TRACE("Sprite::ReadGFX invoked. GFX name is : %s\n", file_name );

    FILE* fp;                           // file pointer to opened file_name
    if ( ( fp = fopen(file_name,"rb") ) != NULL )
    {

        short image_count = 0, i = 0;               // number of sprite images contained in file_name
        int w = 0, h = 0;
        unsigned int size = 0;
        DWORD buffer_size = 0;

        fread(&image_count, sizeof(image_count), 1, fp);    // get number of bmp files to read

        for ( i = 1; i <= image_count; i++ )
        {
            IMAGE an_image;     // create enough local storage to read in one image
            SURFACE a_surface;

        w = fread(&an_image.width,  sizeof(an_image.width), 1, fp);         // bmp width
        h = fread(&an_image.height, sizeof(an_image.height), 1, fp);        // bmp height
        size =  fread(&an_image.size,   sizeof(an_image.size), 1, fp);      // bmp size

        TRACE("Sprite::Read an_image.width = %d, an_image.height = %d, an_image.size = %d\n", w, h, size);
            an_image.buffer = new DWORD[an_image.size]; // create enough storage to hold bmp data
            buffer_size = fread(an_image.buffer, sizeof(BYTE), an_image.size, fp);  // read the raw pixel data from the bmp here
            try
            {
                Create(an_image.width, an_image.height, a_surface); // create ddraw surface
                Write(an_image, a_surface, Scene::scene_palette);               // copy image into surface
                surface_queue.Enqueue(a_surface);   // save data structure by queueing record object
                TRACE("Width = %i, Height = %i, Size = %i, Buffer Size = %u\n", w, h, size, buffer_size);
            }
            catch (int exception)
            {
                TRACE("%Xh exception caught by Sprite::ReadGFX\n ", exception);
                if (exception == VIDEO_EXCEPTION)
                {
                    TRACE("VIDEO_EXCEPTION caught by Sprite::ReadGFX, due to Surface::Create failure\n");
                    TRACE("Terminating: throwing SPRITE_EXCEPTION\n");

                    // clean up to avoid memory leaks!!
                    if (!surface_queue.IsEmpty())
                    {
                        surface_queue.MakeEmpty();
                    }
                    if (  an_image.buffer != NULL && an_image.size != 0   )
                    {
                        delete an_image.buffer;
                        an_image.buffer = 0;
                        an_image.buffer = NULL;
                    }
                    fclose(fp); // close the input file
                    throw (SPRITE_EXCEPTION); // terminate the program
                }
            }
        }
        fclose(fp);
    }
    else
    {
        TRACE ("Sprite::ReadGFX %s not found\n", file_name);
        char message[60];
        strcpy ( message, "Graphics file not found: ");
        strcat ( message, file_name);
        strcat ( message, "\nApplication will now terminate.");
        FatalMessageBox( message );
        throw (SPRITE_EXCEPTION);
    }
}

```

---
Tags: c++, 2d, graphics, game-loop
---


# Question
Title: why each game does not provide the option to download only one graphic quality, instead of having to download low, medium, high and ultra graphics?
If there is an option like this it will definitely save storage space.

When you download or stream a film there is an option for graphic quality, and we only download that one graphic quality.

Or is there another reason behind it all?

# Answer
This is because texture size is not really a barring factor for performance. When you say download in the graphics option context, the only thing you would exclude from download is larger size textures, shadow maps, and that’s generally about it. Even high poly models take very little in the way of memory when they are on the disk.

Memory and performance are often confused as one in the same, but in reality larger textures incur very little in the way of performance. In general, the largest performance gains when selecting lower graphics options come from the algorithms used (or rather, *not used*). For example, antialiasing can be very expensive depending on the algorithm selection. Even better examples of new tech are things like super-sampling, real-time ray tracing and reflections. They will literally make your computer hot because they are so taxing on your hardware. Meanwhile, the downloaded bits are only a drop in the bucket.

As far as why they don’t allow you to download them separately, that is a matter of design decision. World Of Warcraft has historically allowed you to play the game even as it downloads because they download the smallest things first. Other games choose not to, typically because when someone changes the graphics settings, they would despise having to wait another half hour to play their AAA game. That, or the fact that games are now designed with multiple platforms in mind make the task both expensive to coordinate and lacking in a decent gain.
> 2 votes

---
Tags: performance, assets, distribution
---


# Question
Title: How to generate fixed amount of health points in every interval when the data is in database?
Most of the common example of that in the game is stamina regeneration to control the activity of the players. For example, genshin impact, they have something called resin system, and it regenerates 1 resin in every 8 minutes until the amount maxed out. What is the algorithm for that? In my case it's hp.

My situation: The players' data is saved in the database. I am creating a text-based rpg game using discord bot, and the programming language I am using is python.

Here is what I had thought:

* when freeing the data from the memory, save the date and time of when the hp became less than max amount to the database.
* when the data is in the memory, while hp is not full add fixed amount of hp in every interval.
* when querying the data from database, update the hp, calculate from the saved date and time, interval, and fixed amount of hp.

Thanks in advance.

# Answer
> 0 votes
Usually, databases are used for data at rest. The data about players who are currently offline. It gets saved when the player logs out. When a player comes online again, their data is taken out of the database and loaded into memory, so it can be accessed much faster.

So how do you handle changes which happen to the data at rest while the players are offline?

There are two common options.

## A: Cronjobs

Have a background process which runs at regular intervals and updates the whole database. This is usually pretty easy to do. You just figure out how to run a query like `UPDATE characters SET hp = hp + 1 WHERE hp < hp_max` every minute and all the data will always be up-to-date. This is useful when you have features like browsing offline characters with their current HP.

But unfortunately, online games tend to accumulate a huge amount of dead accounts over time. So after a couple years, you might spend more processing power on updating dead accounts than you spend on those which are actually playing. The nightmare scenario is that the above query will take longer than a minute to execute, causing your cronjob to pile update jobs on your database faster than it can process them and eventually causing it to stop responding to queries altogether.

But for a discord bot for a smaller community, this might not become an issue that quickly.

## B: Update on access

This is a far more elegant method I usually recommend, but it takes some more thought and diligence to implement and use it correctly.

When you persist a character to the database, store it with the timestamp of the last update. When you load a character from the database (for whatever reason), check that timestamp, check the difference between the current time, and then simulate the HP recovery algorithm. For example, when your characters recover 1 hp every 60 seconds and this character was last saved 100,000 seconds ago (a bit over a day), you give it (100,000 / 60 =) 1666 HP when they log back in.

Keep in mind that when your game has interactions with characters who are offline (or even just viewing their current HP is possible) then it is important that you update a character whenever you access it, regardless of the reason. When someone attacks an offline character, you need to update them. When someone views the HP of an offline character, you need to update them. When you want to run an analytics query to get the current HP of all characters in the game (for some reason), you have to update every single character to get correct results.

---
Tags: algorithm
---


# Question
Title: Questions regarding using (CC BY-NC-ND 3.0) and (CC BY-NC 4.0) music for a completely free game (not Freemium)
I am in the process of developing a small video game for a game-jam on itch.io.

The game-jam requires the developer to first make a github repository, upload all the source code and material (including music, sound effects and artwork) there and provide a link to your game-jam entry on itch.io.

I want to use some music that I found on freemusicarchive.org.

Some of the tracks on the website have (CC BY) licence while majority of them are either CC BY-NC-ND 3.0 or 4.0 (meaning to say that majority of the music tracks are NOT allowed for commercial purposes).

So my question is this:

I do not intend to make any money from my entry and I will make my entry completely free to access it. There will be no freemium or pay-to-unlock-features kind of thing with my game. It will be 100% free. You can go to the URL of my game, which will be hosted on itch.io (zipped HTML) and then anyone can play it.

Can I use music that have non-commercial licences in them (e.g CC BY-NC-ND etc.) for my completely free to play game?

Thanks!

# Answer
First of all, I am not a lawyer. I can not provide you legal advise. This is just how I as a legal layman would interpret this license and what consequences I would make based on that interpretation.

---

When you have a question about the details of a creative common license which are not covered by the laypeople synopsis, then it can be useful to look at the actual license text.

It defines non-commercial as:

> NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.

So yes, using it in a freely available game which does not aim to make any money whatsoever does not seem to be an issue for the creator, at least according to this clause.

OK, but what about the no-derivatives part? Is a game which uses the music a derivative work? The license says:

> The Licensor hereby grants You \[the rights\] to produce and reproduce, but not Share, Adapted Material

Or in other words, you can "adapt" it for your own use, but then you can not give your "adaptation" to others.

OK, but how does it define "Adapted Material"?

> Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.

And here it gets tricky. "synched in timed relation with a moving image" appears to talk about using the song in a video. But it might just as well fulfill the definition of using it in a game.

So it appears to me that using a CC-ND license song in a game might not be possible without permission. So you might want to either seek the creators permission to use the song in your game or look for a different one.

---

By the way, my favorite site for finding background music for game jam games is filmmusic.io. Almost everything on there is CC-BY. Which basically means "do whatever you want, just give credit".
> 1 votes

---
Tags: assets, legal, copyright, music
---


# Question
Title: How to implement a Behavior Tree (preferably in Unity 3D)
I have a state machine I want to implement as a behavior tree. I now have an understanding of how they work but I can't seem to find a full implementation of one. I have implemented a simple one using a plug-in called Behavior Machine but the problem I have with it is I feel like it limits me just as it did when I used it for making my FSM until I implemented my own FSM that is when I had the privilege of using my own functions to trigger my own state transitions and optimize it so that it doesn't use a lot of resources.

The other problem I have is it is difficult to implement my own nodes and control which part executes (optimization). Any idea where I can find a good tutorial on how I can do this, preferably with Unity and in C# or Java. Or where I can find a good library with proper documentation because the one I found on Git-hub or other sites are buggy or just some classes with no documentation. Your help will be greatly appreciated.

So basically, what I want to do is implement my own Behavior Tree. This way I think I can have better control on how it executes so that it can run on mobile devices smoothly.

# Answer
There actually aren't a lot of full-blown behavior tree implementations available. There are a good amount of theoretical "behavior tree by example" or just "this is a behavior tree" documents out there. I'll put a few here, but won't really expand on them much because I'm assuming that you've read them and don't know where to start:

The last two will probably be more like what you are looking for. I kind of like the last one for basic design, but it doesn't address some of the inherent flaws in behavior trees, like real-time reaction and state management. The next to last one is a full-fledged implementation with a very good wiki on how to design them. If you have what you were looking for, you can stop reading here.

If I still have your attention, then you're probably going to set down the path of rolling your own behavior tree, and those references from before are excellent resources to learn everything you need to know to do just that. On an implementation level, it's pretty important to realize that behavior trees are just a specific realization of a component system, where the behaviors are the components that can be swapped around and ordered to represent the conditional logic that you want you AI to perform. As such, when you design a behavior tree from the ground up, you start by designing a treed component manager with a specific interface to a generic behavior.

What is a treed component manager? It's a term I just made up, but it fits. When you design a component-based system, you generally loop through component slots and execute each component sequentially. In this case, you want the execution of the components to be determined based on the outcome of previous components, which can be (and usually is) represented by a tree of logic that you traverse. The design of the tree itself is relegated to some configuration outside of the code.

Well, then what do I mean by a "specific interface to a generic behavior?" This, once again, goes back to the component idea. When you have components, you don't know exactly what they do (by design!). You need to expose an interface to the most generic behavior (usually done through pure abstraction) and then have your component manager call that completely generic function that basically just says, "Do your thing."

If you read the documents I linked before, you'll see that most often these behaviors have one of three functions. First, they could be a composite behavior that has one to many children and dictate the flow of the tree. They could be a decorator with one child that modifies the outcome of its child in some way before passing that result up the tree. And finally, it could be an action that actually does something -- either setting a state (by writing to a blackboard of some sort), or causing the entity to do something in the game. From these building blocks, you create arbitrarily complex conditional logic chains. In the end, that's all a behavior tree is -- a really complex (and modular) if-then-else series.
> 7 votes

# Answer
For those coming across this thread, I recommend a look at this implementation:

https://github.com/eelstork/BehaviorTrees/blob/master/cs/src/Status.cs

This is a short (\<100loc) implementation of stateless behavior trees. Sequences and selectors are implemented via overloading `&&` and `||`.

Then a BT would look something like this:

```
Status Patrol()
=> (playerInSight && Shoot(player))
|| (underFire && TakeCover())
|| Guard(doorWay);

```

This approach is more useful if you're going to code the BTs. For visual scripting how your BT transpiles to C# doesn't really matter (well, it does, and a stateless implementation is still attractive for performance; but the fastest C# conversion might eschew operator overloading and just use if-elses).
> 1 votes

---
Tags: ai
---


# Question
Title: Converting IntPtr to objects (here Raylib Material[])
I'm trying to apply a texture to the material of a Model but I could not figure out how to do it:

so I made a direct translation of the c code taken from examples:

(original from "Raylib \[shaders\] example - postprocessing shader" line 77)

```
model.materials[0].maps[MAP_DIFFUSE].texture = texture;

```

(my c# translation)

```
m_LP_SpookyTree = LP_SpookyTree.GetModel;
m_LP_SpookyTree.materials[0].maps[MaterialMapType.MAP_ALBEDO].texture = Raylib.LoadTexture("Ressource/Textures/PlaceHolders/mossy_rock_diff_1k.png");

```

According to the cs file on the repo, the "materials" definition is an Int pointer. The problem comes from the Intptr, how could I get the material array from it?

thanks for your time.

PS: I've created an issue on Raylib.cs GitHub repo so if I get an answer on one before the other, I'll update accordingly

---

EDIT 1:

I've tried to change every IntPtr to the object it should actually point to regarding the comments in the source file, compile the lib, and imported it. unfortunately, it broke. so I don't think it's possible.

---

EDIT 2:

I've found this article talking about IntPtr to objects (vice versa)

https://stackoverflow.com/questions/728105/how-to-convert-an-intptr-back-into-an-object

I've implemented it like so:

```
public static object pointerToObject(IntPtr pMapping, Type type)
{
    return Marshal.PtrToStructure(pMapping, type);
}

```

but now I get this error:

```
System.MissingMethodException : 'No parameterless constructor defined for type 'Raylib_cs.Material[]'.'

```

PS: The new code:

```
Material[] materials = (Material[])PointerManipulation.pointerToObject(m_LP_SpookyTree.materials,typeof(Material[]));
MaterialMap[] materialMaps = (MaterialMap[])PointerManipulation.pointerToObject(materials[0].maps, typeof(MaterialMap[]));

materialMaps[(int)Convert.GetTypeCode(MaterialMapType.MAP_ALBEDO)].texture = Raylib.LoadTexture("Ressource/Textures/PlaceHolders/mossy_rock_diff_1k.png");

```

# Answer
I've found a way to do it without strange coding.

I've found in this repo linked on the Raylib.cs readme.md file a translation of the c examples to c#.

Though, I had to do small modifications to the script.

Following are the original script and the modified version that worked for me:

original from https://github.com/ChrisDill/Raylib-cs-Examples/blob/eacde217a26971bb5e72f16d6f56ece6fd7646aa/Examples/models/models\_yaw\_pitch\_roll.cs

```

            // Model loading
            Model model = LoadModel("resources/plane.obj");      // Load OBJ model

            // Set map diffuse texture
            Material* materials = (Material*)model.materials.ToPointer();
            MaterialMap* maps = (MaterialMap*)materials[0].maps.ToPointer();
            maps[(int)MAP_ALBEDO].texture = LoadTexture("resources/plane_diffuse.png");

```

mine:

```
            m_LP_SpookyTree = LP_SpookyTree.GetModel;
            unsafe {
                Material* materials = (Material*)m_LP_SpookyTree.materials.ToPointer();
                MaterialMap* maps = (MaterialMap*)materials[0].maps.ToPointer();

                Texture2D d_LP_SpookyTree = Raylib.LoadTexture("Ressource/Models/LP_SpookyTree.Diffuse.png");
                maps[(int)MaterialMapType.MAP_ALBEDO].texture = d_LP_SpookyTree;

                Raylib.GenTextureMipmaps(ref maps[(int)MaterialMapType.MAP_ALBEDO].texture);
            }

```

I Had to add Raylib name before LoadTexture and GenTextureMipmaps because else it would not work since these are static methods from the RayLib cs binder.

So on a technical point, I think, from what I've seen in the code, that to translate an IntPtr we don't need to use strange methods that do not work. Instead, an explicit cast- as followed - suffice to make the pie. You might actually correct me since I'm not a really good programmer.

```
(Material*)m_LP_SpookyTree.materials.ToPointer();

```

In comparison here is the c code to get the material array:

```
m_LP_SpookyTree.materials;

```

In the cs binder, this returns an IntPtr which must be converted to its correct type.

also, I had to change MAP\_ALBEDO to MaterialMapType.MAP\_ALBEDO.

you can witness following is the working proof:

Hope it would help Cs users of Raylib
> 0 votes

---
Tags: c#, raylib
---


# Question
Title: Why the transform is not moving back to the originPos(Original Position)?
```
using UnityEngine;
using System.Collections;

public class Move : MonoBehaviour
{
    public Transform target;
    public float rotationSpeed;
    public float moveSpeed;

    private Vector3 originPos;
    private Quaternion originRot;

    private void Start()
    {
        originPos = transform.position;
        originRot = transform.rotation;
    }

    private void Update()
    {
        var distance = Vector3.Distance(transform.position, target.position);
        if(distance < 0.1f)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, originRot, Time.deltaTime * rotationSpeed);
            transform.position = Vector3.MoveTowards(transform.position, originPos, Time.deltaTime * moveSpeed);
        }

        transform.rotation = Quaternion.Lerp(transform.rotation, target.rotation, Time.deltaTime * rotationSpeed);
        transform.position = Vector3.MoveTowards(transform.position, target.position, Time.deltaTime * moveSpeed);
    }
}

```

At this line if the distance is less then 0.1f it should start moving back to the original position but the transform is not moving it's just staying at the same place :

```
transform.position = Vector3.MoveTowards(transform.position, originPos, Time.deltaTime * moveSpeed);

```

# Answer
> 1 votes
It seems that your object is likely actually rapidly jittering back and forth between states. This is because you are not making it remember what direction it is traveling in.

The moment `distance < 0.1f` is true, it will indeed start moving back to its origin. However, this will make the comparison untrue again, putting it back on its original trajectory.

The way to fix this is to have the comparison instead toggle a flag that determines the object's current priority, which you would reset whenever it has to move towards its target again.

In addition, you are currently making the object move towards target regardless of the distance variable. This should probably be caught in an else clause, instead.

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


# Question
Title: How can I implement a Varying Jump Height Mechanic for my character?
First of all I want to mention that English is **NOT** my mother tongue, I am using GODOT to make my game and that **I am only 16**, so I don't have any prior programming experience, although, I understand what certain things do.

I am working on my first video game (**a 2D Platformer** about a mole in a deserted world), and I want to implement a "Varying Jump Height Mechanic" for my character. I try to make the controls feel like a hybrid between the games Super Mario Bros 1, Super Castlevania IV, Super Meat-Boy and Mega Man 7.

For now, I managed to give the player the desired air control, however, without having the possibility to control the height of the jump, the movement will feel quite sloppy.
One more thing before I give you the script, all the sprites are placeholders for now, if that has to do with anything of course

**SCRIPT:**

```
extends KinematicBody2D

const SPEED = 125
const GRAVITY = 18
const JUMP_POWER = -325
const FLOOR = Vector2(0, -1)

const FIREBALL = preload("res://Fireball.tscn")

var velocity = Vector2()

var on_ground = false

var is_dead = false

func physicsprocess(delta):

if is_dead == false:

     if Input. is_action_pressed("ui_right"):
         velocity.x = SPEED
         $AnimatedSprite.play("run")
         $AnimatedSprite.flip_h = true
         if sign($Position2D.position.x) == -1:
             $Position2D.position.x *= -1

     elif Input. is_action_pressed("ui_left"):
         velocity.x = -SPEED
         $AnimatedSprite.play("run")
         $AnimatedSprite.flip_h = false
         if sign($Position2D.position.x) == 1:
              $Position2D.position.x *= -1

     else:
         velocity.x = 0
         if on_ground == true:
             $AnimatedSprite.play("idle")

     if Input. is_action_pressed("ui_up"):
         if on_ground == true:
             velocity.y = JUMP_POWER
             on_ground = false

     if Input. is_action_just_pressed("ui_focus_next"):
         var fireball = FIREBALL.instance()
         if sign($Position2D.position.x) == 1:
             fireball.set_fireball_direction(1)
         else:
             fireball.set_fireball_direction(-1)

         get_parent().add_child(fireball)
         fireball.position = $Position2D.global_position

     velocity.y += GRAVITY

     if is_on_floor():
         on_ground = true
     else:
         on_ground = false
         if velocity.y < 0:
             $AnimatedSprite.play("jump")
         else:
             $AnimatedSprite.play("fall")

     velocity = move_and_slide(velocity, FLOOR)

     if get_slide_count() > 0:
         for i in range(get_slide_count()):
             if "Enemy" in get_slide_collision(i).collider.name:
                 dead()

     if Input. is_action_just_pressed("ui_cancel"):
         get_tree().change_scene("titlescreen.tscn")
func dead():
is_dead = true
velocity = Vector2(0, 0)
$AnimatedSprite.play("dead")
$CollisionShape2D.disabled = true
$Timer.start()

func onTimertimeout():
gettree().change_scene("titlescreen.tscn")

```

...............................................................

I hope that I can find someone that is kind, and patient enough to help me with this issue, I would do it myself, but like I said I am 16 so I do not have any experience when it comes to programming. :)

# Answer
I had been doing forms of programming for a decade by the time I was 16, so you may want to not use that as an excuse in the future :)

Generally, the best way to do this is to store a flag when you first initiate a jump by pressing the button. This flag should get unset once your vertical velocity passes through zero again (so, when you fall) OR when you fail to pass the modified ground check.

What modified ground check? Glad you asked. When the jump flag is set, we actually want to look a little further below the character than normal to see if we are still very close above ground. This will require some tuning, but generally we like this to be the space of 3 to 5 input frames.

While this jump flag is set, we keep reading input from the jump button. If it stays pressed, we keep adding vertical velocity at a rate you find suitable.

What does this end up looking like? You press the button, and velocity keeps getting added as long as A) You keep the button pressed AND B) you keep close to the ground AND C) You are actually moving up.

As you are looking for responsive, smooth controls, it may also be worth looking into 'coyote time' which implements much the same idea as I described above to make tight jumps feel more fair.
> 1 votes

---
Tags: 2d, movement, platformer, godot, jumping
---


# Question
Title: How to place same canvas on multiple cameras in Unity?
I know how to do It on one, but I don't know how to do it using multiple cameras, 3 of them are important, i want to show the whole UI except for the minimap. I need to change the camera angle on some spots, while keeping the same canvas for displaying the number of coins XP and the current level.

# Answer
# Option 1:

Set the canvas to be a `Screen Space - Overlay`

This mode means that the canvas renders *last* directly to the screen (in screen space), regardless of which cameras are active and how they're displaying what they display.

# Option 2:

Set the canvas to be a `Screen Space - Camera` and change which camera it renders on when appropriate.

This mode means that the canvas is the *last thing rendered by the indicated camera* and will only render on that camera's view (and if another camera renders afterwards, it will render *over* the canvas). By changing which camera is active you also change which camera the canvas renders to, you maintain the visibility of the canvas.

Option 1 is likely the preferred solution, but depending on your exact needs and camera setup, Option 2 might be what you're looking for.
> 1 votes

# Answer
Here is a simple solution: duplicate another canvas then set this canvas to new camera.
You could use this simple script to read the raw\_image texture from the target canvas:

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

public class CameraTexture : MonoBehaviour
{
    public RawImage camera_texture;
    private RawImage rawImage;
    // Start is called before the first frame update
    void Start()
    {
        rawImage = GetComponent<RawImage>();
    }

    // Update is called once per frame
    void Update()
    {
        rawImage.texture = camera_texture.texture;
    }
}

```
> 1 votes

---
Tags: unity, camera, ui-design
---


title: UnityWebRequest security

text:
# Question
Title: UnityWebRequest security
I have a game where I would like to register users and post the outcome of matches between two users through web requests in Unity but have some security questions regarding `UnityWebRequest`.

Assume the following code for sending a web request:

```
public class TestHTTP : MonoBehaviour
{
    [SerializeField]
    private bool sendRequest = false;
    // Update is called once per frame
    void Update()
    {
        if (sendRequest)
        {
            Model testModel = new Model();
            testModel.ID = "0001";
            testModel.name = "Random_Name";
            testModel.int1 = 555;
            StartCoroutine(SendWebRequest(testModel));
            sendRequest = false;
        }
    }
    public IEnumerator SendWebRequest(Model m)
    {
        string json = JsonUtility.ToJson(m);
        //string text = JsonUtility.ToJson(SimpleAESEncryption.Encrypt(json, "some_password"));
        using (UnityWebRequest request = UnityWebRequest.Post($"some_https", json))
        {
            request.method = UnityWebRequest.kHttpVerbPOST;
            request.SetRequestHeader("Content-Type", "application/json");
            yield return request.SendWebRequest();
            if (request.isNetworkError)
            {
                Debug.Log("NETWORK ERROR:::" + request.error);
            }
            else if (request.isHttpError)
            {
                Debug.Log("HTTP ERROR:::" + request.error);
            }
            else
            {
                string returnData = request.downloadHandler.text;
            }
        };
    }
}

```

After doing a bit of testing I noted that sending via http would give a plain text body, which was remedied by switching to a https target. Is this enough of a level of encryption or should I add a layer of encryption for the model prior to sending?

Lets assume my model contains data regarding the outcome of a match between two players. Would https (TLS 1.2) be enough to stop someone resending the same request/packet to inflate their number of wins for example? Or should additional measures be taken to stop this?

# Answer
> 1 votes
As DMGregory said in his comment on the question, if you try to prevent cheating on the transport layer, you are doing it wrong. A player who wants to cheat has several opportunities to manipulate their match results *before* they get encrypted by the network system. Encrypting the traffic between game client and server doesn't help much against those. It does not even help against reverse-engineering your network protocol, because the client has all the knowledge it needs to decrypt its own https traffic. Many network analysis tools like Wireshark offer that out-of-the-box.

So this answer focuses on what https is actually meant to prevent: Eavesdropping and packet manipulation by **a 3rd** party (neither the player not your gameserver).

I personally would consider match results to be pretty non-critical here. I doubt that any eavesdropper is interested in those, and there is not much to be gained by changing other people's match results in transit. But what I *would* worry about are passwords for authentication. Users are lazy and tend to use the same password everywhere. They should not, but they still do no matter how often they are told not to. That means that compromising the password for your game could compromise the whole online identity of a player. So passwords should always be considered serious business, no matter the context. And if you already implemented serious transport layer security for passwords, then you can just as well use the same for the gameplay data. It doesn't gain you much, but it doesn't hurt much either.

For most scenarios, https should be good enough. It provides you with encryption which is strong enough to prevent any passive eavesdropping. However, the strength against active eavesdropping through man-in-the-middle (mitm) attack is a different question. It depends on how well Unity validates the server certificate. By default, this depends on the platform. Usually it uses the root certificate store of the operating system. Which means that your server needs a valid certificate signed by a trusted Certificate Authority. Some platforms do not check server-sided certificates at all, which allows a mitm attacker to read and manipulate traffic by replacing the server's certificate with a fake one.

So for maximum security, you might want to use your own CertificateHandler and validate it against the public key of your webserver (works on PC, Android and iPhone). Considering that your game is usually only going to communicate with that one server and that you can ship the public key with the game, you have a use-case where a self-signed certificate is actually not a bad idea at all. Getting the certificate authorities out of the picture does not just make things easier, it even improves security in this case because a second certificate by a rogue CA would not get accepted.

An example implementation for a custom certificate handler can be found here.

---
Tags: unity, security, encryption, http
---


# Question
Title: Blender & Unity - Move texture with Bone in way that works with Unity?
I created a character model in Blender with non-spherical eyes. The only way I can make the eye movement look good is if I move the pupil Image Textures along the eye meshes.

The way I've achieved the pupil movement in Blender is with modifiers, which Unity apparently doesn't work with. I've tried "UV Warp" controlled by bone and "UV Project" controlled by bone, and moving the eye bones in Unity does nothing.

So, I'm kind of stumped and desperate for something that will work for my use case. Any ideas that will be Unity-friendly, please?

# Answer
> 2 votes
I know this might be late a late responce to your question, but I happened to have made a solution while making something for VRChat. This script moves textures based on changing their UV offset, which might be different from what you are looking for. Although it is a great alternative.

I recently made a script that works by moving the textures on a shader applied to a material. It works with three different textures, and using a bone rotation from 0-2 (1 is default) on the x and y axis, it moves the texture up and down and side to side. You will need to know how to write in C# to modify the script for your needs. This script was made originally made to move textures on a surface to replicate the movement of an eye. Here is the shader code that the materials need to have when you put them into the script:

```
Shader "Custom/MultilayeredShader"
{
    Properties
    {
        _MainTex ("Eye Texture", 2D) = "white" {}
        _SecondTexture("Lower Eyelid", 2D) = "white" {}
        _ThirdTexture("Upper Eyelid", 2D) = "white" {}
        _GlossinessEyelids ("Smoothness Eyelids", Range(0,1)) = 0.5
        _MetallicEyelids ("Metallic Eyelids", Range(0,1)) = 0.0
        _GlossinessEye("Smoothness Eye", Range(0,1)) = 0.5
        _MetallicEye("Metallic Eye", Range(0,1)) = 0.0
    }
    SubShader
    {
        Tags { "RenderType"="transparent" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _SecondTexture;
        sampler2D _ThirdTexture;
        sampler2D _FourthTexture;

        struct Input
        {
            float2 uv_MainTex;
            float2 uv_SecondTexture;
            float2 uv_ThirdTexture;
            float2 uv_FourthTexture;
        };

        half _GlossinessEyelids;
        half _MetallicEyelids;
        half _GlossinessEye;
        half _MetallicEye;
        fixed4 _Color;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            fixed4 c = (1, 1, 1, 1) + tex2D(_MainTex, IN.uv_MainTex).a * (tex2D(_MainTex, IN.uv_MainTex) - (1, 1, 1, 1));//base white and add eye on top
            c = c + (tex2D(_SecondTexture, IN.uv_SecondTexture).a) * (tex2D(_SecondTexture, IN.uv_SecondTexture) - c);//add lower eyelid on top
            c = c + (tex2D(_ThirdTexture, IN.uv_ThirdTexture).a) * (tex2D(_ThirdTexture, IN.uv_ThirdTexture) - c); // add upper eyelid on top
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = ((tex2D(_SecondTexture, IN.uv_SecondTexture).a+tex2D(_ThirdTexture, IN.uv_ThirdTexture).a) * _MetallicEyelids)  +  ((((tex2D(_SecondTexture, IN.uv_SecondTexture).a + tex2D(_ThirdTexture, IN.uv_ThirdTexture).a)*-1)+1) *  _MetallicEye);
            o.Smoothness = ((tex2D(_SecondTexture, IN.uv_SecondTexture).a + tex2D(_ThirdTexture, IN.uv_ThirdTexture).a) * _GlossinessEyelids) + ((((tex2D(_SecondTexture, IN.uv_SecondTexture).a + tex2D(_ThirdTexture, IN.uv_ThirdTexture).a)*-1) + 1) *  _GlossinessEye);;
            o.Alpha = c.a;
        }
        ENDCG
        //float lerp(float v0, float v1, float t) {
        //  return
        //}
    }
    FallBack "Diffuse"
}

```

Here is the script code (It takes the bones, and eye materials with the shader applied as inputs):

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

public class EyeDriver : MonoBehaviour
{
    // Start is called before the first frame update

    public Material eyeL;
    public Transform eyeLbone;
    public Transform upperLeft;
    public Transform lowerLeft;
    public Transform eyeRbone;
    public Transform upperRight;
    public Transform lowerRight;
    public Material eyeR;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //left eye
        float y;
        float x;
        if (eyeLbone != null || eyeL != null)
        {
            //left eye code
            x = ((eyeLbone.localRotation.eulerAngles.x - 1)*-1);//turn the 0 to 2 to -1 to 1. Then inverse it.
            y = ((eyeLbone.localRotation.eulerAngles.y - 1)) / 20; //turn the 0-2 to -1 to 1. then make it move slower up and down.
            if ((eyeLbone.localRotation.eulerAngles.x - 1) > 0) //if it is negative.. (going towards center of face)
            {

                x = (x / 8);
                eyeL.SetTextureOffset("_MainTex", new Vector2(x, y)); //make it move slower towards the center of the face
            }
            else
            {
                x = (x / 4);
                eyeL.SetTextureOffset("_MainTex", new Vector2(x, y)); //else make it move normal speed aka 1/4 speed.
            }
        }
        //right eye
        if(eyeRbone != null || eyeR != null)
        {
            x = (eyeRbone.localRotation.eulerAngles.x - 1);
            y = (eyeRbone.localRotation.eulerAngles.y - 1) / 20;
            if ((eyeRbone.localRotation.eulerAngles.x - 1) > 0)
            {
                eyeR.SetTextureOffset("_MainTex", new Vector2((x / 4), y));
            }
            else
            {
                eyeR.SetTextureOffset("_MainTex", new Vector2((x / 8), y));
            }
        }
        //upperright
        if (upperRight != null || eyeR != null)
        {
            Transform bone = upperRight;
            string texture = "_ThirdTexture";

            y = ((0.0175f*((bone.localRotation.eulerAngles.y - 2) * (bone.localRotation.eulerAngles.y - 2)))-0.05f);
            if ((bone.localRotation.eulerAngles.y - 1) > 0)
            {
                eyeR.SetTextureOffset(texture, new Vector2(0, y));
            }
            else
            {
                eyeR.SetTextureOffset(texture, new Vector2(0, y));
            }
        }
        //loweright
        if (lowerRight != null || eyeR != null)
        {
            Transform bone = lowerRight;
            string texture = "_SecondTexture";

            y = ((0.0175f * ((bone.localRotation.eulerAngles.y - 2) * (bone.localRotation.eulerAngles.y - 2))) - 0.05f);
            if ((bone.localRotation.eulerAngles.y - 1) > 0)
            {
                eyeR.SetTextureOffset(texture, new Vector2(0, y));
            }
            else
            {
                eyeR.SetTextureOffset(texture, new Vector2(0, y));
            }
        }
        //upperleft
        if (upperLeft != null || eyeL != null)
        {
            Transform bone = upperLeft;
            string texture = "_ThirdTexture";

            y = ((0.0175f * ((bone.localRotation.eulerAngles.y - 2) * (bone.localRotation.eulerAngles.y - 2))) - 0.05f);
            if ((bone.localRotation.eulerAngles.y - 1) > 0)
            {
                eyeL.SetTextureOffset(texture, new Vector2(0, y));
            }
            else
            {
                eyeL.SetTextureOffset(texture, new Vector2(0, y));
            }
        }
        //lowerleft
        if (lowerLeft != null || eyeL != null)
        {
            Transform bone = lowerLeft;
            string texture = "_SecondTexture";

            y = ((0.0175f * ((bone.localRotation.eulerAngles.y - 2) * (bone.localRotation.eulerAngles.y - 2))) - 0.05f);
            if ((bone.localRotation.eulerAngles.y - 1) > 0)
            {
                eyeL.SetTextureOffset(texture, new Vector2(0, y));
            }
            else
            {
                eyeL.SetTextureOffset(texture, new Vector2(0, y));
            }
        }
    }
}

```

The script part of this code is just a proof of concept, the math in the code will need to be changed to fit your needs.

---
Tags: unity, textures, blender
---


title: Using multiple pygame_gui managers

text:
# Question
Title: Using multiple pygame_gui managers
I would like to structure my gui into different panels. so to help keep my code managable i thought it might be a good idea to have a main panel. with its own manager and then a secondary panel with its own manager that gets drawn ontop of the main panel.

Ideally I would have a main screen with a couple of buttons on the left. In the centre of the main screen I can show different panels. (Think of a website with a navbar on the side)

This would make it easier to work on the individual panels and also allow me to place buttons on the panels relative to the panels they will appear on as opposed to having to place them relative to the main panel.

My problem now is that I can't seem to get the events from any of the secondary managers into pygame's event queue.

Is this at all possible? Do I need to show my not-working code?

# Answer
> 0 votes
In the Pygame GUI UI Manager documentation, it states:

> The UI Manager class helps keep track of all the moving parts in the pygame\_gui system.
>
> Before doing anything else with pygame\_gui, create a UIManager and remember to update it every frame.

This seems to suggest that **you can only have one UI Manager.**

Instead, what I think you want is the **UI Layers** feature, which allows you to create multiple GUIs and layer them on top of each other. (*Documentation*) This is done through **UIPanel elements.**

From the UI Layers documentation:

> UI Layers start at 0, which represents the lowest level, and progress upwards as they are needed. Things in higher layers will be drawn on top of things in lower layers if they overlap... HUDs may overlap UI elements that appear ‘in’ game worlds; such as monster health bars. For these occasions there is the **UIPanel element** which works as a container, much like a UI Window, except **you specify what layer of the UI it will draw on** (and thus what it will appear on top of).

---
Tags: gui, python, pygame
---


title: Shader Flickering Normal Map Lighting

text:
# Question
Title: Shader Flickering Normal Map Lighting
I am encountering an issue when using a normal map with directional and/or point lighting. Without using the lighting, I am able to render the object fine. When any amount of lighting is applied, it causes the object to flicker (as shown below).

The lighting also works fine when I am not using a normal map. I believe this is an issue with the shader code. The shader code does allow for more than one light source at a time. However, even if I just use one light source (e.g. one directional light) and the normal mapping, the flickering occurs.

Full Repo: https://github.com/paulburgess1357/ExtraLifeEngine

Vertex Code:

```
#version 330 core
#define MAXIMUM_DIR_LIGHTS 2
#define MAXIMUM_POINT_LIGHTS 2

struct DirectionalLight {
    vec3 direction;
};

struct PointLight {
    vec3 position;

    float constant;
    float linear;
    float quadratic;
};

layout (location = 0) in vec3 model_position;
layout (location = 1) in vec3 model_normals;
layout (location = 2) in vec2 tex_coords;
layout (location = 3) in vec3 in_tangent;
layout (location = 4) in vec3 in_bitangent;

// Global uniforms
layout (std140) uniform uniform_matrices {
    mat4 projection_matrix;
    mat4 view_matrix;
};

layout (std140) uniform uniform_camera_world_position{
    vec3 camera_world_position;
};

uniform int active_dirlight_qty; // Set to -1 during shader initialization
uniform DirectionalLight dirlight[MAXIMUM_DIR_LIGHTS];

uniform int active_pointlight_qty; // Set to -1 during shader initialization
uniform PointLight pointlight[MAXIMUM_POINT_LIGHTS];

// Input
uniform mat4 model_matrix;
uniform mat3 normal_matrix;

// Output
out PointLight tangent_pointlights[MAXIMUM_POINT_LIGHTS];
out DirectionalLight tangent_dirlights[MAXIMUM_DIR_LIGHTS];

out vec3 tangent_camera_position;
out vec3 tangent_fragment_position;
out vec2 fragment_tex_coords;

// Function Definitions
mat3 calc_tbn_matrix(mat3 normal_matrix, vec3 model_normals, vec3 tangent_vec);
PointLight convert_pointlight_to_tangent_space(PointLight pointlight, mat3 tbn_matrix);
DirectionalLight convert_dirlight_to_tangent_space(DirectionalLight dirlight, mat3 tbn_matrix);

void main(){

    // TBN Matrix
    mat3 tbn_matrix = calc_tbn_matrix(normal_matrix, model_normals, in_tangent);

    // Calc fragment_position for gl_Position and tangent_fragment_position
    vec3 fragment_position = vec3(model_matrix * vec4(model_position, 1.0)); // World space

    // Convert Pointlights to Tangent Space
    for(int i = 0; i < active_pointlight_qty; i++){
        tangent_pointlights[i] = convert_pointlight_to_tangent_space(pointlight[i], tbn_matrix);
    }

    // Convert Directional Lights to Tangent Space
    for(int i = 0; i < active_dirlight_qty; i++){
        tangent_dirlights[i] = convert_dirlight_to_tangent_space(dirlight[i], tbn_matrix);
    }

    // Output (tangent_pointlights and tangent_dirlights are also output)
    fragment_tex_coords = tex_coords;
    tangent_camera_position = tbn_matrix * camera_world_position;
    tangent_fragment_position = tbn_matrix * fragment_position;
    gl_Position = projection_matrix * view_matrix * vec4(fragment_position, 1.0);

}

mat3 calc_tbn_matrix(mat3 normal_matrix, vec3 model_normals, vec3 tangent_vec){

    vec3 t = normalize(normal_matrix * tangent_vec);
    vec3 n = normalize(normal_matrix * model_normals);
    t = normalize(t - dot(t, n) * n);
    vec3 b = cross(n, t);
    mat3 tbn_matrix = transpose(mat3(t, b, n));

    return tbn_matrix;

};

PointLight convert_pointlight_to_tangent_space(PointLight pointlight, mat3 tbn_matrix){
    pointlight.position = normalize(tbn_matrix * pointlight.position);
    return pointlight;

};

DirectionalLight convert_dirlight_to_tangent_space(DirectionalLight dirlight, mat3 tbn_matrix){
    dirlight.direction = normalize(tbn_matrix * dirlight.direction);
    return dirlight;
};

```

Fragment Code

```
#version 330 core
#define MAXIMUM_DIR_LIGHTS 2
#define MAXIMUM_POINT_LIGHTS 2

struct DiffuseMaterial {
    sampler2D m_sampler;
};

struct SpecularMaterial {
    sampler2D m_sampler;
    float m_shininess;
};

struct NormalMaterial {
    sampler2D m_sampler;
};

struct DirectionalLight {
    vec3 direction;
};

struct SceneLight {
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

struct PointLight {
    vec3 position;

    float constant;
    float linear;
    float quadratic;
};

// Shader Uniforms
// uniform int active_diffuse_qty;
uniform DiffuseMaterial diffuse_material;

// uniform int active_specular_qty;
uniform SpecularMaterial specular_material;

// uniform int active_normal_qty
uniform NormalMaterial normal_material;

uniform SceneLight scenelight;

uniform int active_dirlight_qty; // Set to -1 during shader initialization
uniform int active_pointlight_qty; // Set to -1 during shader initialization

in DirectionalLight tangent_dirlights[MAXIMUM_DIR_LIGHTS];
in PointLight tangent_pointlights[MAXIMUM_POINT_LIGHTS];

in vec3 tangent_camera_position;
in vec3 tangent_fragment_position;
in vec2 fragment_tex_coords;

// Output
out vec4 fragment_color;

// Function Definitions
vec3 calc_directional_light(DirectionalLight dirlight,
                            DiffuseMaterial diffuse_material,
                            SpecularMaterial specular_material,
                            SceneLight scenelight,
                            vec3 normalized_frag_model_normals,
                            vec3 view_direction,
                            vec2 fragment_tex_coords);

vec3 calc_point_light(PointLight pointlight,
                      DiffuseMaterial diffuse_material,
                      SpecularMaterial specular_material,
                      SceneLight scenelight,
                      vec3 normalized_frag_model_normals,
                      vec3 view_direction,
                      vec2 fragment_tex_coords,
                      vec3 fragment_position);

// Shader
void main() {

    // Normal map to normal vector; Transform to range -1, 1
    vec3 normalized_frag_model_normals = normalize(texture(normal_material.m_sampler, fragment_tex_coords).rgb);

    // Convert normal to tangent space
    normalized_frag_model_normals = normalize(normalized_frag_model_normals * 2 - 1);
    vec3 tangent_view_direction = normalize(tangent_camera_position - tangent_fragment_position);

    // Lighting
    vec3 result = vec3(0.0f);

    // Directional
    for(int i = 0; i <= active_dirlight_qty; i++) {
        result += calc_directional_light(tangent_dirlights[i], diffuse_material, specular_material, scenelight, normalized_frag_model_normals, tangent_view_direction, fragment_tex_coords);
    }

    // Point (active pointlight qty set to -1 during shader compilation)
    for(int i = 0; i <= active_pointlight_qty; i++){
        result += calc_point_light(tangent_pointlights[i], diffuse_material, specular_material, scenelight, normalized_frag_model_normals, tangent_view_direction, fragment_tex_coords, tangent_fragment_position);
    }

    if(result.x == 0.0f && result.y==0.0f && result.z==0.0f){
       result = scenelight.ambient  * vec3(texture(diffuse_material.m_sampler, fragment_tex_coords));
    }

    fragment_color = vec4(result, 1.0);
};

// Function Definitions
vec3 calc_directional_light(DirectionalLight dirlight,
                            DiffuseMaterial diffuse_material,
                            SpecularMaterial specular_material,
                            SceneLight scenelight,
                            vec3 normalized_frag_model_normals,
                            vec3 view_direction,
                            vec2 fragment_tex_coords){

    vec3 light_direction = normalize(dirlight.direction);
    vec3 halfway_btwn_view_and_light_dir = normalize(light_direction + view_direction);

    // Ambient
    vec3 ambient = scenelight.ambient * vec3(texture(diffuse_material.m_sampler, fragment_tex_coords));

    // Diffuse
    float diffuse_impact = max(dot(normalized_frag_model_normals, light_direction), 0.0);
    vec3 diffuse = scenelight.diffuse  * diffuse_impact * vec3(texture(diffuse_material.m_sampler, fragment_tex_coords));

    // Specular
    float specular_impact = pow(max(dot(normalized_frag_model_normals, halfway_btwn_view_and_light_dir), 0.0), specular_material.m_shininess);
    vec3 specular = scenelight.specular * specular_impact * vec3(texture(specular_material.m_sampler, fragment_tex_coords));

    return (ambient + diffuse + specular);
}

vec3 calc_point_light(PointLight pointlight,
                      DiffuseMaterial diffuse_material,
                      SpecularMaterial specular_material,
                      SceneLight scenelight,
                      vec3 normalized_frag_model_normals,
                      vec3 view_direction,
                      vec2 fragment_tex_coords,
                      vec3 fragment_position){

    vec3 light_direction = normalize(pointlight.position - fragment_position);
    vec3 halfway_btwn_view_and_light_dir = normalize(light_direction + view_direction);

    // Ambient
    vec3 ambient  = scenelight.ambient * vec3(texture(diffuse_material.m_sampler, fragment_tex_coords));

    // Diffuse
    float diffuse_impact = max(dot(normalized_frag_model_normals, light_direction), 0.0);
    vec3 diffuse = scenelight.diffuse * diffuse_impact * vec3(texture(diffuse_material.m_sampler, fragment_tex_coords));

    // Specular
    float specular_impact = pow(max(dot(normalized_frag_model_normals, halfway_btwn_view_and_light_dir), 0.0), specular_material.m_shininess);
    vec3 specular = scenelight.specular * specular_impact * vec3(texture(specular_material.m_sampler, fragment_tex_coords));

    // Attenuation
    float distance_to_light = length(pointlight.position - fragment_position);
    float attenuation = 1.0 / (pointlight.constant + pointlight.linear * distance_to_light + pointlight.quadratic * (distance_to_light * distance_to_light));

    ambient  *= attenuation;
    diffuse  *= attenuation;
    specular *= attenuation;

    return (ambient + diffuse + specular);
}

```

# Answer
This is solved! The light variables in the vertex shader were not being converted to tangent space (\< vs \<=). The fix is below:

```
    // Convert Pointlights to Tangent Space
    for(int i = 0; i <= active_pointlight_qty; i++){
        tangent_pointlights[i] = convert_pointlight_to_tangent_space(pointlight[i], tbn_matrix);
    }

    // Convert Directional Lights to Tangent Space
    for(int i = 0; i <= active_dirlight_qty; i++){
        tangent_dirlights[i] = convert_dirlight_to_tangent_space(dirlight[i], tbn_matrix);
    }

```
> 0 votes

---
Tags: opengl, glsl
---


# Question
Title: Is Kip R. Irvine's claim of Assembly being practical for game development accurate?
Kip R. Irvine's book, *Assembly Language for x86 Processors*, sixth edition, begins by comparing the Assembly language against high-level languages. One of the pros for Assembly, was game development:

> Game programmers are experts at writing code that takes full advantage of hardware features in a target system. They use assembly language as their tool of choice because it permits direct access to computer hardware, and code can be hand optimized for speed.

Whereas a high-level language:

> Produces too much executable code, and may not run efficiently.

This caught my attention. While I do realize that Assembly can optimize your programs, perhaps even significantly, I wonder if, at this point, it is at all **practical**?

My skepticism comes from:

* Assembly seems to be difficult to maintain.
* High-level languages aren't so slow.
* I'm pretty sure that we have a handful of cutting-edge games based solely on high-level languages.
* A particular interest in game development is to make your product cross-platform. I can only think of this as a significant obstacle for anyone using Assembly.
* How much is "too much" executable code? I'm not entirely sure how reliable can this measure be.

Even if he meant to use Assembly for specific portions of your game, it still seems (to me) somewhat unpractical.

I'm not particularly advanced in Assembly, so I'm not sure. Are these claims accurate?

# Answer
> 13 votes
99% of the time, the compiler will produce better assembly than you will.

That being said, its often very useful to be able to *read* assembly when working in performance critical environments for a couple of reason:

1. Occasionally the compiler will do something that you're not expecting it to do, generating "bad" code, or otherwise non-optimal code.
2. Debugging release builds on target hardware without any (or very few and untrustworthy) symbols.

These days, it's unusual to write pure assembly. You will have access to various low-level instructions by way of *intrinsics*. For example, a common intrinsic used on PS3/360 was \__fsel. The intrinsic tells the compiler that you want to use a particular instruction, but it lets the compiler work out the best way to slot it into the trace, registers, etc.

So all in all, it's far more useful to be able to read, and understand assembly than it is to *write* it. Just as it is far more useful to understand how your CPU works, than it is to be able to build one ;)

# Answer
> 5 votes
**Portability**

One thing to keep in mind is the issue of portability. It's common to need to develop games library or engine code that will run on a PC (x86), console (PPC for XBox360/PS3/WiiU and x86 for XBone/PS4), mobile (mostly ARM, rarely some x86 or MIPS), and so on. C and its ilk are pretty much as low-level as you can get and still be able to compile your code on a diverse set of CPU architectures.

Higher levels languages and frameworks can abstract even further. Developing your game in Android's Java for instance will let your game run on any Android device without even needing a recompile. Other languages like JavaScript or such will allow your game to run on *any* device.

**Need**

On another note, most games don't *need* to maximize hardware anymore. Look at the glut of Flash and JavaScript games. Look at tech like Unreal3 running in JavaScript via emscripten. They do need that portability, though. The big AAA games that are really stressing the hardware are all written in C++ (rarely C) and scripting languages for game logic and glue so it should be obvious they don't need assembly for speed. They all come out supporting 2-3 platforms at launch with another few usually coming out a few months later making it quite clear how important portability is.

Completely irrelevant of whether assembly *is* or *can be* more efficient than today's C/C++ compilers (and that's arguable), the end result is that the cons of using assembly vastly outweigh the potential benefits even when compared to very high level languages which are highly abstracted from the machine like JavaScript.

**Cost**

As a company picking a language for a new project you also have to weigh tools, productivity, and hiring. You can find a *lot* of people experienced in C++. There are very good tools available for it. The language is decent at allowing a developer to express algorithms directly without worrying about machine details and hence saving time. Other languages do even better in all these area.

If you go with assembly, you have a much smaller pool of developers to hire from. The tools amount to little more than a text editor. Every task is going to involve a lot more time and effort due to the need to explicitly walk the CPU through every non-reusable step of every algorithm.

If you are a company with X time to ship your product and Y dollars to get the job done, you *really* want a language with a competitive (and hence cheap and plentiful) market, time-saving tools, and good developer productivity.

Making your game faster doesn't make you money. Actually shipping the game within budget *does* make you money.

**Knowledge vs Compilers**

A developer who intimately understands the target architecture (the CPU instruction set, architecture, micro-architecture, system buses, peripherals, etc.) can probably write faster code in assembly. The vast majority of developers don't fall into that category, however. A modern C/C++ compiler often has a lot more knowledge about the architecture than most programmers and hence can often generate surprisingly good code (though of course they can still sometimes generate surprisingly bad code).

Keep in mind that modern compilers can employ a number of optimization passes that simply surpass the realm of viability for a human to employ, especially at the project sizes of today's games and on today's highly complex machines and OSes. Various forms of inter-procedural analysis (or whole program analysis) allow the compiler to look at the entire program in ways a human simple can't. They can reason about very complex sets of interactions. They can make decisions with more information than a human can typically deal with at once. This is basic to the trend of all information analysis (look at where data mining has come in recent years as further example). The compiler can often use very advanced and finely tuned heuristics

Observe how many things like the `inline` keyword in C++ is treated as a soft hint by most modern compilers. The simple truth is that most human beings, even very experienced ones, are simply *terrible* at determining when inlining (or other types of optimizations) are actually beneficial or hurtful. The compiler will often ignore the `inline` keyword in cases where its logic determines that inlining would be counter-productive. Especially with inter-procedural analysis, the compiler is able to figure out on its own when to inline functions and when not to, or even when to *partially inline* a function (a technique that vetted assembly programmers might already be aware of, but they're unlikely to know *when* to use for maximal benefit).

The point is that the core assertion of the book you're linking is simply dated. The compilers then were often dumber and the CPU architectures simpler for humans to deal with, but today we have significantly more capable (and complex) technology.

**Case Studies**

Others have noted that Rollercoaster Tycoon was possibly the last major game written in assembly, which came out in 1999. That's 14 years ago, a whole 2 years before GPUs and the programmable graphics pipeline (which *must* be coded in high-level languages if you're sticking with the latest DirectX or OpenGL APIs, I might note, as they've both deprecated and ceased maintaining their assembly syntaxes).

One might look at which games have been written primarily in assembly or which use assembly at all. I will note that not one of the three AAA engines I've dealt with professionally has had even an ounce of assembly; the closest they get is using compiler intrinsics.

I tried to look up a list of games known to be written in assembly language, but honestly can't find any. I *can* find a number of games documented to be written in very high level languages like JavaScript or ActionScript or Python and even articles from some of the most respected lead developers of cutting-edge engines like Tim Sweeney of Epic (Unreal Engine) looking at moving away from C++ to even higher-level languages (as far back as the early 2000s).

I'm not at all big on trying to pretend authoritative opinions are fact, but it's hard to disagree with the lead engineer of Unreal Engine and agree with an academic. Especially when it's hard to find any evidence that backs up said academic. If assembly were more practical, one would expect to see it praised by today's game developers a little bit more.

**Conclusion**

> I wonder if, at this point, \[assembly\] is at all practical?

No.

# Answer
> 3 votes
This statement is too broad and seriously out of date.

Using assembly a programmer can optimize the heck out of it. Highlevel languages abstract details away and are somewhat slower than assembler, but usually this doesn't matter.

"Premature optimization is the root of all evil."

While you surely can program a game in assembler, it isn't really practical. For 90% of the code it does not really matter, how fast it is. It's more important getting it done. Then do profiling and optimize the bits that are too slow. Maybe even rewrite some bits in optimized assembler, but not the whole game.

# Answer
> 2 votes
Chris Sawyer wrote most of RCT in x86 assembly. That was probably one of the last games that used it extensively. Possible? Yes. Currently practical? No.

I am not going to bother restating other people's points about optimization.

# Answer
> 0 votes
This reads more like a statement by a die-hard assembly language hold-out than anything else; I'm not sure if it has any practical merit nowadays (actually I lie; I am sure; it has none) - maybe 15 years ago, not today, and not for a long time.

Let's look at some facts:

* Hand-optimized assembly *can* be faster for sure, but you need to be really *really* good (and know *exactly* what you're doing) - i.e someone like Michael Abrash - in order to beat a modern halfway-decent optimizing compiler.
* x86 is the past - Visual C++ no longer supports inline assembly in x64 programs, for example. I'm certain that nobody wants to limit their possibilities for porting to x64.
* For optimization work that centers around the renderer, assembly doesn't matter a damn - this is all about handing over tasks to a faster processor.
* Use of APIs and frameworks limits your ability to break into assembly; nobody in their right mind is going to write a game engine that doesn't use APIs or frameworks.
* One area which is extremely performance-critical - game logic scripting - is *exactly* where you *can't* (and *don't want to*) use assembly.
* Even in the final analysis, it's a far more productive use of time to *optimize the algorithm* rather than break into assembly. E.g. if a sort function was running slow, would your first instinct be to rewrite it in assembly, or would you instead just look for a faster sort algorithm? I know which one I'd do.

Looking at the author's home page, I see that he's very much rooted in academia and with little in the way of practical experience in basically *anything* (aside from being a founding programmer of a research company almost 30 years ago). That should be enough to establish his credentials.

# Answer
> 0 votes
My answer to all this. Use assembler when you need it and where/when it's feasible. Nothing at all wrong with knowing how software/firmware works with electronic hardware at the root level. You are a better engineer when you understand how software and electronics work together to produce a desired outcome. I've been an electronics engineer etc for some 43 years now and am always in learn more. Graduated DeVry Institute of Tech in Chicago in 1977. What an amazing and rewarding career I've been blessed with...keeping up with all the changes and innovations etc etc...Thank You Lord Jesus!

---
Tags: optimization, assembly
---


# Question
Title: Hiding text/choosing which text to show in unity
i'm making a dialogue system that reads from a text file with a portrait that changes expressions depending on the context. I'm thinking of putting in a "cue" in the text file to determine which expression to show on the screen. Like #1 for default expressions, 2 for happy, etc. But the problem is the cues will show up on the dialogue box as well.

So, is there a specific code to hide texts specifically in unity like how "\n" is not shown in other languages? Because my other solution to this is making two separate files and scripts for the dialogue and expression cues which will probably add confusion and more problems in the future.

# Answer
As far as I know there is nothing like that. But I also don't see why anyone would *need* a feature like that, because there is no way in Unity to put text from a file directly into a UI text element. There is always at least one step in between where you read the content of the text file into a string variable. And this is where I would approach this problem.

For example, you could say that when a line in your text file begins with `{` (or some other character which is unlikely to show up in regular dialogue text) then this line is the facial expression. When the line begins with anything else, it's a line of dialogue.

But maybe you want to add more kinds of "stage directions" later. Audio, effects, and so on. And sooner or later you run out of symbols. So you might want to use just one symbol followed by a word which describes what that symbol means. And if you go so far, then the actual text might not look that special anymore, so it should also be notated by a word. So you might end up with a file format like this:

```
{ "character": "bob" },
{ "emotion": "happy" },
{ "transition": "fade" },
{ "music": "calm.ogg" },
{ "text": "Pleasure to meet you" }

```

Wait a minute... that is JSON! A standardized format for hierarchical key/value data. One which Unity can actually parse out of the box. So you don't even need to write your own file parser. You just need to create a plain old C# class with all the fields which you can have in a line of dialogue and then use the method `JsonUtility.FromJson` to take a text string and create and instance of that class.
> 0 votes

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


# Question
Title: Verlet rope between two moving points connected with a spring joint?
I'm connecting two moving rigidbodies using a spring joint in Unity. Between them, a rope will be rendered using a line renderer and I want it to move realistically as the joints move, without physics.

I've read about verlet integration, but only found examples where one point moves, and the other one is calculated, for example a guy with a grappling gun, swinging back and forth.

Here's the current implementation with spring joints.

The second image shows a nice and smooth verlet rope with a line renderer. It's a little too lenient, but looks good. As this doesn't use physics, it doesn't let me move the object or affect the ship, for example if it was stuck on something.

How do I make an **elastic** rope like the second image, between the spring joints, **without the physics engine**?

# Answer
The solution was quite simple when I studied Verlet integration enough.

By pinning the start and end points to the ship and scrap pile, and then using points and sticks to constrain the points between, I managed to make the rope work exactly like I wanted.

I used this page to learn the details: http://datagenetics.com/blog/july22018/index.html

I also had much us of this video course (4 parts): https://www.youtube.com/watch?v=3HjO\_RGIjCU

Now I'm at the problem that space towing doesn't look good with a spring, but that's a problem for another question. Check that question here as it's related.
> -1 votes

---
Tags: unity, physics, mathematics, rigidbody, graphic-effects
---


# Question
Title: How are Tile Collision Slopes done in Game Maker Studio 2 / GML or in general?
I have been trying to get my slopes to function for almost a month now, doing nothing else with the project. Rewrote it 6-7 times in different collision styles, sometimes coming close to success while still being stuck with absolutely no help I could find during this month.

Here are the methods that I tried and what happened:

First I followed a video tutorial specific to game maker 2's tile collisions. It fills an array with how many pixels are filled on the y axis for every pixel on the x. Then it calculates how deep the player's (bounding box) bottom-center is in the slope tile and pushes him above the corresponding pixel count from the array.

Worked great for my floor slopes, didn't for my ceiling slopes. So I tried to reverse the way the pixels are counted and got a proper array, however fiddling with this system for 2 weeks alone, I still got stuck, presumably due to a math error.

If you are interested about this system, I basically posted everything there is to it on the yoyogames forums: Here

I definitely need ceiling slopes to work, since the game is a Metroidvania like game, where there might be a lot more vertical movement going on.

But then I figured, I could simplify this whole procedure, since my pixel art aesthetic currently uses one type of slope (where I potentially would like to keep the system to work with any slope that is a straight line for future additions) Currently my only slope is 2 tiles wide and 1 tile high.

I tried around with setting the player's y coordinate according to the linear function y = m\*x + b I tested this by putting in y = -0.5 * current player position + the y coordinate of the slope tile in the room. However this function sets my player a fair bit above the slope, in the air. I know this is a lot to ask and maybe I'm totally stupid about this problem but I really tried HARD on this one, with my current knowledge and the one that is readily available I can't solve my issue.

# Answer
Turns out the answer was indeed calculating it with y = m\*x + b Which means for game maker studio: Get the slope tiles x and y coord = x/y & ~ TILE\_SIZE\_MINUS\_ONE make a switch case for your slope detection (I made them not detectable for my other tile collision so tilemap\_get\_at\_pixel returns 0 for air, 1 for full solid blocks and anything from 2-9 for the slopes) then populate the formula, which differs a bit from slope to slope. My bottom floor right slope made it so the formula was: y = -1 * (x - Tile\_x) + TILE\_SIZE + Tile\_Y - 1 - sprite\_bbox\_bottom;

Since Tile X and Tile Y are the top left corner of the cell I need to add (remember, this means go down in GMS and many other engines) the Tile Size to get to the origin point where x = 0 (where the slope starts, basically). - 1 to stand above the tile by 1 pixel and - this bbox variable, which was calculated to be the distance between the bounding box and the origin of the sprite (center).

Sad that nobody could help me with this but hey, now I know. Thanks for reading.
> 1 votes

---
Tags: 2d, platformer, game-maker-studio-2
---


title: Comparing strings doesn't work

text:
# Question
Title: Comparing strings doesn't work
I'm making something for a dialogue system that reads "cues" from a textfile to identify which emotion to show in the character's portrait during a conversation. Basically if the current line says "2", it means change the portrait to where the character is smiling. "1" for neutral, etc. Unfortunately the part that compares the emotion variable, and the string from the text file doesn't return true.

I already checked using debug.log if the string from the text file is showing the right number, and it does. I tried comparing them using "==" sign and ".equals();" but neither seems to work.

```
public TextAsset textFileP;
public string[] textLineP;
public GameObject character;
public Animator anim;
public string smile = "2";

void Start()
{
    anim = GetComponent<Animator>();

    if (textFileP != null)
    {
        textLineP = (textFileP.text.Split('\n'));
        character.SetActive(true);
    }
}

void Update()
{

    if (DialogueParser.nextLine < DialogueParser.textLine.Length - 1)
    {

        //change portrait
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            string cue = textLineP[DialogueParser.nextLine];
            // Debug.Log(cue);
            if (cue.Equals(smile))
            {
                anim.SetInteger("2", 2);
            }

        }

```

# Answer
When you create your text file with most text editors on Windows, then lines aren't terminated just by the line-feed character (`\n`) but also by an additional carriage-return character before it (`\r\n`). So when you split such a text file by `\n`, then you will receive a bunch of strings suffixed by the invisible `\r` character.

You can actually see that in Notepad++ when you enable display of these symbols with `View`-\>`Show Symbol`-\>`Show End Of Line`. You will notice that there are not one but two invisible characters at the end of each line.

To fix that problem, split the file by `"\r\n"`. Or if you want to make sure that it works even when your content creators use Linux (which uses only `\n`) or MacOS (which uses only `\r`), then you might either have to normalize your file content with `.Replace`, or you split the string in a way which accepts any flavor of line endings.
> 1 votes

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