# Question
Title: Smooth out movement of the snake in a 2d Snake game
I am working on a 2-D snake game in C++ with the SFML library. I would like to smooth out the movement of my snake as it looks extremely choppy currently.

## How the Snake moves

The snake is made up of a **list of parts**. If I want to move the snake, I simply remove one part from the back (`.pop_back()`) and then add a new part in the front **accrding to the velocity**. This works perfectly. The speed of the snake *must* be the same as the distance between the parts. So if the distance is **15**, the will be 15. But a speed of 15 is extremely high, so I need to only update the snake every few frames or use `sf::Sleep()`. Since the snake moves such a high distance every frame, the movement doesn't look smooth at all. And since the speed must be equal to the distance between the parts, reducing the speed doesn't work too. How can I come about tackling this?

# Answer
> 0 votes
This solution is for grid based games. The idea is to have "turns". A turn will happen regardless of whatever or not there is input or not. At the end of the turn the avatar will be aligned to the grid, and a turn always takes the same time.

Pseudo-code:

```
var current_time = get_current_time();
var elapsed_time = current_time - start_time;
update_input(ref input);
if (elapsed_time > turn_duration)
{
    elapsed_time -= turn_duration;
    start_time += turn_duration;
    for (var part_index = 0; part_index < tail.length - 1; part_index++)
    {
        var part = tail[part_index];
        var next_part = tail[part_index + 1];
        part.start_position = part.end_position;
        part.end_position = next_part.start_position;
    }

    var final_part = tail[tail.length - 1];
    final_part.start_position = final_part.end_position;
    final_part.end_position = head.start_position;
    head.start_position = head.end_position;
    head.end_position = compute_next_position(head.start_position, input);
}

head.current_position = interpolate(head.start_position, head.end_position, elapsed_time);
for (var part_index = 0; part_index < tail.length; part_index++)
{
    var part = tail[part_index];
    part.current_position = interpolate(part.start_position, part.end_position, elapsed_time);
}

```

Thus, for every part, and for the head, we are storing where it was at the start of the "turn", and where it will be at the end of the turn. We use the elapsed time since the start of the turn to compute the current position via interpolation.

When, the turn ends, we use the input and the last position of the head to compute the next position of the head.

You can buffer input if you like. You can treat no input as going in the same direction if you like.

*The code above can be modded to interrupt the motion. That would require to have an `end_time` and check against that, instead of `turn_duration`. Then you can update the motion as soon as input comes, and still have the turn end at the same instant. However, I do not think that is appropriate for snake.*

# Answer
> 0 votes
(I can copy this over to your original question if you'd like to undelete that one and delete/close this one instead)

I'd solve this by storing an array of the grid points the snake head has run through, and the next point it's on its way toward.

Then we'll store a progress variable between 0 and 1, that represents how far the snake has progressed from its old position to its new position.

We'll number our snake parts from 0 for the head up to `snakeSize - 1` for the last tail segment. In our `positionHistory` array, 0 will be the point the head is moving toward now, 1 will be the point the head just left, and `snakeSize` will be the point the last tail segment just vacated.

We can update the state like so:

```
progress += deltaTime / secondsToCrossOneTile;

if (progress >= 1.0f) {
     // TODO: Handle activating a new tail segment here
     //       when finishing the previous growth phase.

     // TODO: Handle eating a pellet here and beginning a new growth phase.

     for (int i = snakeSize; i > 0; --i) {
         positionHistory[i] = positionHistory[i - 1];
     }

     positionHistory[0] = PickNextPoint();

     progress -= 1.0f;
}

```

(You could also store your history as a circular buffer, and just shift the starting offset instead of copying all the data over one notch)

Now every frame we can run through each piece in the list, using this progress value as an interpolation weight between its old position and the new position.

```
for(int i = 0; i < snakeSize; i++) {
    snakePart[i].position = lerp(positionHistory[i+1], positionHistory[i], progress);
}

```

When you want to add a segment to the snake, you place it at the position of the last tail segment, and leave it stationary there until the next time we hit our `progress >= 1.0f` condition. Then you append it to the `snakePart` collection and extend the position history an extra notch.

---
Tags: c++, physics, movement, sfml, snake
---


title: Footstepper with Vr Unity

text:
# Question
Title: Footstepper with Vr Unity
I have the Footstepper: Complete Footstep Solution from the unity store, and i dont get it working with the Vr,

I made the footstep material like official documentation said, Then i put the Footstepper Setup in the ovrPlayer object.

The problem is that sometimes sound the default fallback, so i think that the colission is not detected as it suppose.

Some idea ?

# Answer
Effectively i change the Raycast Settings to get more height and it works :)
> 0 votes

---
Tags: unity, assets, virtual-reality
---


# Question
Title: How can I access a variable on a script in another scene that I made it dontdestroyonload?
I need to get access to the variable flag loading from some script in another scene. The variable loading in my main menu scene and I need to access it in scripts in my game scene.

I'm not sure if using dontdestroyonload in this case is the right way and I don't want to make the loading variable public static either :

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEditor;
using Cinemachine;
using UnityStandardAssets.Characters.ThirdPerson;

public class MenuController : MonoBehaviour
{
    #region Default Values
    [Header("Default Menu Values")]
    [SerializeField] private float defaultVolume;
    [SerializeField] private int defaultSen;
    [SerializeField] private bool defaultInvertY;

    [Header("Levels To Load")]
    public string _newGameButtonLevel;
    private string levelToLoad;

    public SceneFader sceneFader;
    public GameObject player;

    private int menuNumber;
    #endregion

    #region Menu Dialogs
    [Header("Main Menu Components")]
    [SerializeField] private GameObject menuDefaultCanvas;
    [SerializeField] private GameObject GeneralSettingsCanvas;
    [SerializeField] private GameObject graphicsMenu;
    [SerializeField] private GameObject soundMenu;
    [SerializeField] private GameObject controlsMenu;
    [SerializeField] private GameObject confirmationMenu;
    [Space(10)]
    [Header("Menu Popout Dialogs")]
    [SerializeField] private GameObject noSaveDialog;
    [SerializeField] private GameObject newGameDialog;
    [SerializeField] private GameObject loadGameDialog;
    #endregion

    #region Slider Linking
    [Header("Menu Sliders")]
    [SerializeField] private Text controllerSenText;
    [SerializeField] private Slider controllerSenSlider;
    public float controlSenFloat = 2f;
    [Space(10)]
    [SerializeField] private Text volumeText;
    [SerializeField] private Slider volumeSlider;
    [Space(10)]
    [SerializeField] private Toggle invertYToggle;
    #endregion

    public bool loading = false;

    #region Initialisation - Button Selection & Menu Order
    private void Start()
    {
        DontDestroyOnLoad(this);
        menuNumber = 1;
    }
    #endregion

    //MAIN SECTION
    public IEnumerator ConfirmationBox()
    {
        confirmationMenu.SetActive(true);
        yield return new WaitForSeconds(2);
        confirmationMenu.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (menuNumber == 2 || menuNumber == 7 || menuNumber == 8)
            {
                GoBackToMainMenu();
                ClickSound();
            }

            else if (menuNumber == 3 || menuNumber == 4 || menuNumber == 5)
            {
                GoBackToOptionsMenu();
                ClickSound();
            }

            else if (menuNumber == 6) //CONTROLS MENU
            {
                ClickSound();
            }
        }
    }

    private void ClickSound()
    {
        GetComponent<AudioSource>().Play();
    }

    #region Menu Mouse Clicks
    public void MouseClick(string buttonType)
    {
        if (buttonType == "Controls")
        {
            controlsMenu.SetActive(true);
            menuNumber = 6;
        }

        if (buttonType == "Graphics")
        {
            GeneralSettingsCanvas.SetActive(false);
            graphicsMenu.SetActive(true);
            menuNumber = 3;
        }

        if (buttonType == "Sound")
        {
            GeneralSettingsCanvas.SetActive(false);
            soundMenu.SetActive(true);
            menuNumber = 4;
        }

        if (buttonType == "Exit")
        {
            Debug.Log("YES QUIT!");
            Application.Quit();
        }

        if (buttonType == "Options")
        {
            menuDefaultCanvas.SetActive(false);
            GeneralSettingsCanvas.SetActive(true);
            menuNumber = 2;
        }

        if (buttonType == "LoadGame")
        {
            menuDefaultCanvas.SetActive(false);
            loadGameDialog.SetActive(true);
            menuNumber = 8;
        }

        if (buttonType == "NewGame")
        {
            menuDefaultCanvas.SetActive(false);
            newGameDialog.SetActive(true);
            menuNumber = 7;
        }
    }
    #endregion

    public void VolumeSlider(float volume)
    {
        AudioListener.volume = volume;
        volumeText.text = volume.ToString("0.0");
    }

    public void VolumeApply()
    {
        PlayerPrefs.SetFloat("masterVolume", AudioListener.volume);
        Debug.Log(PlayerPrefs.GetFloat("masterVolume"));
        StartCoroutine(ConfirmationBox());
    }

    public void ControllerSen()
    {
        controllerSenText.text = controllerSenSlider.value.ToString("0");
        controlSenFloat = controllerSenSlider.value;
    }

    #region ResetButton
    public void ResetButton(string GraphicsMenu)
    {
        if (GraphicsMenu == "Audio")
        {
            AudioListener.volume = defaultVolume;
            volumeSlider.value = defaultVolume;
            volumeText.text = defaultVolume.ToString("0.0");
            VolumeApply();
        }

        if (GraphicsMenu == "Graphics")
        {
            controllerSenText.text = defaultSen.ToString("0");
            controllerSenSlider.value = defaultSen;
            controlSenFloat = defaultSen;

            invertYToggle.isOn = false;
        }
    }
    #endregion

    #region Dialog Options - This is where we load what has been saved in player prefs!
    public void ClickNewGameDialog(string ButtonType)
    {
        if (ButtonType == "Yes")
        {
            // Here to use a script to load the start game scene slowly smooth fade to black
            // Then fade back to transparent when loading/loaded the scene game !!!!!
            //SceneManager.LoadScene(_newGameButtonLevel);

            // When making new game to reset everything state scene everythig.
            // Including the uiSceneText for example.
            // To check how to reset everything to default !
            loading = false;
            newGameDialog.SetActive(false);
            StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, _newGameButtonLevel));
        }

        if (ButtonType == "No")
        {
            GoBackToMainMenu();
        }
    }

    public void ClickLoadGameDialog(string ButtonType)
    {
        if (ButtonType == "Yes")
        {
            //if (PlayerPrefs.HasKey("SavedLevel"))
            //{
            //Debug.Log("I WANT TO LOAD THE SAVED GAME");
            //LOAD LAST SAVED SCENE
            //levelToLoad = PlayerPrefs.GetString("SavedLevel");
            //SceneManager.LoadScene(levelToLoad);
            loading = true;
            newGameDialog.SetActive(false);
            StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, _newGameButtonLevel));

            //}

            /*else
            {
                Debug.Log("Load Game Dialog");
                menuDefaultCanvas.SetActive(false);
                loadGameDialog.SetActive(false);
                noSaveDialog.SetActive(true);
            }*/
        }

        if (ButtonType == "No")
        {
            GoBackToMainMenu();
        }
    }
    #endregion

    #region Back to Menus
    public void GoBackToOptionsMenu()
    {
        GeneralSettingsCanvas.SetActive(true);
        graphicsMenu.SetActive(false);
        soundMenu.SetActive(false);

        VolumeApply();

        menuNumber = 2;
    }

    public void GoBackToMainMenu()
    {
        menuDefaultCanvas.SetActive(true);
        newGameDialog.SetActive(false);
        loadGameDialog.SetActive(false);
        noSaveDialog.SetActive(false);
        GeneralSettingsCanvas.SetActive(false);
        graphicsMenu.SetActive(false);
        soundMenu.SetActive(false);
        menuNumber = 1;
    }

    public void ClickQuitOptions()
    {
        GoBackToMainMenu();
    }

    public void ClickNoSaveDialog()
    {
        GoBackToMainMenu();
    }
    #endregion
}

```

At the top line 56 :

```
public bool loading = false;

```

Inside Start at line 61 :

```
DontDestroyOnLoad(this);

```

Then inside the method for starting a new game in line 207 :

```
loading = false;

```

And in the method that loading a saved game in line 228 :

```
loading = true;

```

Now that I know when it's starting a new game and when it's loading a game I want to use this loading variable in some scripts in my game scene.

For example this script :

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

public class SceneFader : MonoBehaviour
{
    #region FIELDS
    public GameObject fadeOutUIGameobjectImage;
    public float fadeSpeed = 0.8f;

    private MenuController menuController;
    private Image fadeOutUIImage;

    private void Start()
    {

    }

    public enum FadeDirection
    {
        In, //Alpha = 1
        Out // Alpha = 0
    }
    #endregion

    #region FADE
    public IEnumerator Fade(FadeDirection fadeDirection)
    {
        fadeOutUIGameobjectImage.SetActive(true);

        float alpha = (fadeDirection == FadeDirection.Out) ? 1 : 0;
        float fadeEndValue = (fadeDirection == FadeDirection.Out) ? 0 : 1;
        if (fadeDirection == FadeDirection.Out)
        {
            while (alpha >= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
            fadeOutUIGameobjectImage.SetActive(false);
        }
        else
        {
            fadeOutUIGameobjectImage.SetActive(true);
            while (alpha <= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
        }
    }
    #endregion

    #region HELPERS
    public IEnumerator FadeAndLoadScene(FadeDirection fadeDirection, string sceneToLoad)
    {
        yield return Fade(fadeDirection);
        SceneManager.LoadScene(sceneToLoad);

        SceneManager.sceneLoaded += SceneManager_sceneLoaded;
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        if (menuController.loading == true)
        {
            var saveLoad = GameObject.Find("Save System").GetComponent<SaveLoad>();
            saveLoad.Load();
        }
    }

    private void SetColorImage(ref float alpha, FadeDirection fadeDirection)
    {
        if(fadeOutUIImage == null)
        {
            fadeOutUIImage = fadeOutUIGameobjectImage.GetComponent<Image>();
        }

        fadeOutUIImage.color = new Color(fadeOutUIImage.color.r, fadeOutUIImage.color.g, fadeOutUIImage.color.b, alpha);
        alpha += Time.deltaTime * (1.0f / fadeSpeed) * ((fadeDirection == FadeDirection.Out) ? -1 : 1);
    }
    #endregion
}

```

At the top I did :

```
private MenuController menuController;

```

Then inside the event SceneManager\_sceneLoaded I did at line 67 :

```
if (menuController.loading == true)

```

but I didn't make any reference to the MenuController script even if it's not destroyed. so loading will be null here I guess.

The idea is to use global in my project with the loading bool flag variable to find if the game is loading or if a new game started.

# Answer
There are at least two ways. Either you can

1. make singelton of your menucontroller, store static instance variable in script and access that way
2. or find object from your scene

**Singelton** (something like this):

```
public static MenuController Instance { get; private set; }

public Awake() {
     if (Instance != null && Instance != this)
     {
         Destroy(this.gameObject);
         return;
     }

     Instance = this;
     DontDestroyOnLoad( this.gameObject );
 }

```

And access it

```
 MenuController.Instance.CallSomeMethod();

```

Or **find object**: https://docs.unity3d.com/ScriptReference/GameObject.Find.html

Example from Unity page:

```
 // This returns the GameObject named Hand.
 hand = GameObject.Find("Hand");

```

Note that find object takes time, so do it once in Start().
> 2 votes

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


# Question
Title: Instantiating GameObjects in Custom Game Engine
So,i'm having a bit of an issue with instantiating my gameobjects into to universe(My Scene object).

I can create an empty object from scratch and populate it from there with ease,my problem starts when i try to clone the gameobject which i just created.

My steps are

1. I create an empty gameobject (GAMEOBJECT A)
2. I add an component to it (COMPONENT A)
3. Now i create a gameobject B from A
4. GameObject B created,and the component A is in the component list of the gameobject B
5. I try to get the component using inheritance but nullptr returns

It seems when i try to clone components,it returns only the base class pointer.There i try to recreate the derived class and add it to new gameobject's component list but obviously i fail.

* If i cant solve this with inheritance how can i solve it ?
* is there better way to implement such a desing ?
* or i just fail to use inheritance in c++.If it's, can you guys point out what am i doing wrong here

This is my GameObject AKA RGameElement

```
class RGameElement
{
protected:
    vector<RElementComponent*> Elements;
public:
    template <class T>
    T* GetComponent() {

        int elementSize = Elements.size();

        for (int i = 0;i < elementSize;i++)
        {
            T* pr = dynamic_cast<T*>(Elements[i]);
            if (pr != nullptr)
                return pr;
        }
        return nullptr;
    }
    template <class T>
    T* AddComponent() {

        T* newElementComp = new T();
        Elements.push_back(newElementComp);
        return newElementComp;
    }
    void AddComponent(RElementComponent* targetComponent)
    {
        RElementComponent* newElement = new RElementComponent();

        *newElement = *targetElement;

        Elements.push_back(newElement);
    }

    /*void AddComponent(RElementComponent* targetComponent);*/
    vector<RElementComponent*> GetComponent() const;
}

```

This is my Component AKA RElementComponent

```
class RGameElement;

class RElementComponent
{
public:
    RGameElement* RootGameElement;
    virtual RElementComponent GetReference() { return RElementComponent(); };
    virtual void Setup() {};
    virtual void StartLogic() {};
    virtual void UpdateLogic() {};

}

```

and this my Instantiate via gameobject ref function

```
RGameElement* RUniverse::Instantiate(RGameElement* targetGameElement)
{
    RGameElement* newElement = new RGameElement();

    vector<RElementComponent*> components = targetGameElement->GetComponents();
    int componentSize = components.size();

    for (int i = 0;i < componentSize;i++)
    {
        newElement->AddComponent(components[i]);
    }

    Elements.push_back(newElement);
    return newElement;
}

```

# Answer
> 0 votes
I managed to solve it with the help of the comments.

It seems i needed a interface to copy the derived object's data.

So

* Created a pure virtual function inside a base class Clone()
* Implemented that virtual function inside the derived class

Code looks like this

Base Element Class

```
class RElementComponent
{
public:
    RElementComponent* RootGameElement;
    virtual RElementComponent* Clone() = 0;
    virtual void Setup() {};
    virtual void StartLogic() {};
    virtual void UpdateLogic() {};

};

```

Derived class

```
class RObserver : public RElementComponent
{
public:
    int myOb;
    RObserver();
    void WhoAreYou();
    RObserver* Clone()
    {
        RObserver* observer = new RObserver();
        *observer = *this;
        return observer;
    }
};

```

---
Tags: c++, architecture, software-engineering, gameobject
---


# Question
Title: Unity Prevent reloading of edited files packages
I had to make a change in the existing Universal Rendering Pipeline's `ShadowCaster2D.cs` to suit my needs. But every time I reload the project, the file gets reset. How do I prevent this?

The file that I need to keep is found in the following path:

```
(Unity Project path)\Library\PackageCache\com.unity.render-pipelines.universal@7.1.7\Runtime\2D\ShadowCaster2D.cs

```

# Answer
> 0 votes
TLDR: following this unity forum thread, I just followed what polemical said which was to

> in Project window, right-click the package, select "Show in Explorer". Then copy that package to another folder outside the project structure, then in Package Manager click the + and click "Add package from disk" and browse to the package.json of your copy - whatever changes to that won't be overwritten.

I tried to wrap my head around creating a script to modify the script but I'm a bit short on time. **For now, this is the answer** as also suggested by Benjamin.

If there's a better solution, I can mark that as an answer.

---

update 1: Since we're using a repository to handle the code, selecting the custom unity package locally is not advisable as Unity **will** crash upon startup because it can't locate the file in someone else's computer. to fix this, we had to create a repository that each one of us can access. Remove the local unity package and add the custom package using git url. the problem will be fixed

# Answer
> 0 votes
For some reason I can't comment so I'm going to have to answer instead. One option (I'm not sure it will work) is to modify the file in the package cache. I believe that unless you clear it, unity will pull the files from there each refresh. Another option is to create a script that runs on project reload and overwrites the file with the version you want.

## Possible ways to receive callbacks

I haven't tested these and I'm not sure if they will work, but I hope they'll be helpful to you.

* `EditorApplication.playModeStateChanged`
* `IPreprocessBuildWithReport`
* `AssetsModifiedProcessor`
* `UnityEditor.Build` namespace

You mentioned the project reloading, so `EditorApplication.projectChanged` might be of help to you as well. These links https://answers.unity.com/questions/704066/callback-before-unity-reloads-editor-assemblies.html https://docs.unity3d.com/ScriptReference/Callbacks.DidReloadScripts.html might also provide you with enough information to solve your problem.

As a last resort, you could create your own copy of `ShadowCaster2D` and use that behaviour instead of the default one

# Answer
> 0 votes
Don't edit the package in the Library, copy it to YourProject/Packages instead. The folder inside the Library can and will be overwritten at any time. The intended place for packages you don't want downloaded is YourProject/Packages.

---
Tags: unity, file
---


# Question
Title: Unity build issue - GooglePlayGamesManifest and GameServicesManifest
I have added leaderboard to my unity game for which I have used the google play services plugin. But when I try to build, this is the error I get:

```
 Execution failed for task 'processReleaseManifest'.
> Manifest merger failed : Attribute meta-data#com.google.android.gms.games.APP_ID@value value=
(\728999946156) from [:unityLibrary:GameServicesManifest.plugin] AndroidManifest.xml:10:13-42
is also present at [:unityLibrary:GooglePlayGamesManifest.plugin] AndroidManifest.xml:20:13-46 value=
(\u003728999946156).
Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:8:9-
10:45 to override.

```

Here's what's in the first manifest file:

```
<?xml version="1.0" encoding="utf-8"?>
<!-- This file was automatically generated by the Google Play Games plugin for Unity
 Do not edit. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.example.games.mainlibproj"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="14" />
<application>
    <!-- The space in these forces it to be interpreted as a string vs. int -->
    <meta-data android:name="com.google.android.gms.games.APP_ID"
        android:value="\u003728999946156" />
    <!-- Keep track of which plugin is being used -->
    <meta-data android:name="com.google.android.gms.games.unityVersion"
        android:value="\u0020.20.20" />
    <activity android:name="com.google.games.bridge.NativeBridgeActivity"
        android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
</application>

```

and the second file:

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package="com.google.example.games.mainlibproj">
<application>
<meta-data android:name="com.google.android.gms.games.APP_ID" android:value = "\728999946156" />
<activity android:name="com.google.games.bridge.NativeBridgeActivity" android:theme =
"@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
</application>
</manifest>

```

# Answer
I restarted my unity project and the problem no longer exists. I'm not sure how it got resolved....
> 0 votes

---
Tags: unity, google-play-services
---


title: Pyglet Layout won't render?

text:
# Question
Title: Pyglet Layout won't render?
Here's some sample code I copy pasted to try and get a Pyglet layout to work. I just get a blank screen. Every time I try to write my own code based on the docs or copy/paste some example code it just will not render the layout.

Interwebs reveal a few other people with this issue but no answers given.

Labels seem to work fine although even they are quirky.

```
import pyglet

white = (255, 255, 255, 255)

window = pyglet.window.Window(width=200, height=200, caption='Text layout')

# document
document = pyglet.text.decode_text(
    ('Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! '
     'Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!'))
document.set_style(start=0, end=0, attributes=dict(font_size=12, color=white))

# text layout
text_layout = pyglet.text.layout.TextLayout(document=document,
                                            width=window.width,
                                            height=window.height,
                                            multiline=True,
                                            wrap_lines=True)
text_layout.color = (.5,.5,.5,1.0)

@window.event
def on_draw():
    window.clear()
    text_layout.draw()

pyglet.app.run()

```

# Answer
It turns out I need to declare a font type in the attributes of the document.

I added:

```
font_name="Times New Roman"

```

to the attributes dictionary and voila. Frustrating that all the examples I found did not explicitly declare a font type, and yet for me this seems to be a requirement. I was just about to give up and roll my own text renderer.
> 1 votes

# Answer
This was the only example I could find for use of text\_layout, but to make it work, I needed the change the following line:

```
document.set_style(start=0, end=0, attributes=dict(font_name="Times New Roman"
    ,font_size=12, color=white))

```

to:

```
document.set_style(start=0, end=len(document.text), attributes=dict(
    font_name="Times New Roman" ,font_size=12, color=white))

```

I would have expected that end=0 would do the whole document, but no.
> 1 votes

---
Tags: python, pyglet
---


title: Unity ads issue - null reference error

text:
# Question
Title: Unity ads issue - null reference error
I'm trying to add unity ads to my game. In my game there are three panels - startgame, ingame and gameover. Once the game starts, only the startgame panel is active and once you tap on the screen, the ingame panel gets actived and startgame panel is deactivated. In the ingame panel I have added a button to show ads (once an ad is ready) so that after watching the ad, user can receive 100 additional points. Here is my admanager script:

```
string GooglePlay_ID = "123456";
bool test_mode = true;
string myPlacementId = "rewardedVideo";

public Button inGameAdBtn;

void Start()
{
  inGameAdBtn = GetComponent<Button>();
  inGameAdBtn.interactable = Advertisement.IsReady(myPlacementId);
  if (inGameAdBtn) inGameAdBtn.onClick.AddListener(ShowRewardedVideo);

  Advertisement.AddListener(this);
  Advertisement.Initialize(GooglePlay_ID, test_mode);
}

public void ShowRewardedVideo()
{
    Advertisement.Show(myPlacementId);
}

public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{

    if (showResult == ShowResult.Finished)
    {
        GameManager.instance.GetPoints();
    }

else if (showResult == ShowResult.Skipped)
    {

    }

    else if (showResult == ShowResult.Failed)
    {
        Debug.LogWarning("The ad did not finish due to an error.");
    }
}

public void OnUnityAdsReady(string placementId)
{
    // If the ready Placement is rewarded, show the ad:
    if (placementId == myPlacementId)
    {
        inGameAdBtn.interactable = true;
    }
}

public void OnUnityAdsDidError(string message)
{
    // Log the error.
}

public void OnUnityAdsDidStart(string placementId)
{
    // Optional actions to take when the end-users triggers an ad.
}

```

When I hit play, I get an error in the console saying - NullReferenceException: Object reference not set to an instance of an object. When I click on it, it takes to this line of code "inGameAdBtn.interactable = Advertisement.IsReady(myPlacementId);".

I believe this is because once the game starts, the ingame panel is inactive and the admanager script is looking for the inGameAdBtn (which is in the ingame panel). Is there any way to resolve this issue?

**EDIT**

I have added a screenshot of the game. This is after I hit play, the first panel that is activated is the StartPanel and once I tap on the screen, the next panel will activate (InGamePanel) and the StartPanel will deactivate. The inGameAds button is in the InGamePanel which is currently inactive.

# Answer
> 0 votes
```
inGameAdBtn = GetComponent<Button>();

```

This line of code says "throw away whatever the designer assigned to the `inGameAdBtn` in the Inspector, and replace it with the `Button` component attached to this object.

...but there is no `Button` component attached to this object in your screenshot. So this throws away a perfectly good button and replaces it with `null`, the absence of a button.

Naturally when you next try to use this button, while holding only the absence of a button, you get an exception.

If you plan to wire up this reference in the Inspector, delete this line of code that tries to search for it on this object — it's not doing anything you want it to do.

---
Tags: unity, unity-ads
---


# Question
Title: How does faction work in a Multiplayer game?
I'm trying to work out how Factions would work in any Standard MMO

If the player is hostile with a faction, then the NPC's of that faction would attack on sight.

If the player is neutral\> with a faction, then the NPC's of that faction wouldn't attack on sight.

The "Reputation Value" would be an integer.

```
Hostile = 0
Unfriendly = 2000
Neutral = 4000
Friendly = 6000
Honored = 8000
Revered = 10000
Exalted = 12000

```

**Example:**

When the player Logs in. The Bandit faction must find out the Player's Reputation Value towards them.

```
if Player.Bandit.UNFRIENDLY or Player.Bandit.HOSTILE:
    the NPC would be able to attack the player on-sight.
if Player.Bandit.NEUTRAL or FRIENDLY or HONORED or REVERED or EXALTED:
    the NPC won't be able to attack the player on-sight.

```

or

```
ReputationValue = Player.Bandit.Reputation

if ReputationValue > 4000
   the NPC won't be able to attack the player on-sight.
else
   the NPC will be able to attack the player on-sight.

```

---

This is more complicated than it initially appears. Every player has a FactionList, and the FactionList ReputationValue can change potentially, multiple times per second.

For the player, it is relatively simple, they have a FactionList which contains the FactionName and FactionReputation for each Faction. Clientside, they can attack anything as long as it's 5999 or below.

But for the Enemy, Serverside. they need to check the players FactionList and not only for a single player, but for potentially hundreds of players.

For ANY entity to KNOW if they can or can't attack, they first NEED to know the SPECIFIC player's FactionList ReputationValue for their Faction.

the FactionList ReputationValue is a constantly changing value which must be obtained potentially every few seconds from Each Player.

How does this check work?

When is it performed?

How often is it performed?

I'm assuming Each Faction performs this check whenever a player logs in. Adding this players value to a list.

Performing this check as part of an Aggro-radius would be insanely inefficient.

# Answer
> 1 votes
A typical mmo has even more checks compared to just the reputation. Some take your level into consideration (low level mobs ignore high lvl players). Retaliation guards if you have killed some players some time ago. Reputation. Buff effects/ Transformations.

Typically it would check on each frame (or close to it). Checks order is something along the line of

* Check if something is in my range
* Determinate what I found in my range
* Determinate if I should attack it or not

The third step would take your reputation into account. And the value is requested each time he detects him in his range - else if you farm some reputation and it is only evaluated on login, a change in reputation would not be noticed. The server simply is requesting the player data (which he has already) and compares all values for each mob that determinate if a mob is hostile. There is some optimization going on, once we found something in our range, we don't need to reevaluate it all the time or for certain encounters you might have aggro trigger zones that are fixed.

The most expensive operation is the aggro distance of the mob. Even if you just take the distance as you and the mob as criteria (on a 2D plane), you have √((xB−xA)*(xB−xA)+(yB−yA)*(yB−yA)) which is a lot more expensive than a simple value if condition check.

# Answer
> 0 votes
Performing this check can easily be implemented as a very fast and efficient operation.

* Give every player an array of integers with one entry for each faction in the game. This array represents their reputation with each faction.
* Give each mob a faction ID which is equal to the index in the reputation array of the player

Now when you have a player and a mob, finding if the mob is friendly or hostile is just two very simple operations:

1. an array index lookup
2. an integer comparison to see if the reputation for that faction is below the attack-on-sight threshold

`if (player.factionReputation[mob.factionId] < 2000)`

There are a lot of things an MMO server needs to perform every tick which are far more CPU-intense than that. And you don't even need to do this every tick, only when the mob is in the state of their behavior tree where they look for a new target to attack. And when considering potential targets to attack, then there are a lot of operations which are far more CPU-intense than just checking the faction reputation:

* Is the player in attack range?
* Is there a clear line of sight to the player?
* Is there an unobstructed path to the player?

These are the things you might want to worry about optimizing in your game.

---
Tags: multiplayer, mmo
---


title: Vector2 distance_to weird results

text:
# Question
Title: Vector2 distance_to weird results
I'm using `Vector2.distance_to` to get the distance between a MeshInstance and a KinematicBody but the results aren't as expected.

I'm using `distance_to` like so:

```
var player_global_transform = $KinematicBody.get_global_transform().origin
var player_position = Vector2(player_global_transform.x, player_global_transform.z)

# Here I loop through the planes and compare positions but to simplify it I'll just show
# the one.
var plane_global_transform = $MeshInstance.get_global_transform().origin
var plane_position = Vector2(plane_global_transform.x, plane_global_transform.z)
var player_distance_to_plane = player_position.distance_to(plane_position)

```

Also I'm using Vector2s because I don't care about Y values for this calculation.

Lets say I have 9 mesh planes (240x240) in a grid and the player is standing in the middle mesh of them:

The distance from the KinematicBody and the middle square is (0, 0) as the player is right in the middle of it. Now if I move over a square to the left:

The distance returned is (240, 0) which is expected as I'm now 1 mesh plane distance away from the center of the previous mesh. Now if I extend the grid and add 3 more meshes to the left and move over to that one:

The distance is now (360, 0) instead of (480, 0) and I can't seem to figure out why. It also seems that if I add another column of plane meshes to the left and move over another square, it's still (360, 0).

# Answer
You started with a 3x3 grid/mesh of unit 240px positioning the dot in its **center** (0,0).

Next you move the dot 1 unit (240, 0) to the left which is the center of the first column.

By adding a column to the right the **mesh center point** the mesh is now 4 units wide moving the dot half a unit (120px) relative to the new center which equals to 240px + 120px = 360px aka (-360,0)
> 0 votes

---
Tags: vector, godot, gdscript
---


title: Scene reset function not working

text:
# Question
Title: Scene reset function not working
I am entirely new to programming. Recently just watched this YouTube tutorial and follow the way the author wrote the code until (1:22:24). I'm not sure why the scene reset function for trasnform.position.y \> 10 not working for me. The compiler does not detect any error and game run as normal but the scene does not reset when the bird position on y axis more than 10. I'm using another bird object anwyay since i can't find exactly the same bird picture as author did. Also is there a way to check what the value store in each variable? Example I want to check what the value stored in "transform.position.y" to find out why it is not working.

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class GreenBird : MonoBehaviour
{
    Vector3 _initialPosition;

    private void Awake()
    {
        _initialPosition = transform.position;
    }

    void update()
    {
        if (transform.position.y > 10)
        {
            string currentSceneName = SceneManager.GetActiveScene().name;
            SceneManager.LoadScene(currentSceneName);
        }
    }

    private void OnMouseDown()
    {
        GetComponent<SpriteRenderer>().color = Color.red;
    }

    private void OnMouseUp()
    {
        GetComponent<SpriteRenderer>().color = Color.white;
        Vector2 directionToInitialPosition = _initialPosition - transform.position;
        GetComponent<Rigidbody2D>().AddForce(directionToInitialPosition * 100);
    }

    private void OnMouseDrag()
    {
        Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(newPosition.x, newPosition.y);
    }
}

```

# Answer
Your method is called update(). It should be Update(). Unity never runs it, because that upper case matters.
> 5 votes

---
Tags: unity
---


title: Colorize with a given color a texture

text:
# Question
Title: Colorize with a given color a texture
I have a texture and I want to "colorize" it with a given color, lets say cyan (`#00ffff`) or purple (`#800080`). What I want to do, is get all the pixel values from the texture, and remove the color and keep the "brightness" and "saturation" and apply to the desired color. There is a tool in GIMP to do this called Colorize (`Colors -> Colorize..` while editing), I made an example below.

This is will all be done in a shader (GLSL), although this is probably a general algorithm.

# Answer
> 7 votes
This live demo uses the algorithm described by @Dries in a fragment shader to colorize the incoming fragment color.

It basically can be summarised by:

```
vec4 getInputColor()
{
    TODO: sample from a texture / use a uniform var / varying ...
}

vec4 toGrayscale(in vec4 color)
{
  float average = (color.r + color.g + color.b) / 3.0;
  return vec4(average, average, average, 1.0);
}

vec4 colorize(in vec4 grayscale, in vec4 color)
{
    return (grayscale * color);
}

void main()
{
  // This is the color you want to apply
  // in the "colorize" step. Should ultimately be a uniform var.
  vec4 c = vec4(0.0, 1.0, 1.0, 1.0);

  // The input fragment color.
  // Can come from a texture, a varying or a constant.
  vec4 inputColor = getInputColor();

  // Convert to grayscale first:
  vec4 grayscale = toGrayscale(inputColor);

  // Then "colorize" by simply multiplying the grayscale
  // with the desired color.
  vec4 colorizedOutput = colorize(grayscale, c);

  // Done!
  gl_FragColor = colorizedOutput;
}

```

# Answer
> 2 votes
If you want it exactly like the thing above you'll first have to make your render grayscale.

You can do this in the pixel shader by taking a sample of the texture you were using (or only the color doesn't matter). Make a sum of the r, g and b value and divide that by 3. Return that value as the rgb values from the pixel shader.

Then do this (with or without the grayscale). Multiply the color of your texture (or the value of the grayscale) with the color you want.

Return that value in your pixel shader and that should be it.

# Answer
> 1 votes
If you just multiply a grayscale with a color, white will become that color instead of staying white. Instead, multiply only for gray values up to 0.5 and for brighter values, mix the color with white (the mix value will be the gray value normalized from \[0.5..1.0\] to \[0.0..1.0\]. So the mix amount would be (grayVal-0.5)\*2.0

# Answer
> 0 votes
I had this same question. The following is one of the simpler solutions I tried today while looking to colourise an image while cleanly preserving black and white values. It has complications and limitations to be sure (see discussion below), but it should be pretty usable.

If you're ok with the additional computations of HSL conversion, skip my hacky RGB approach and just check out this article on Photoshop blending modes; the GIMP equivalent you're looking for is Photoshop's "Color" mode.

If you want something a little more minimal (no colour mode conversions), hopefully this helps...

**Steps:**

1. Convert input image values to greyscale using perceptual brightness
2. Find the average value of the desired colour and use this to centre the RGB values
3. Modulate (in the artistic sense) the original input values using mathematical power

This method behaves reasonably well with the full range of colour input values, including black or white (mix/lerp methods do not). It also retains the brightness of the original image pretty successfully (multiplication methods do not). It is *not* particularly successful with high-saturation-low-value colours (like a saturated navy blue), since the RGB nature of the computations result in less saturated output. I've arbitrarily boosted saturation in the code example on ShaderToy, which of course has its own downsides (burning and hue shifts can result at higher levels). But this is all pretty simple, and hopefully fairly fast due to not relying on HSL/HSV conversions.

If you know your RGB input values will always be within a known brightness range, a mix/lerp solution might be more accurate and reliable. I needed something that was a little more flexible (if not strictly accurate for hue/saturation), so came up with this.

**Pseudo-code:**

```
float3 image = // input image values
float imageGrey = image.r * 0.3 + image.g * 0.7 + image.b * 0.1; // roughly perceptual greyscale conversion

float3 color = // input colour values
float colorAverage = (color.r+color.g+color.b)*0.3334; // mid-point of the float3
float3 colorPow = 1.0+colorAverage-color; // centre at 1.0 and invert the colour values

return pow(imageGrey, colorPow);

```

**Real example:**

https://www.shadertoy.com/view/wsVyRG

**References:** (for the perceptual greyscale conversion)

https://gist.github.com/Volcanoscar/4a9500d240497d3c0228f663593d167a https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/

---
Tags: glsl, color
---


# Question
Title: Why don't ShaderToy shaders work with LibGDX?
Can someone tell me what is different about the shader implementation in LibGDX that makes it incompatible with the shaders from ShaderToy? It looks like you can use ShaderToy shaders directly with other frameworks so am wondering what the difference is.

People talk about converting shadertoy shaders from GLSL to HLSL for use with Unity or Monogame, but as far as I know LibGDX uses GLSL so I don't see why the code is different?

# Answer
> 0 votes
LibGDX support GLSL shaders. GLSL is an standard language… ShaderToy scripts, while based in GLSL are not standard.

> It looks like you can use ShaderToy scripts directly with other frameworks so am wondering what the difference is.

What do you mean directly? I have seen plugins for a couple engine that will allow you to paste ShaderToy scripts and use them as materials. Not what I would call "directly", but it works most of the time. People also convert ShaderToy scripts to GLSL by hand.

It is worth noting that ShaderToy scripts closely resemble fragment shaders, and - unless the ShaderToy script uses some other features, such as input or sound - it takes little work to adapt them by hand to GLSL fragment shaders. If the script uses such features… well, though luck, because shaders are programs uploaded to the GPU, and thus are unable to take user input or play sound. Which means that a complete implementation of a ShaderToy script runtime in another engine is not a trivial task.

What work does it take to adapt it? As per the fragment shader, first ShaderToy has some built-in variables that you would have to pass as uniforms. And second you need to write a `main` function that calls the `mainImage` function from ShaderToy (or just paste the code from `mainImage` inside `main`). *If you want an output equal to the one you get in ShaderToy you will also have to setup an scene with a single quad that covers the view, and has the appropriate UV coordinates.*

I want to make empahsis on that ShaderToy scripts are not standard. The function `mainImage` is not standard. On the other hand, `main` is part of the GLSL standard.

These are the input uniforms according to the ShaderToy documentation:

```
uniform vec3 iResolution;
uniform float iTime;
uniform float iTimeDelta;
uniform float iFrame;
uniform float iChannelTime[4];
uniform vec4 iMouse;
uniform vec4 iDate;
uniform float iSampleRate;
uniform vec3 iChannelResolution[4];
uniform samplerXX iChanneli;

```

You can see you will have to pass stuff like the current time and the position of the mouse. That means you also need a script that is updating these uniforms before doing the render call. For LibGDX in particular, you would do that inside `render`. You can imagine, from there, how to go about making a ShaderToy clone in LibGDX. *If you are trying to do this as a shorthand to implement your game, you probably should simply implement your game instead.*

However, chances are, you want to use the ShaderToy scripts as a material. That is, you would be rendering a scene, as you would normally do, and the ShaderToy scripts defines how to shade a surface. That means that you would create your GLSL fragment shader based on your ShaderToy script, then when rendering the mesh that uses it, you would set the uniforms and call render on the mesh. And at that point, it makes much more sense to implement only what you need instead of cloning all ShaderToy functionality, and it would be much more efficient.

To reiterate, ShaderToy is based on GLSL. Thus, if you can use ShaderToy, you got a head start in GLSL. However do not let ShaderToy prevent you from learning GLSL.

---
Tags: libgdx, shaders
---


# Question
Title: Why is my object not destroyed when the HP is reduced?
I tried to write a script that declares an object to have hp 90 initially and every time you click on the object, it turns red and will reduce the hp by 10. When the hp is lower than 10, it should destroy the object.

But when I click my object 10 times, it still is not destroyed. How can I fix this code?

```
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    public void OnMouseDown()
    {
        GetComponent<SpriteRenderer>().color = Color.red;
        var hp = 90;
        _ = hp - 10;

        if(hp < 10)
        {
            Destroy(gameObject);
        }
    }
}

```

# Answer
Everytime you click, you reset back your hp to 90. Consider setting a current hp var at the start and just reduce it every click.

```
public int maxHp = 90;
private int currentHp;

void Start()
{
    currentHp = maxHp
}

void OnMouseDown()
{
    GetComponent<SpriteRenderer>().color = Color.red;
    currentHp -= 10;
    if(currentHp < 10)
    {
        Destroy(gameObject);
    }
}

```

You can set your max hp via the editor or just set it directly.
> 2 votes

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


# Question
Title: Using a mesh stencil with 2D lighting in the Universal Render Pipeline
I've followed the CodeMonkey tutorial on using a dynamic mesh as a stencil for a field of view or visibility polygon effect, and have got it working using the latest version of Unity and its Universal Render Pipeline (I believe this uses a Forward Renderer).

I'd like to use the 2D lighting and this requires a 2D Renderer, which I have also got working.

Unfortunately I can't figure out a way of combining these. I've got a Universal RenderPipeline and added my 2D Renderer and the Forward Renderer to the renderer list, but it only allows one of these to work (I'd assumed it would trigger in order).

How can I get both of these effects working together, or if it isn't possible, is there a recommended approach for combining 2D lighting and stencil masking?

# Answer
Figured out a workaround.

For the FOV custom mesh I had to use a new shader that just wrote to the stencil buffer. I found https://gist.github.com/ewandennis/ff0f12da482a0aff55486290c00c5e9e that does this. I set it to write the value 1 to the buffer.

I then had to create a duplicate shader to the lit sprite one that Unity provides now (not sure whether it's OK to post this so I'll err on the side of caution and not do so).

I added the following at the top of each of the three Pass sections:

```
            Stencil
            {
                   Ref 1               // use 1 as the value to check against
                   Comp equal       // write this pixel if equal to 1.
            }

```

I switched the sprites' material to point to this shader and everything was now clipped to the FOV mesh.
> 1 votes

---
Tags: unity, lighting, graphic-effects, stencil
---


# Question
Title: How do I calculate to and from a Non-Linear Acceleration?
I am looking at non-linear accelerations using the following values:

* initial\_acceleration
* time\_to\_max\_velocity
* max\_velocity
* current\_velocity

Initial\_acceleration is the per frame acceleration we start with from 0 velocity. Over the course of "time\_to\_max," the acceleration is supposed to follow an interpolation from this value to whatever it needs to be to be to hit max\_velocity at the end of this time. I need code both to generate the velocity generated by this function at a given point in time, and code for an inverse function that gives me the time given a current velocity.

It sounds like what I want is a type of quadratic interpolation or spline, but I have been unable to work out the details. Above I've graphed some values:

* Red shows the case where: initial\_acceleration * time\_to\_max == max\_velocity
* Green shows the case where: initial\_acceleration * time\_to\_max \> max\_velocity
* Blue shows the case where: initial\_acceleration * time\_to\_max \< max\_velocity

The speed curves I've tried in code chaining lerp operations together always end up doing weird things like curving over my max speed and then back down to max speed again. If anyone can supply code, or math, that could get me even halfway towards an answer, I would be very appreciative.

# Answer
> 0 votes
Let's say we want our acceleration to be an affine function of time, meaning we have a constant jerk. That makes our velocity vs time graph take the form of a parabola, with its directrix parallel to the time axis.

The general equation for such a curve is:

$$v(t) = a \cdot t^2 + b \cdot t + c$$

Since your parabola goes through the point \\$(t, v(t)) = (0, 0)\\$, we can conclude that \\$c = 0\\$.

Next, the derivative of this equation is:

$$\frac {d v(t)} {d t} = 2 a \cdot t + b$$

So if you want the initial acceleration to be \\$a\_0\\$ then we can conclude \\$b = a\_0\\$

Then if we want \\$v(T\_{max}) = v\_{max}\\$, we can solve for \\$a\\$:

$$\begin{align} v\_{max} &= a \cdot T\_{max}^2 + a\_0 \cdot T\_{max}\\ v\_{max} - a\_0 \cdot T\_{max} &= a \cdot T\_{max}^2\\ \frac {v\_{max}} {T\_{max}^2} - \frac {a\_0} {T\_{max}} &= a \end{align}$$

So we end up with the equation for speed:

$$v(t) = \left( \frac {v\_{max}} {T\_{max}^2} - \frac {a\_0} {T\_{max}} \right) \cdot t^2 + a\_0 \cdot t$$

...which you can solve for \\$t\\$ using the quadratic formula (taking the positive root):

$$t = \frac {-a\_0 + \sqrt{a\_0^2 + 4 v \left( \frac {v\_{max}} {T\_{max}^2} - \frac {a\_0} {T\_{max}} \right) }} {2 \left( \frac {v\_{max}} {T\_{max}^2} - \frac {a\_0} {T\_{max}} \right) }$$

Note that with this construction, you need to keep \\$a\_0 \cdot T\_{max} \<= 2 v\_{max}\\$ if you want the velocity function to be non-decreasing over the interval \\$t \in \[0, T\_{max}\]\\$. If your initial acceleration is too steep or your time horizon is too short, your velocity will have to exceed your max, then slow down again to hit your target. If you need curves in this range, then we'll need to fall back on a different class of function with a more aggressive braking behaviour than the constant jerk we use here.

---

Here's another approach that works better for higher values of the initial acceleration, based on a kind of hyperbolic function:

$$x = \frac t {T\_{max}}\\ v(t) = v\_{max}\cdot x \cdot \frac {k + 1} {x + k}$$

Where

$$k = \frac 1 {T\_{max} \frac {a\_0} {v\_{max}} - 1}$$

This one can handle arbitrarily high values of \\$a\_0\\$, but it blows up for the constant acceleration case \\$a\_0 = \frac {v\_{max}} {T\_{max}}\\$, so you'd need to special-case values in that vicinity. It also tends to make a sharper "corner" than the quadratic approach I showed first:

(Quadratic / constant jerk curve in blue, new hyperbolic function in orange)

The hyperbolic function is reasonably straightforward to invert too:

$$vx + vk = v\_{max} x k + v\_{max}x\\ vk = x \left(v\_{max}(k + 1) - v\right)\\ x = \frac {vk} {v\_{max}(k + 1) - v}\\ t = T\_{max}\cdot x =T\_{max}\frac {vk} {v\_{max}(k + 1) - v}$$

---
Tags: physics, mathematics, interpolation
---


# Question
Title: Unity, interior poly always missing in clothing
I've modeled interior polygons but for some reason they do not show up in Unity. I've tried changing import settings for normals to both calculate and import... How do you have a tshirt's interior poly show up?

# Answer
> 1 votes
Most likely the normals must be flipped on those polygons. At any rate, unless you really need a second layer of polygons for some reason that I can't grasp from your post, you don't need them: a single layer is enough, just use a two-sided shader for it.

To enable two-sided rendering change to render face both on your material:

---
Tags: unity, mesh, 3dsmax, import
---


# Question
Title: Camera animation stutters on first launch
The camera stutter for a fraction of a second when animating a camera from one position to another position. This issue only happens when the game is launched for the first time after installation. The camera animation is smooth for further game launches.

I am using **LeanTween** to animate the camera. No data is loaded while the camera is animating.

**Environment**:

Unity version: 2019.3.03f

Mobile platform: iOS

iOS versions: 12 and above

**More information:**

The assets are being initialized and loaded on the first screen. I have a module to initialize all the assets before the camera starts panning. I also seeing stutters on the first installation for certain 3D objects animation; these objects are also loaded on the first screen. I don’t know what else to improve with the initialization.

Since we can’t run Unity’s profiler on real devices, I ran the profiler on Unity’s editor and looked at the call stacks at the points where you see the spikes. Below is the screenshot of the call stack of a spike during a specific animation stutter:

I made the following changes:

1. Instead of LeanTween, I used my own code for camera animation
2. Disabled all UI animations
3. Disabled analytics solutions
4. Disabled the camera’s occlusion culling property
5. Camera animation using Unity Timeline

However, these changes did not affect the stutters.

Also, I am not seeing the stutters in the editor but they are clearly visible on a device. I can’t profile the game on a device using Xcode since it is not using native code.

I ran the same code on a few Android devices and I am not seeing the stutters there.

I would appreciate any suggestions and thoughts on this topic. Thank you.

**Code structure:**

My game has three screens (A, B, and C). All the mesh files, materials, and game objects present on screens B and C are initialized and set to be active from the start of the game; in other words, everything is loaded on screen A before the animation to screen B begins. Occlusion culling is on for the camera.

The camera stays on screen A for 3 seconds and then animates to screen B. After the user performs a certain action on screen B, the camera animates to screen C.

The stutters happen when the camera is halfway between screens A to B and halfway between screens B to C.

# Answer
> 0 votes
LeanTween is not something I use since we can animate the camera without any third-party tool using Unity Timeline. My suggestion is to add a half-second delay to that first animation to solve it. Anyhow, the best approach would be to move to Unity Timeline.

---
Tags: unity, camera, performance, optimization
---


# Question
Title: Is using events a good way to have the option to return out of a method or alter its normal execution?
Let's say I have a script that calls a method frequently, and when doing so wants to allow other objects to know about it and potentially alter what happens in that method. This is fairly simple to do using C# events:

```
public class PassByReference
{
    public bool foo;

    public PassByReference(bool foo)
    {
        this.foo = foo;
    }
}

public class Example : MonoBehaviour
{
    public event Action<PassByReference> OnSomethingHappened;

    private void DoSomething()
    {
        var returnOut = false;

        // Do some stuff

        var passByReference = new PassByReference(returnOut);
        OnSomethingHappened?.Invoke(passByReference); // Some other object can read and alter this

        if (passByReference.foo)
            return;

       // Do some more stuff
    }
}

```

Is this a good way to do things if one anticipates that, based on a combination of the information given by the event, and their own properties, other objects may want to stop the second half of the `Example` method from running (or maybe alter what happens)? I guess what I'm trying to do is prevent the `Example` class from having to store references to many other classes that will interact with it only occasionally, and clog up the method with many `if` statements. My main concern, though, is that frequently creating new classes to pass data via reference in the event(s) can lead to performance issues, especially if many objects in my game are using the `Example` script.

# Answer
If I interpret this example correctly, then you have a situation where you have a game object which is supposed to do "something" unless there is a reason why it can not do "something" right now, and there is a large number of potential reasons for that with different grades of obscurity which depend on various other gameObjects.

In this case, it might be an option to invert the responsibility. Instead of having the object check all possible reasons why it might be unable to do something, have the *other* objects tell it that it can not do something for some reason.

```
public class Shooting : MonoBehaviour
{

    private bool canShootThisUpdate;
    private bool canShootThisFixedUpdate;

    public void SuppressShooting() {
       canShootThisUpdate = false;
       canShootThisFixedUpdate = false;
    }

    private void Update()
    {
         if(Input.GetButton("Fire") &&
            canShootThisUpdate &&
            canShootThisFixedUpdate) {
             Debug.Log("Pew! Pew! Pew!");
         }
         canShootThisUpdate = true;
    }

    private void FixedUpdate()
    {
         canShootThisFixedUpdate = true;
    }
}

```

This code will make the object shoot unless at least one other gameObject called the `SuppressShooting()` method during the last update / fixed update.

So any object which wants to stop this gameObject from shooting, just needs to do so. Like for example a "no shooting zone":

```
public class NoShootingZone : MonoBehaviour {

   void OnTriggerStay(Collider other) {
        Shooting shooting = other.GetComponent<Shooting>();
        if (shooting) {
             shooting.SuppressShooting();
        }
   }
}

```

or a "weapon cooldown" behavior which is actually on the same gameObject:

```
[RequireComponent(typeof(Shooting))]
public class WeaponCooldown : MonoBehaviour {

   public float cooldownTime;

   void Update() {
        cooldownTime -= Time.deltaTime;
        if (cooldownTime > 0) {
             GetComponent<Shooting>().SuppressShooting()
        }
   }
}

```

Note that for this to work reliable, the execution order of the Shooting script must be before any script which calls SuppressShooting from FixedUpdate, OnCollision\* events or OnTrigger\* events. Otherwise the suppression effect will fail when there are two Updates without a FixedUpdate between them. If you don't like scripts being reliant on execution order (which I can totally understand) you could also go for an alternative architecture where other objects suppress shooting not for a single update but for a specific amount of time. This might also be more performance-friendly if you have many such timed effects:

```
public class Shooting : MonoBehaviour
{

    private float suppressionTime;

    public void SuppressShooting(float time) {
       if (suppressionTime < time) suppressionTime = time;
    }

    private void Update()
    {
         if(Input.GetButton("Fire") &&
            suppressionTime <= 0f) {
             Debug.Log("Pew! Pew! Pew!");
         }
         suppressionTime -= Time.deltaTime;
    }
}

```

If you want to suppress shooting at least until the next Update, pass `float.Epsilon`. If you want to suppress shooting at least until the next FixedUpdate, pass `Time.fixedDeltaTime`.
> 1 votes

# Answer
Event-Driven Design (EED) is a good pattern widely used in the game industry, so yes, that is totally the good and standard approach. How to implement it is entirely your choice. You can do it using Unity Event System, you can do it in pure C# or a mix of the two.

Personally, I always mix EED with a Finite State Machine (FSM) approach to tackle the cases where incompatible events are triggered, but it's just my personal view about EED implementation: you can do it in a stateless way, but it will be more complex to test and fix unwanted behaviours.
> 1 votes

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


# Question
Title: What are the dangers of setting rigidbody velocity directly for movement and what are the alternatives
I'm playing around with Unity, trying to make a neat 3rd person platformer movement system using rigidbodies so that I may in the future implement things like pushing boxes/physics objects, grappling hooks, etc... as well as I'm not really knowledgeable in terms of math and physics to be able to code them from scratch using `CharacterController`

What I've done is I've implemented some basic movement by setting velocity directly

```
Vector2 input = GetInput();
bool hasInput = Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon;
bool isDashing = dashCounter > 0f;
if (hasInput && !isDashing)
{
    Vector3 direction = GetDirection(); // get camera direction scaled by forward & right vectors
    transform.localRotation = Quaternion.LookRotation(direction);

    UpdateTargetSpeed(input); // update target speed based on movement direction
    Vector3 movementVector = new Vector3(input.x * TargetSpeed, 0f, input.y * TargetSpeed); // add speed to input vector
    movementVector = transform.localRotation * movementVector; // rotate the vector to where the character is facing
    movementVector = Vector3.ClampMagnitude(movementVector, TargetSpeed); // clamp magnitude to avoid faster speed on diagonals

    body.velocity = new Vector3(movementVector.x, Velocity.y, movementVector.z);
}

```

And I'm also projecting velocity on ground normal for slopes so that the character doesn't fly off when moving down slopes

```
if (wasPreviouslyGrounded && !jumping && groundCheck.CanStick)
{
    float slopeAngle = Mathf.Abs(Vector3.Angle(groundCheck.StickyContactNormal, Vector3.up));
    if (slopeAngle < 85f)
    {
        body.velocity = Vector3.ProjectOnPlane(Velocity, groundCheck.StickyContactNormal);
    }
}

```

I have implemented jumping and dashing using `AddForce`

```
body.AddForce(0f, movementSettings.JumpForce, 0f, ForceMode.Impulse);

```

This all works okay but everywhere I looked people are always claiming that setting velocity directly is a bad practice and should be avoided. I've seen suggestions to use `AddForce` instead, but I haven't been able to get the same movement with it, no matter which force mode I used. I am also lost on how to control the amount of force I'm giving to the body during continuous movement. The thing I did is to check the magnitude of body's current velocity and if it's at or above the target speed then forgo applying the force but that just makes the body continuously accelerate and decelerate giving off jittery movement

```
if (body.velocity.sqrMagnitude < TargetSpeed * TargetSpeed)
{
    body.AddForce(force, ForceMode.VelocityChange);
}

```

Can anyone ELI5 me the answers to the following questions:

1. Why exactly is setting velocity directly a "bad practice"?
2. What is the preferred alternative?
3. How can I get snappy and responsive movement without setting the velocity directly?
4. How can I accomplish sticking to the ground when going down slopes without projecting and setting the velocity directly?

# Answer
When you set the velocity of your rigidbody directly, then:

* It will (obviously) cancel all other forces acting on the rigidbody. So you lose the option to use any force-based effects at all on this object. That means no knockback, no explosions, no wind... (unless you program the low-level physics for those yourself)
* When there are other non-kinematic non-static rigidbodies blocking the object's path, then the physics engine will give it as much force as it needs to push them away without slowing down. Applying potentially unlimited forces in rigidbody-collisions can cause potentially unlimited physics glitches. You might witness "fun" game mechanics like rigibodies getting launched into orbit or getting pushed through solid walls.

So unless you want no actual rigidbody physics at all in your game, always move objects by using `AddForce`.

When you have the problem that your object acts as if it's sliding on ice (not snappy and responsive), then crank up the "Drag" setting of the rigidbody. It will result in a shorter acceleration and deceleration and also put a limit on how fast it can get. But you will also need more force to achieve the same speed.
> 2 votes

---
Tags: unity, physics, 3d, movement, rigidbody
---


# Question
Title: Divide two quaternions evenly by a scalar to get a smooth rotation in-between
How do you divide two quaternions - say `A` and `B` \- evenly by a scalar, to calculate the rotations between them to render a smoother rotation?

> Effectively, say you want to smooth the rotations between `A` and `B` evenly by `n`. How do you calculate each quaternion value between A and B?

I have found that resorting to `.eulerAngles` leads to some wild gimbal locking, so I think the math needs to stay in quaternion space...

# Answer
> 1 votes
It sounds like you're describing `Quaternion.Slerp`. You can use this to generate quaternion at any particular fraction of the rotation between a start and an end quaternion:

```
IEnumerator<Quaternion> RotationSteps(Quaternion from, Quaternion to, int stepCount) {

    yield return from;

    for(int i = 1; i < stepCount; i++) {
        yield return Quaternion.Slerp(
                        from,
                        to,
                        i / (float)stepCount
                     );
    }

    yield return to;
}

```

Or you can compute the incremental rotation of a single step like so:

```
Quaternion travel = to * Quaternion.Inverse(from);

Quaternion step = Quaternion.Slerp(
                      Quaternion.identity,
                      travel,
                      1f / stepCount
                  );

```

---
Tags: unity, quaternion
---


# Question
Title: How do I keep vertex position when changing material?
I've created 2 shaders using shader graph which I'm applying to a sphere to simulate a ball of water/ice. The water shader distorts the shape of the sphere over time to look like it's flowing a bit. What I would like to do is swap the shader from water to ice, and keep the shape of the distorted sphere when the materials swap over.

I'm pretty new to unity and shaders in general so I don't know where to start.

# Answer
> 2 votes
You'll need to do one of two things:

1. (easiest) Copy the code that distorts the vertices over time from the water shader to the ice shader.

Replace any reference to a "time" variable in that code with a reference to a new shader parameter that you set to the current time value at the moment you do the material swap. That will effectively lock the waves in their state from that frame, until you modify that parameter.

(You could even drive that parameter in slow-mo for a couple frames, if you want it to look like the waves gradually freezing in place, rather than a hard stop)
2. (harder) Copy the code that distorts the vertices over time from the water shader, and implement it in a C# script.

At the moment you swap the materials, create a copy of the mesh, and use your C# script to change the vertices of the copy to match the output of the water vertex shader. Then upload that mesh data to the GPU, and swap your object to use this modified mesh instead of the original.

Now your ice shader can keep its usual vertex shader logic, because you've baked the frozen waves into the mesh it's acting on.

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


# Question
Title: How do i set conditions for an IF statement as the game progress through "difficulty"?
This is code that I wanted to put in my IF statement

```
    public GameObject fallingRockPrefab;
public Vector2 spawnsMinMax;
float randX;
float randY;

//Spawn Positions
Vector2 SpawnPosition;
float nextSpawnTime;

void Update()
{
    if (Time.time > nextSpawnTime)
    {
        float SpawningInBetween = Mathf.Lerp(spawnsMinMax.y, spawnsMinMax.x, Difficulty.GetDifficultyPercent());
        print(SpawningInBetween);
        nextSpawnTime = Time.time + SpawningInBetween;

        randX = Random.Range(-5.6f, 5.6f);
        randY = 5.57f;
        SpawnPosition = new Vector2(randX, randY);
        Instantiate(fallingRockPrefab, SpawnPosition, Quaternion.identity);

    }

}

```

This is the code from my "Difficulty.GetDifficultyPercent"

```
    public static class Difficulty{
static float secondsToMaxDifficulty = 30;

public static float GetDifficultyPercent()
{
    return Mathf.Clamp01(Time.timeSinceLevelLoad / secondsToMaxDifficulty);
}}

```

I'm planning to make a certain event happen when my game bypass a certain stage of a difficulty as it progress but I just don't know what to put it as.

My guess is this,

if(Time.time \> Difficulty(25))

but didn't work.

# Answer
> 0 votes
Try this:

```
if(GetDifficultyPercent() > .25f)

```

As wondra pointed out, you cannot call a class directly in C#, and this method returns a value 0..1.

If you want to be able to call this method with a time parameter, you will need to update your method to something like this:

```
public static class Difficulty{
   static float secondsToMaxDifficulty = 30;
   public static float GetDifficultyPercent(float time)
   {
       return Mathf.Clamp01(time / secondsToMaxDifficulty);
   }
}

```

and call it like this:

`if(GetDifficultyPercent(Time.time) > .25f)`

Bear in mind that Time.time returns the amount of time that the application has been running. So once you add the functionality to restart the game, or add in a pause function, or a main menu, you will have to rework your difficulty timer.

# Answer
> 0 votes
It looks like your approach should more or less work. It seems like there are probably two different situations where you will need to consider difficulty in your game.

1.) Increase/Decrease probability with regards to difficulty.

```
private IEnumerator SpawnFallingRockRoutine()
{
    while (playing)
    {
        float spawnCooldown = Mathf.Lerp(minSpawnRate, maxSpawnRate, Difficulty.GetCurrentDifficulty());
        // spawn falling rock logic
        yield return new WaitForSeconds(spawnCooldown);
    }
}

```

2.) Trigger events only if at a certain difficulty.

```
private IEnumerator EvilMonkeySpawnRoutine()
{
    while (playing)
    {
        float cooldown = 1.0f;
        if (Difficulty.GetCurrentDifficulty() >= evilMonkeyDifficulty)
        {
            // spawn evil monkey
            cooldown = evilMonkeyCooldown;
        }

        yield return cooldown;
     }
}

```

You may also want to change how your Difficulty class works to make it a bit more extendable in your project:

```
public class Difficulty
{
    private static float maxDifficultyTime = 30.0f;
    private static float gameStartTime = 0.0f;
    private static float difficultyIncreaseRate = 1.0f;
    private static float difficultyBump = 0.0f;

    public static void SetStartTime(float time)
    {
        gameStartTime = time;
    }

    // Use if you want to make the game temporarily harder
    public static void BumpUpDifficulty(float increase)
    {
        difficultyBump += increase;
    }

    // Use if you want to make the game temporarily easier
    public static void BumpDownDifficulty(float decrease)
    {
        difficultyBump -= decrease;
    }

    // Gets current difficulty in range of 0.0 - 1.0
    public static float GetCurrentDifficulty()
    {
        return Mathf.Clamp01(GetCurrentDifficultyUnclamped());
    }

    // Get current difficulty in range of min - max
    public static float GetCurrentDifficultyClamped(float minDifficulty, float maxDifficulty)
    {
        return Mathf.Clamp(GetCurrentDifficultyUnclamped(), minDifficulty, maxDifficulty);
    }

    // Gets the raw current difficulty (careful with this one)
    public static float GetCurrentDifficultyUnclamped()
    {
        return difficultyBump + (Time.time - gameStartTime) * (difficultyIncreaseRate / maxDifficultyStartTime);
    }
}

```

---
Tags: c#
---


# Question
Title: How to expand the limit of screen mouse access for FPS side rotation
I started coding in Godot and i have a working FPS controller but the problem is that when i move my mouse sideways , it cannot move my sight beyinid that side of my screen , in other words the movement of my charecter is limited by the size of my screen , how to prevent this

Rotation code

```
func _input(event):
if event is InputEventMouseMotion:
    head.rotate_y(deg2rad(event.relative.x * -mouseSensitivity))
    camera.rotate_x(deg2rad(event.relative.y * -mouseSensitivity))

```

# Answer
That you want is to capture the mouse pointer.

Call `input.set_mouse_mode` it takes as parameter a `MouseMode`.

Copied from the linked documentation:

> enum MouseMode:

> **MOUSE\_MODE\_VISIBLE = 0** --- Makes the mouse cursor visible if it is hidden. **MOUSE\_MODE\_HIDDEN = 1** --- Makes the mouse cursor hidden if it is visible. **MOUSE\_MODE\_CAPTURED = 2** --- Captures the mouse. The mouse will be hidden and its position locked at the center of the screen.
>
> Note: If you want to process the mouse's movement in this mode, you need to use InputEventMouseMotion.relative.
>
> **MOUSE\_MODE\_CONFINED = 3** --- Makes the mouse cursor visible but confines it to the game window.

`MOUSE_MODE_VISIBLE` and `MOUSE_MODE_HIDDEN` let the mouse pointer, visible or hidden. `MOUSE_MODE_CONFINED` limits the movement of the mouse pointer to the window, that means it gets stuck at the edge, and we do not want that. However, with `MOUSE_MODE_CAPTURED` it will register relative movement, but the mouse pointer remains at the center (which also means that anything that relies on the position of the pointer won't work).

Example:

```
func _ready():
    Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED);

```

With the mouse pointer captured, your camera script should work.

---

And you encounter a couple problems:

1. You can't use the mouse to close the game window.
2. Any UI won't work.

That means you are going to need a way to change the `MouseMode` to `MOUSE_MODE_VISIBLE`. You could, for example use an input action:

```
func _input(event):
    if event.is_action_pressed("ui_cancel"):
        Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE);

```

You can imagine that would also include code that open the in-game menu with the option to close the game among other things (e.g. set the mouse sensitivity). *Or if the game is windowed, you can just close the window.* Then, when the menu is closed, you would then set `MOUSE_MODE_CAPTURED` again for the camera to continue to work.

---

You probably want to pause the game while the menu is open. You can use `get_tree().paused = true;` for that. \*Set to `false` to un-pause, of course. Remember to set the pause\_mode of your nodes appropriately. You may also be interested in using `Engine.time_scale = 0.0;` (which would also stop animated shaders).

---

On the flip side, if you don't have a menu to show at all, you probably want to recapture the mouse when the user clicks on the window. In that case, handle the click input as you normally would, and check `Input.get_mouse_mode() == Input.MOUSE_MODE_VISIBLE`, if that is the case, capture the mouse pointer. You may want to call `get_tree().set_input_as_handled()` if you want to avoid that click event being handled by some other script afterwards.

---

I suppose there is another way to go about this, and that is to move the mouse pointer.

To do that, you can call `get_viewport().warp_mouse(Vector2 to_position)` or `Input.warp_mouse_position(Vector2 to)`. *In my tests these do the same thing.*

These would also trigger an input event. They are different in that`event.relative` will be `(0, 0)` for these events. Which is not much trouble for you.

With that, I present to you, poor man's mouse capture:

```
func _process(_delta):
    var viewport = get_viewport();
    viewport.warp_mouse(viewport.size * 0.5);

```

You probably want to set a variable to decide if you want to capture or not, and set an input action to change it… Yeah, the stuff I explained above. I'd recommend do it with `set_mouse_mode`, however, many recommend to write your own code to keep the mouse pointer centered (a solution for game development frameworks that do not have this built in) that probably people would suggest it if I don't mention it. *It may also lead people searching for "how to return the mouse to the center of the screen in Godot?" to `set_mouse_mode`, which is what they probably need.*
> 0 votes

---
Tags: rotation, godot, screen
---