# Question
Title: Why are my textures not displaying propely in my raycasting engine?
I have been working on a simple raycasting engine (like wolfenstein 3d) using the SFML Graphical Library. For the most part, my raycasting works fine, I based it off of Lodev's example and made some minor changes.

The problems I am having include:

1. The Final Column of a Texture being drawn multiple times
2. Parts of textures not being drawn because they stretch past there tile

Thanks you for your time, and thanks in advance to anyone who can help!

Image Depicting the issues:  As you can see the blue bricks on the left stop drawing before the edge of the shape and just repeat the last line, and the second eagle simply draws around half of the texture.

Here is my Code:

```
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <stdlib.h>
#include <math.h>

#include <iostream>
#include <sstream>

#define mapWidth 23
#define mapHeight 7
#define texWidth 64
#define texHeight 64

std::string ConvertToString(int number) {
    std::ostringstream buff;
    buff << number;
    return buff.str();
}

int worldMap[mapHeight][mapWidth] =
{
    { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 },
    { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 },
    { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 },
    { 1,0,1,0,0,2,0,0,3,0,0,4,0,0,3,0,0,2,0,0,1,0,1 },
    { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 },
    { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 },
    { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }
};

int hitCount[mapHeight][mapWidth] =
{
    { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
    { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
    { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
    { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
    { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
    { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
    { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
};
int main()
{
//initialize textures
int column = 1;

sf::Texture bluestone;
bluestone.loadFromFile("bluestone.png");

sf::Texture eagle;
eagle.loadFromFile("eagle.png");

sf::Texture greystone;
greystone.loadFromFile("greystone.png");

sf::Texture redbrick;
redbrick.loadFromFile("redbrick.png");

sf::Texture mossystone;
mossystone.loadFromFile("mossy.png");

sf::Sprite WallTexture;

int LastMapX = -1, LastMapY = -1;
int LastSide = -1;
int Repeats = 0;

int w = 1024, h = 576;
float scaleY;
int scaleX;
float textureSectionX;

double posX = 2, posY = 2;  //x and y start position
double dirX = -1, dirY = 0; //initial direction vector
double planeX = 0, planeY = 0.66; //the 2d raycaster version of camera plane

double time = 0; //time of current frame
double oldTime = 0; //time of previous frame

                    // Create the main window
sf::RenderWindow window(sf::VideoMode(w, h), "SFML window");

window.setFramerateLimit(60);
sf::Clock clock = sf::Clock();
sf::Time fps;

// Start the game loop
while (window.isOpen()) {
    // Process events
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window: exit
        if (event.type == sf::Event::Closed)
            window.close();

        // Escape key: exit
        if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
            window.close();
    }

    window.clear();
    //ceiling and floor
    sf::RectangleShape floor(sf::Vector2f(1024, 288));
    sf::RectangleShape ceiling(sf::Vector2f(1024, 288));
    floor.setPosition(0, 288);
    floor.setFillColor(sf::Color(96, 96, 96));
    ceiling.setPosition(0, 0);
    ceiling.setFillColor(sf::Color(50, 50, 50));

    window.draw(floor);
    window.draw(ceiling);
    ///////////////////////COUNTING HITS PER SECTOR//////////////////////////////////////////////////////////
    for (int i = 0; i < mapHeight; i++)
    {
        for (int j = 0; j < mapWidth; j++)
        {
            hitCount[i][j] = 0;
        }
    }

    for (float x = 0; x < w; x++)
    {
        //calculate ray position and direction
        double cameraX = 2 * x / double(w) - 1; //x-coordinate in camera space
        double rayPosX = posX;
        double rayPosY = posY;
        double rayDirX = dirX + planeX * cameraX;
        double rayDirY = dirY + planeY * cameraX;

        //which box of the map we're in
        int mapX = int(rayPosX);
        int mapY = int(rayPosY);

        //length of ray from current position to next x or y-side
        double sideDistX;
        double sideDistY;

        //length of ray from one x or y-side to next x or y-side
        double deltaDistX = sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX));
        double deltaDistY = sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY));
        double perpWallDist;

        //what direction to step in x or y-direction (either +1 or -1)
        int stepX;
        int stepY;

        int hit = 0; //was there a wall hit?
        int side; //was a NS or a EW wall hit?

                  //calculate step and initial sideDist
        if (rayDirX < 0)
        {
            stepX = -1;
            sideDistX = (rayPosX - mapX) * deltaDistX;
        }
        else
        {
            stepX = 1;
            sideDistX = (mapX + 1.0 - rayPosX) * deltaDistX;
        }
        if (rayDirY < 0)
        {
            stepY = -1;
            sideDistY = (rayPosY - mapY) * deltaDistY;
        }
        else
        {
            stepY = 1;
            sideDistY = (mapY + 1.0 - rayPosY) * deltaDistY;
        }

        //perform DDA
        while (hit == 0)
        {
            //jump to next map square, OR in x-direction, OR in y-direction
            if (sideDistX < sideDistY)
            {
                sideDistX += deltaDistX;
                mapX += stepX;
                side = 0;
            }
            else
            {
                sideDistY += deltaDistY;
                mapY += stepY;
                side = 1;
            }
            //Check if ray has hit a wall
            if (worldMap[mapX][mapY] > 0)
            {
                hitCount[mapX][mapY]++;
                hit = 1;
            }

        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////

    ///////////////////////RAYCASTING FOR TEXTURES AND Y SCALE + DRAWING ////////////////////////////////////
    for (float x = 0; x < w; x++)
    {
        //calculate ray position and direction
        double cameraX = 2 * x / double(w) - 1; //x-coordinate in camera space
        double rayPosX = posX;
        double rayPosY = posY;
        double rayDirX = dirX + planeX * cameraX;
        double rayDirY = dirY + planeY * cameraX;

        //which box of the map we're in
        int mapX = int(rayPosX);
        int mapY = int(rayPosY);

        //length of ray from current position to next x or y-side
        double sideDistX;
        double sideDistY;

        //length of ray from one x or y-side to next x or y-side
        double deltaDistX = sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX));
        double deltaDistY = sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY));
        double perpWallDist;

        //what direction to step in x or y-direction (either +1 or -1)
        int stepX;
        int stepY;

        int hit = 0; //was there a wall hit?
        int side; //was a NS or a EW wall hit?

                  //calculate step and initial sideDist
        if (rayDirX < 0)
        {
            stepX = -1;
            sideDistX = (rayPosX - mapX) * deltaDistX;
        }
        else
        {
            stepX = 1;
            sideDistX = (mapX + 1.0 - rayPosX) * deltaDistX;
        }
        if (rayDirY < 0)
        {
            stepY = -1;
            sideDistY = (rayPosY - mapY) * deltaDistY;
        }
        else
        {
            stepY = 1;
            sideDistY = (mapY + 1.0 - rayPosY) * deltaDistY;
        }

        //perform DDA
        while (hit == 0)
        {
            //jump to next map square, OR in x-direction, OR in y-direction
            if (sideDistX < sideDistY)
            {
                sideDistX += deltaDistX;
                mapX += stepX;
                side = 0;
            }
            else
            {
                sideDistY += deltaDistY;
                mapY += stepY;
                side = 1;
            }
            //Check if ray has hit a wall
            if (worldMap[mapX][mapY] > 0)
            {
                hit = 1;
            }

        }

        //Calculate distance projected on camera direction (oblique distance will give fisheye effect!)
        if (side == 0)
        {
            perpWallDist = fabs((mapX - rayPosX + (1 - stepX) / 2) / rayDirX);
            while (rayPosY > 1)
            {
                rayPosY =- 1;
            }
            textureSectionX = rayPosY;
        }
        else
        {
            perpWallDist = fabs((mapY - rayPosY + (1 - stepY) / 2) / rayDirY);
            while (rayPosX > 1)
            {
                rayPosX =- 1;
            }
            textureSectionX = rayPosX;
        }

        if (textureSectionX < 0)
        {
            textureSectionX = fabs(textureSectionX);
        }

        if (textureSectionX > 64)
        {
            return 0;
        }

        //Calculate height of line to draw on screen
        float lineHeight = abs(int(h / perpWallDist));
        scaleY = lineHeight / 64;
        scaleX = hitCount[mapX][mapY] / 64;
        if (scaleX < 1)
        {
            scaleX = 1;
        }

        //choose wall texture

        switch (worldMap[mapX][mapY])
        {
        case 1:  WallTexture.setTexture(bluestone); break;
        case 2:  WallTexture.setTexture(eagle); break;
        case 3:  WallTexture.setTexture(greystone);break;
        case 4:  WallTexture.setTexture(redbrick); break;
        default: WallTexture.setTexture(mossystone);break;
        }

        if (LastMapY == mapY && LastMapX == mapX && side == LastSide)
        {
            Repeats++;
        }
        else
        {
            Repeats = 0;
        }

        textureSectionX = textureSectionX + Repeats;

        //give x and y sides different brightness
        if (side == 1)
        {
            WallTexture.setColor(sf::Color(148,148,148,255));
            textureSectionX = 64 - textureSectionX;

        }

        float y = 288 - ((64 * scaleY) / 2);

        //Draw the walls
        WallTexture.setScale(1, scaleY);
        WallTexture.setTextureRect(sf::IntRect(textureSectionX,0,1,64));

        int drawTexture = 0;

        while (drawTexture < scaleX)
        {
            WallTexture.setPosition(x, y);
            window.draw(WallTexture);
            drawTexture++;
            x++;
        }
        x--;

        WallTexture.setColor(sf::Color(255, 255, 255, 255));

        LastMapY = mapY;
        LastMapX = mapX;
        LastSide = side;
    }

    fps = clock.getElapsedTime();
    float fpsValue = 1000000 / fps.asMicroseconds();
    clock.restart();

    double moveSpeed = fps.asSeconds() * 5.0; //the constant value is in squares/second
    double rotSpeed = fps.asSeconds() * 3.0; //the constant value is in radians/second

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        //both camera direction and camera plane must be rotated
        double oldDirX = dirX;
        dirX = dirX * cos(rotSpeed) - dirY * sin(rotSpeed);
        dirY = oldDirX * sin(rotSpeed) + dirY * cos(rotSpeed);
        double oldPlaneX = planeX;
        planeX = planeX * cos(rotSpeed) - planeY * sin(rotSpeed);
        planeY = oldPlaneX * sin(rotSpeed) + planeY * cos(rotSpeed);
    }
    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        //both camera direction and camera plane must be rotated
        double oldDirX = dirX;
        dirX = dirX * cos(-rotSpeed) - dirY * sin(-rotSpeed);
        dirY = oldDirX * sin(-rotSpeed) + dirY * cos(-rotSpeed);
        double oldPlaneX = planeX;
        planeX = planeX * cos(-rotSpeed) - planeY * sin(-rotSpeed);
        planeY = oldPlaneX * sin(-rotSpeed) + planeY * cos(-rotSpeed);
    }
    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
        if (worldMap[int(posX + dirX * moveSpeed)][int(posY)] == false) posX += dirX * moveSpeed;
        if (worldMap[int(posX)][int(posY + dirY * moveSpeed)] == false) posY += dirY * moveSpeed;
    }
    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
        if (worldMap[int(posX - dirX * moveSpeed)][int(posY)] == false) posX -= dirX * moveSpeed;
        if (worldMap[int(posX)][int(posY - dirY * moveSpeed)] == false) posY -= dirY * moveSpeed;
    }

    window.display();
    window.clear();
}

return EXIT_SUCCESS;
};

```

# Answer
The fact that the last line is repeated on your blue wall hints me that you should *maybe* set your `WallTexture` to repeat with `setRepeat( true )`, or that you have a bug with the correct mapping of your texture on the plane. Your code being very complex, I suggest you leave only one wall (e.g. the blue wall that you currently have an issue with), and do a render pass and output to the console all the relevant data and compare it to what you would expect, i.e. your `textureSectionX` should probably not be \< 0 and it should probably always go to up to 63...
> 1 votes

---
Tags: c++, sfml, raycasting
---


# Question
Title: Detect when item has been dragged & dropped onto an inventory slot
In my inventory system I want to be able to drag and drop items into inventory slots.

I managed to make it work, but only in a weird way:

* When the player starts dragging, it picks up the item and it follows the mouse's position.
* When they release the button outside the inventory, the item's position is restored to the slot from which it was picked up.

I use `GameObject mouseReleasedObject = eventData.pointerCurrentRaycast.gameObject;` to detect whether the drag was released over an inventory slot.
* The problem is that when the player drops it on a possible inventory slot, the same "restore to previous slot" behaviour happens.

That's because the mouse is top of the dragged item *and* the slot as well but the item is rendered above everything else.

How can I make the dragging ignore the item itself, and detect the slot underneath?

Start dragging:

```
    public void OnBeginDrag(PointerEventData eventData)
    {
        GameObject draggedObject = eventData.rawPointerPress;
        if(draggedObject.GetComponent<RectTransform>() is null) return;

        if(draggedObject.tag == "InventoryItem")
        {
            Debug.Log("InventoryItem drag has started!");
            dragStartSlot = draggedObject.transform.parent.gameObject;
            draggedItem = draggedObject;
            draggedItem.transform.SetParent(canvas.transform);
            draggedItem.transform.SetAsLastSibling();

        }
    }

```

End dragging:

```
    public void OnEndDrag(PointerEventData eventData)
    {

        GameObject mouseReleasedObject = eventData.pointerCurrentRaycast.gameObject;
        if(draggedItem is null) return;
        Debug.Log("Released at: "+mouseReleasedObject.gameObject.name);
        if(mouseReleasedObject.transform.tag == "InventorySlot")
        {
            if(mouseReleasedObject.transform.childCount < 1)
            {
                //  the inventory slot is empty, we place here the item!
                draggedItem.transform.SetParent(mouseReleasedObject.transform);
                draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
            }
            else
            {
                //  the inventory slot is taken, we swap the items!
            }
        }
        else
        {
            //  the item is not released on a proper slot, we restore it's position!
            draggedItem.transform.SetParent(dragStartSlot.transform);
            draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
        }
    }

```

# Answer
My solution for this problem is using the Canvas' Graphic Raycaster Component:

```
public void OnEndDrag(PointerEventData eventData)
    {

        bool itemHasBeenPlaced = false;
        var results = new List<RaycastResult>();
        graphicRaycaster.Raycast(eventData, results);
        foreach(var hit in results)
        {
            if(hit.gameObject.transform.tag == "InventorySlot")
            {
                if(hit.gameObject.transform.childCount < 1)
                {
                    //  the inventory slot is empty, we place here the item!
                    draggedItem.transform.SetParent(hit.gameObject.transform);
                    draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
                    itemHasBeenPlaced = true;
                }
                else
                {
                    //  TODO: the inventory slot is taken, we swap the items!
                    Debug.Log("the inventory slot is taken, we swap the items!");
                    itemHasBeenPlaced = true;
                }
            }
        }
        if(!itemHasBeenPlaced)
        {
            //  the item is not released on a proper slot, we restore it's position!
            draggedItem.transform.SetParent(dragStartSlot.transform);
            draggedItem.GetComponent<RectTransform>().localPosition = Vector3.zero;
        }

    }

```
> 1 votes

---
Tags: unity, c#, gui, user-interface
---


# Question
Title: Non-invocable member 'WaitForSeconds' cannot be used like a method
I have a script - using System.Collections;

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

public class Spawn : MonoBehaviour
{
    public GameObject Diamond;
    public int DiamondCount;
    public int Xpos;
    public int Zpos;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(Spawning);
    }
    IEnumerator Spawning()
    {
        while (DiamondCount < 5)
        {
            Xpos = Random.Range(24, -17);
            Zpos = Random.Range(-17, 24);
            Instantiate(Diamond, new Vector3(Xpos, 0.94f, Zpos), Quaternion.identity);
            yield return WaitForSeconds(0.1f);
            DiamondCount +=1;
        }
    }
    // Update is called once per frame
    void Update()
    {

    }
}

```

Which spawns diamonds in an area but I cant get the script to work

Wait For Seconds doesn't work

# Answer
As the documentation for `WaitForSeconds` shows, it is a class that you need to construct and return an instance of.

What you want is:

```
yield return new WaitForSeconds(0.1f);

```
> 1 votes

---
Tags: unity
---


# Question
Title: How to make a script on a prefab act on a particular scene instance?
I am building Actionables (Windmill, Coal) on a Planet by hovering the mouse over the Planet and clicking on it.

Actionables are prefabs, which have an `Actionable` component, with the same setup (at the moment).

Once the player is happy with the location of their Actionable, they click LMB, which activates `onClick` callback, which is supposed to call `Planet.Build()`, which adds the Actionable on the Planet permanently (saves it into an internal array).

I also have a "Turn Off" Button, which calls `stopBuilding()` when clicked, disabling the preview placement.

When `stopBuilding()` is invoked by the button click, everything works as expected.

I also want to be able to call `Planet.stopBuilding()` (which, by removing the `actionableModel`, disables hover preview on the Planet) from `Planet.Build()`, such that the player does not need to click the Turn Off button described above after building an Actionable.

Inside Actionable prefabs I can only assign other prefabs, but I need them to interact with the scene object. I cannot override the Planet object in Actionable instances, as they are generated on the fly.

How do I access the scene object Planet from Actionable prefab?

Here is my `Planet` and its `stopBuilding` method so far:

```
   public class Planet : MonoBehaviour
   {
       private GameObject actionableModel;

       // ...

       public void stopBuilding()
       {
           // For debugging only
           Planet planet = GameObject.Find("Planet").GetComponent<Planet>();
           Debug.Log(planet.actionableModel);
           Debug.Log(this.actionableModel);

       }
   }

```

And here is the `Actionable` component which has a `UnityEvent` property `onClick`, which calls `stopBuilding()` on a click event.

```
   public class Actionable : MonoBehaviour
   {
       public class OnClick : UnityEvent<GameObject> { }
       public OnClick onClick = new OnClick();

       // ...

       void OnMouseDown()
       {
           onClick.Invoke(gameObject);
       }
   }

```

# Answer
> 1 votes
First, I want to challenge this:

> I cannot override the Planet object in Actionable instances, as they are generated on the fly.

They are being generated on the fly *by your code*. So, *your code* can provide the correct `Planet` instance.

```
Actionable SpawnActionablePrefab(Actionable prefab, Planet planetToBuildOn) {
    var instance = Instantiate(prefab);

    // TODO: Position/rotate it as desired or perform other setup steps.

    instance.OnClick.AddListener(() => planet.StopBuilding(instance.gameObject));

    return instance;
}

```

You could use this same approach to assign the current planet to a member variable on the instance at spawn time, so it has a local record of who to call later, in case you want to avoid constructing delegates all the time.

So be wary of the temptation to throw up your hands and say "I can't" - chances are, you *can*.

---

That said, I think there are other approaches that are more scalable - especially if you want to grow your game to support multiple planets, pooling actionables, etc. in the future.

We could introduce a `SelectionManager` whose job it is to keep track of which planet the player is currently interacting with.

```
public class SelectionManager : MonoBehaviour {

    // Quick & dirty singleton pattern with lazy instantiation,
    // so it works even if you don't have an instance in your scene.
    static SelectionManager _instance;
    public static SelectionManager Instance {
        get {
            if (_instance == null) {
                _instance = FindObjectOfType<SelectionManager>();
                if (_instance == null) {
                    var manager = new GameObject("Selection Manager");
                    _instance = manager.AddComponent<SelectionManager>();
                }
            }

            return _instance;
        }
    }

    Planet _selectedPlanet;

    void Awake() {
        // Assign a default selection.
        // Replace this with your actual selection logic when the time comes.
        _selectedPlanet = FindObjectOfType<Planet>();
    }

    public Planet GetSelectedPlanet() { return _selectedPlanet; }

    public void SetSelectedPlanet(Planet planet) {
        // TODO: you might want to call on OnSelect / OnDeselect here,
        // or abort up any UI operations currently in progress on the selected planet.
        _selectedPlanet = planet;
    }
}

```

Now inside `Actionable` we can have a method like this:

```
public void Finish() {
    SelectionManager.Instance.GetSelectedPlanet().StopBuilding(gameObject);
}

```

Your `OnClick` event on the prefab can now call *its own* `Finish()` method. When this is invoked on an instance of the prefab at runtime, it will query the `SelectionManager` to ask for the currently selected planet so that it can route its call to it correctly.

So the prefab doesn't need any references to the scene object when it's sitting in your assets folder. We'll fetch that information on demand.

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


# Question
Title: Make transform.up face toward velocity while preventing transform.forward from rolling?
I have been working on a personal project that is suppose to mimic Anthem. I am using a state machine for the character controller that I intend to integrate with the Unity's Animation state machine.

I am calculating a new velocity that makes the player follow the mouse when flying, and I am making `transform.up = Velocity` so that the player appears to be going head first towards its velocity.

The issue is that when you start to rotate in a circular way on the xz plane, the player will start to roll and its `transform.forward` moves from facing towards the ground (which is what I want) to facing the sky.

The core code is in `public override Update()`:

```
public class s_MechFlyt : MechStates{

  float flySpeedPercentage;

  public s_MechFlyt(in MechController Master) : base(Master){
    flySpeedPercentage = 2.5f;
  }

  public override void Update(){
    if (_Master.SprintButtonHeld){

      Quaternion Rot = Quaternion.Euler(-_Master.DMouse.y , _Master.DMouse.x , 0);

      _Master.Velocity = Rot * Vector3.forward * _Master.Stats.Speed * flySpeedPercentage;
      Vector3 Rotation = _Master.Velocity;**
      //Rotation.y = Mathf.Clamp(Rotation.z, 0, 50);
      _Master.transform.up = Vector3.Normalize(Rotation);
      //_Master.transform.rotation = Rot;

      //_Master.transform.rotation = Quaternion.RotateTowards(_Master.transform.up, _Master.Velocity, 5);

      _Master._Controller.Move(_Master.Velocity * Time.deltaTime);

      if (_Master.JumpButtonHeld){
        _Master.ChangeStates("hover");
        _Master.transform.up = Vector3.up;
      }

    }
    else{
      _Master.ChangeStates("fall");
      _Master.transform.up = Vector3.up;
    }
  }

  public override void EnterState(){
    _Master.CamController.ChangeStates("flying");
  }
}

```

# Answer
> 0 votes
You already have a rotation that points `Vector3.forward` in the direction of flight, while keeping `Vector3.up` as vertical as it can.

Pitching that rotation forward 90 degrees means it points `Vector3.up` in the direction of flight, and points `Vector3.forward` down.

```
Quaternion mouseRotation = Quaternion.Euler(-_Master.DMouse.y , _Master.DMouse.x , 0);

_Master.Velocity = mouseRotation * Vector3.forward * _Master.Stats.Speed * flySpeedPercentage;

_Master.transform.rotation = mouseRotation * Quaternion.Euler(90f, 0, 0);

```

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


# Question
Title: How do you simulate UV light and materials with UV-reflective/fluorescent properties within a PBR renderer?
I have a PBR setup, say, in Unity (or Unreal, doesn't really matter, I'm asking about the general principle, not specific implementation), and I would like to add a UV light source, and have control over how my materials respond to it, but still ideally have it conform to the rules of physically-based rendering.

Question is: what do I need to extend with what kinds of properties, and what are the equations to wire them together, and where do I plug those?

Do I need to actually do modifications like this, or does the fact that it already is PBR mean that I only need to plop in a light source with correct combination of settings, and correct responses to that UV source just naturally happen?

Edit: I am asking about fluorescence, where I want certain materials to glow in particular visible light colours in places where the invisible UV light hits them.

# Answer
*Disclaimer: I don't have experience with PBR; this answer is just filtering my physics knowledge through computer graphics concepts.*

Fluorescence can be understood in general as: a material absorbs light of some wavelength (/frequency/energy), and then emits light of another (longer, lower energy) wavelength. This is not exclusive to UV (e.g. a material may be excited by blue light and emit green light).

*Phosphorescence* (a.k.a. “glow in the dark”) is functionally the same phenomenon except that the re-emission is slow, on a time scale we can perceive. If you want to model phosphorescence then it would have to be as an independent light source rather than a kind of reflection, since it's stateful.

> what do I need to extend with what kinds of properties

You need to simulate UV light propagation — light sources and ordinary reflections. An additional color channel may be suitable. Note that common window glass passes some but not all UV; if you care about this and similar effects you might need *multiple* UV channels.

Each fluorescent material needs a color of visible light it emits, and the *efficiency* of the conversion (which, in the model, can just be the brightness of that color). It may also need the spectrum it *absorbs* (if you care about modeling the different absorption of different UV wavelengths or even green light) and a decay rate (if you are modeling phosphorescence).

> and what are the equations to wire them together

UV light propagation follows the same rules, with different material-specific parameters, as visible light propagation.

Fluorescence could be calculated in the same way as a diffuse reflection (and transmission for thin objects such as a sheet of plastic), except that instead of multiplying the incoming light componentwise by the reflectance or transmittance, you take the dot product of the incoming light and the absorption spectrum (or select only the UV component of the light if you're not modeling the absorption explicitly), obtaining a scalar, and then multiply the emission color by that scalar.

If you want to include phosphorescence (which is only relevant in response to time-varying UV lighting conditions), then the abovementioned scalar needs to be a persistent state of the object (or individual texels of its surface) — think of it as the energy storage powering a light source. The UV absorption adds energy and the visible emission consumes it (with some inefficiency along the way). The emission rate may or may not be proportional to the energy (i.e. typical exponential decay); I found references to more complex behavior but probably exponential decay is a good enough model for visual effects.
> 1 votes

---
Tags: rendering, lighting, pbr
---


title: Check if point lies within coordinates

text:
# Question
Title: Check if point lies within coordinates
Let's say I have min (0,0,0) and max (1,1,1). If I have 3 points, lets say

* a (0.2,0.4,0.2)
* b (-0.5,0.8,0.2)
* c (2,0.3,0.1)

How would I go about calculating it those points are within the coordinates of min and max?

*Note that I am using simple shapes such as Cubes and that I am going to use this for optimizations with octrees*

# Answer
This is what we call an axis aligned bounding box (AABB) containment check:

```
bool IsInsideAABB(Point check, Point min, Point max) {
    return min.x <= check.x && check.x <= max.x
        && min.y <= check.y && check.y <= max.y
        && min.z <= check.z && check.z <= max.z;
}

```

Depending on your application, you might want to count points exactly on one boundary or another to be outside the box - so you may want to replace some of the `<=` with `<`

See How should I do AABB::contains? for more on that.
> 0 votes

---
Tags: java, 3d, lwjgl
---


# Question
Title: Where to place "Set XYZ over life" blocks in Unity VFX graph?
As the title says, I am learning VFX graph in Unity and I am curious where I should place `"Set ... over Life"`, for example `"Set Color over Life"` which adjust the color based on the particle's age.

When we create a new visual effect graph, they are placed in the *Output* context by default, which kind of seems odd to me, since it seems more like a *Update* function? It also works if I place it in the *Update* context, but I am afraid that I probably mess with the performance if the block should not be placed there for some reason. Also, why can't I set it in the *Initialize* context - if I do, no changes over time are applied.

Probably someone could point me to the right documentation or some explanation for this, thanks. In general, it would be nice to have a documentation that states which blocks should be used within which context (Initialize, Update, Output).

# Answer
You can place the "Set Color over Life" in any of the sections you are able to drag it into, it wont allow you to place it in the section if it can't be used there, but I believe the Output is the only section with unique blocks, as you've noticed if you place "Set Color over Life" on initialize, it will set the "Set Color over Life" property at the (**start**), you can then change that property again while the particle lives (**update**) if you required and when it is finally rendered with (**Output**).

Although less useful, it really depends on the behaviour you are trying to achieve as to when/how you employ these different blocks.

I would not worry about performance regarding where you place these blocks as they are very preformant and nearly all of the time the problems with performance will depend entirely on how complex you make the graph and how many total particles you can use.
> 0 votes

---
Tags: unity, particles, vfxgraph
---


# Question
Title: Why does the player grab the object outside the trigger zone?
I want the player to be able to grab an object (in this case the knife) when he is in the object's trigger zone. He can get the knife but there is a problem: if I press grab button outside of the trigger zone, then he can get the knife immediately after entering the zone. I want Unity to get the input only when the player is in the trigger, otherwise it should not be working.

Here's the grab script:

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

public class Grab : MonoBehaviour
{
    public GameObject player;
    private bool grabbed;
    public GameObject knifePosition;
    private bool isInTrigger;

    void Update()
    {
        if (Input.GetButtonDown("Grab"))
        {
            grabbed = true;

        } else
        {
            grabbed = false;
        }

       if (grabbed && isInTrigger)
        {
            gameObject.transform.position = knifePosition.transform.position;
       }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject == player && grabbed)
        {
            gameObject.transform.SetParent(player.transform);
            isInTrigger = true;
            Debug.Log("Picked up");
        }
    }
}

```

# Answer
You do not set your `grabbed` back to false in case you do not press the button. This causes your script to remember the pressing and will pick up your item as soon as you enter the zone.

```
void Update() {
    if (Input.GetButtonDown("Grab"))
    {
        grabbed = true;
    } else {
        grabbed = false;
    }
}

```
> 2 votes

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


title: Unity App Crashes on Android

text:
# Question
Title: Unity App Crashes on Android
I've had this issue many a time, unfortunately anything I've used to fix it before doesn't work. So, if I build and run the app, it will run the app for about 5 seconds, before crashing. If I install the apk and try and run it, it will crash immediately.

I cannot for the life of me figure out what's wrong, this is an app I've built with no issues a hundred times, I am pretty certain I never changed any player settings since then, I did, however, reinstall the unity version as I had an issue with the android SDK because it didn't install properly.

I ran logcat in the Android Studio, and the only errors of note I could find are invalid vkGetInstanceProcAdd and Connecting to host time out, player connection will be disabled? However, it does seem to initialize the app through Android studio.

Here is a pastebin of my logcat, filtered to only include unity related issues.

https://pastebin.com/buRGfjXa

Thanks in advance.

# Answer
> 0 votes
Okay, this is kinda embarrassing , I found out the issue lol

I had a switch statement that either loaded the game or quit the game depending on which button was pressed. I realized the default was set to quit game, and I forgot to only count down the timer if the button had been pressed, so it was counting down the timer and then quitting right off the bat...

Not sure who this will help, but I hope it'll at least encourage people to look beyond a crash error if they see this...

I feel like an idiot lol, I don't know why this issue just came up though, the menu seemed to work just fine before...

---
Tags: unity
---


# Question
Title: Unity mailchimp / Klaviyo subscription form
Hey everyone so i want to add a subscription form on my game. so far i can send data to a database and display them on a leaderboard, i found a similar question here but its a bit outdated. Ideally i would like to use klaviyo but since this is the only lead i have i might want to get familiar with how it works!

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

public class MailingScript : MonoBehaviour
{

    public InputField emailField;
    public InputField nameField;

    public void onClick()
    {
        StartCoroutine(SendToMailChimp());
    }

    private IEnumerator SendToMailChimp()
    {
        WWWForm form = new WWWForm();
        form.AddField("EMAIL", emailField.text);
        form.AddField("b_0f079b7af1cef143021ff4236_6cd74c0a6a", nameField.text);
        //form.AddField("subscribe", "Subscribe");
        UnityWebRequest www = UnityWebRequest.Post("https://slaga-games.us1.list-manage.com/subscribe/post?u=0f079b7af1cef143021ff4236&id=6cd74c0a6a", form);
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Registered");
        }
    }
}

```

this is my code so far but it wont do anything. i have a same code for the database which works!

# Answer
found another script here that works for mailchimp https://github.com/fiftytwo/MailChimpSubscriber/blob/main/MailChimpSubscriber.cs Yeah of course so this is the script that i use at the moment for mailchimp

```
 #if UNITY_EDITOR || DEVELOPMENT_BUILD
#define ENABLE_MAILCHIMP_ERROR_LOG
#define ENABLE_MAILCHIMP_SUCCESS_LOG
#endif

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Text;
using System.Net.Mail;
using JetBrains.Annotations;
using UnityEngine.Networking;

namespace Fiftytwo
{
    [PublicAPI]
    public class MailChimpSubscriber : MonoBehaviour
    {
        private const string UrlFormat = "https://{0}.api.mailchimp.com/3.0/lists/{1}/members";
        private const string JsonFormat = "{{\"email_address\":\"{0}\", \"status\":\"subscribed\"}}";

        public MailChimpEvent SubscribeSuccess = new MailChimpEvent();
        public MailChimpEvent SubscribeError = new MailChimpEvent();

        [SerializeField] private string _apiKey = string.Empty;
        [SerializeField] private string _listId = string.Empty;
        public InputField text;

        public void Subscribe ()
        {

            if( text.text == null )
            {
#if ENABLE_MAILCHIMP_ERROR_LOG
                Debug.LogError( "MailChimp — No UI Text found at this GameObject" );
#endif
                SubscribeError.Invoke( null );
                return;
            }

            Subscribe( text.text );
        }

        public void Subscribe ( string email )
        {
            try
            {
                var url = BuildUrl();
                if( string.IsNullOrEmpty( url ) )
                {
#if ENABLE_MAILCHIMP_ERROR_LOG
                    Debug.LogError( "MailChimp — Invalid API Key format" );
#endif
                    SubscribeError.Invoke( email );
                    return;
                }

                var mailAddress = new MailAddress( email );

                StartCoroutine( SendToMailChimp( url, mailAddress.Address ) );
            }
            catch( Exception ex )
            {
#if ENABLE_MAILCHIMP_ERROR_LOG
                Debug.LogError( "MailChimp — Invalid email: " + ex.Message );
#endif
                SubscribeError.Invoke( email );
            }
        }

        private string BuildUrl ()
        {
            var separatorIndex = _apiKey.LastIndexOf( '-' );
            if( separatorIndex < 0 )
                return null;

            var urlPrefix = _apiKey.Substring( separatorIndex + 1 );
            if( string.IsNullOrEmpty( urlPrefix ) )
                return null;

            return string.Format( UrlFormat, urlPrefix, _listId );
        }

        private IEnumerator SendToMailChimp ( string url, string email )
        {
            var request = new UnityWebRequest( url, UnityWebRequest.kHttpVerbPOST );

            request.SetRequestHeader( "Content-Type", "application/json" );
            request.SetRequestHeader( "Authorization", "apikey " + _apiKey );

            var json = string.Format( JsonFormat, email );
            var jsonBytes = Encoding.UTF8.GetBytes( json );
            request.uploadHandler = new UploadHandlerRaw( jsonBytes );

            request.downloadHandler = new DownloadHandlerBuffer();

            yield return request.SendWebRequest();

            if( request.isNetworkError )
            {
#if ENABLE_MAILCHIMP_ERROR_LOG
                Debug.LogErrorFormat( "MailChimp — Network error: {0}", request.error );
#endif
                SubscribeError.Invoke( email );
                yield break;
            }

            if( request.isHttpError )
            {
#if ENABLE_MAILCHIMP_ERROR_LOG
                Debug.LogErrorFormat( "MailChimp — Subscribe error {0}: {1}\n{2}",
                    request.responseCode, request.error, request.downloadHandler.text );
#endif
                SubscribeError.Invoke( email );
                yield break;
            }

#if ENABLE_MAILCHIMP_SUCCESS_LOG
            Debug.LogFormat( "MailChimp — Subscribe success {0}\n{1}", request.responseCode, request.downloadHandler.text );
#endif
            SubscribeSuccess.Invoke( email );
        }

        [Serializable]
        public class MailChimpEvent : UnityEvent<string>
        {
        }
    }
}

```
> 0 votes

---
Tags: unity, unity-networking
---


# Question
Title: Why does the kinematic body move in opposite direction after I interpolate its movement, and how do I fix it?
I have added some basic movement and some manual interpolation to a cube that is a kinematic body in Godot.

```
extends KinematicBody

var speed : int = 10
var slowdown_buffer = 0.2
var movement = Vector3(0,0,0)
func _ready():
    pass

func interpolate():
    if movement.x > 0:
            movement.x -= slowdown_buffer
    elif movement.x < 0:
        movement.x += slowdown_buffer
    else:
        movement.x = 0.0
func _physics_process(delta):
    if Input.is_action_pressed("left"):
        movement.x = -speed
    elif Input.is_action_pressed("right"):
        movement.x = speed
    else:
        interpolate()

    move_and_slide(movement)

```

The problem is that when I move the cube using `A` and `D`, after the cube stops after the interpolation, it starts moving in the opposite direction with a non-increasing speed.

How can I fix this?

# Answer
> 5 votes
You can't rely on `movement.x` hitting 0. This is because floating point errors. Instead, check if it is closer to 0 than `slowdown_buffer` then set it to 0. Like so:

```
extends KinematicBody

var speed : int = 10
var slowdown_buffer = 0.2
var movement = Vector3(0,0,0)
func _ready():
    pass

func interpolate():
    var slowdown = slowdown_buffer
    if movement.x > 0:
        if movement.x < slowdown:
            movement.x = 0
        else:
            movement.x -= slowdown
    elif movement.x < 0:
        if movement.x > -slowdown:
            movement.x = 0
        else:
            movement.x += slowdown

func _physics_process(delta):
    if Input.is_action_pressed("left"):
        movement.x = -speed
    elif Input.is_action_pressed("right"):
        movement.x = speed
    else:
        interpolate()

    move_and_slide(movement)

```

Another thing I notice is that you are not using `delta`. And thus your code is not compensating variations in frame rate.

I would pass it to `interpolate`, and have `slowdown = slowdown_buffer * delta`. The units of `slowdown_buffer` were in change of speed per frame, after they are in change of speed per second. Assuming you had a target frame rate of 60, you want to multiply `slowdown_buffer` by 60, which gives us the value 12.

Like this:

```
extends KinematicBody

var speed : int = 10
var slowdown_buffer = 12
var movement = Vector3(0,0,0)
func _ready():
    pass

func interpolate(delta):
    var slowdown = slowdown_buffer * delta
    if movement.x > 0:
        if movement.x < slowdown:
            movement.x = 0
        else:
            movement.x -= slowdown
    elif movement.x < 0:
        if movement.x > -slowdown:
            movement.x = 0
        else:
            movement.x += slowdown

func _physics_process(delta):
    if Input.is_action_pressed("left"):
        movement.x = -speed
    elif Input.is_action_pressed("right"):
        movement.x = speed
    else:
        interpolate(delta)

    move_and_slide(movement)

```

---

However, to better take advantage of the engine, consider using a `Tween`, for example:

```
extends KinematicBody

var speed : int = 10
var tween: Tween;
var movement = Vector3(0,0,0);

func _ready():
    tween = Tween.new();
    add_child(tween);

func update_movement(value: float):
    movement.x = value;

func _physics_process(delta):
    if Input.is_action_pressed("left"):
        tween.interpolate_method(self, 'update_movement', -speed, 0, 0.833)
        tween.start()
    elif Input.is_action_pressed("right"):
        tween.interpolate_method(self, 'update_movement', speed, 0, 0.833)
        tween.start()

    move_and_slide(movement)

```

That number 0.833 is the duration. After 0.833 seconds it will reach 0. *Originally you were reducing by 0.2 each frame starting from 10, which would take 50 frames. Assuming 60 frames per second, it would take 50/60 seconds to complete, that is aprox 0.833.*

Using `Tween`, you would not have to do these interpolations by hand, nor worry about frames or `delta`, just set the total time. Furthermore, if you see the documentation for `interpolate_method` or the other methods in tween, you can see that it allows you to specify a `TransitionType` and `EaseType`.

*Ah, yes, `Tween` is a node. It is the little sibling of `AnimationPlayer`, which you could use to animate any property… Thus, another option is to export `movement`, create animations in an `AnimationPlayer` that animate (change over time) `movement`, and play them.*

---
Tags: godot, interpolation
---


# Question
Title: Correct way to set up camera buffer [DirectX]
I would like to play with two different implementation of particle system in my project (ok, actually not mine, but I am working on it). I copied the particle system successfully, however, faced the camera buffer initialization problem, highlight this code:

```
bool ParticleShader::Render(Direct3DManager* direct, ParticleSystem* particlesystem, Camera* camera)
{
    bool result;

    result = SetShaderParameters(direct->GetDeviceContext(), camera, direct->GetWorldMatrix(), camera->GetViewMatrix(), direct->GetProjectionMatrix(), particlesystem->GetTexture());
    if (!result)
        return false;

    RenderShader(direct->GetDeviceContext(), particlesystem->GetVertexCount(), particlesystem->GetInstaceCount(), particlesystem->GetIndexCount());
    return true;
}

```

If I just call SetShaderParameters with the same args, there is a bug obviously: particle system scene sticks to the camera (originally, it looks like this).

I checked the params in debug mode and found out that the difference is in the World matrix. The DXUT CFirstPersonCamera is used in my project and it changed the World matrix while moving around the scene whereas in the original particle system project it's constant (identity matrix).

I understand that there is a difference between DXUT camera and the default project camera at the ideological level. Nevertheless, I am a newbie in Graphic it's too difficult to realize how to change the code in a proper way.

Thank you in advance

# Answer
> 0 votes
Hmm.. lt sounds quite silly, however, I hardcoded World Matrix as the identity matrix and It looks OK

---
Tags: camera, directx
---


title: 400 bad request UnityWebRequest

text:
# Question
Title: 400 bad request UnityWebRequest
hey everyone any ideas why im getting a 400 error? im trying to post a json to a subscription list. doing that through postman works just fine!

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class testing : MonoBehaviour
{
    //public InputField field;
    [SerializeField]
    private Email _email = new Email();
    private string URL = "https://a.klaviyo.com/api/v2/list/YeXzKp/members?api_key=pk_ec448e1bdab7504c143466ca5eeabc5e95&profiles=[]";
    IEnumerator SaveIntoJson()
    {
        string data = JsonUtility.ToJson(_email);
        System.IO.File.WriteAllText(Application.persistentDataPath + "Data.json", data);

        //UnityWebRequest www = UnityWebRequest.Post("URL", data);
        //www.SetRequestHeader("Content-type", "application/json");
        UnityWebRequest request = UnityWebRequest.Put(URL, data);
        request.SetRequestHeader("Content-Type", "application/json");
        yield return request.SendWebRequest();
        //yield return www.SendWebRequest();

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
        }
        Debug.Log(data);
    }

    public void SaveData()
    {
        StartCoroutine(SaveIntoJson());
    }
}
[System.Serializable]
public class Email
{
    public List<Profiles> profiles = new List<Profiles>();
}

[System.Serializable]
public class Profiles
{
    public string email;
}

```

# Answer
> 1 votes
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class testing : MonoBehaviour
{
    //public InputField field;
    [SerializeField]
    private Email _email = new Email();
    private string URL = "urlHere&profiles=[]";

    public void SaveData()
    {
        string data = JsonUtility.ToJson(_email);
        System.IO.File.WriteAllText(Application.persistentDataPath + "Data.json", data);
        StartCoroutine(SaveIntoJson(URL , data));
    }
    IEnumerator SaveIntoJson(string url, string data)
    {
        var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
        request.SetRequestHeader("Content-Type", "application/json");
        var jsonBytes = Encoding.UTF8.GetBytes(data);
        request.uploadHandler = new UploadHandlerRaw(jsonBytes);

        request.downloadHandler = new DownloadHandlerBuffer();

        yield return request.SendWebRequest();

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
            Debug.Log(request.downloadHandler.text);
        }
        else
        {
            Debug.Log("Form upload complete!");
        }
        Debug.Log(data);
    }

}
[System.Serializable]
public class Email
{
    public List<Profiles> profiles = new List<Profiles>();
}

[System.Serializable]
public class Profiles
{
    public string email;
}

```

---
Tags: unity, networking, unity-networking
---


# Question
Title: how to create a curve movement of slider in unity
I am trying to create a curved (not circular) movement of slider. Here is my demo images for reference:

I have watched some tutorial but those are for circle images. I want to make this movement along the arrow images below car. Also if this can be done with just images without using slider that will be ok too. I just this done the simpler and easy way.

# Answer
> 1 votes
I created the animation of object on the required path. And when user touches the object the animation triggers.

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


title: Parse Data on runtime into JSON

text:
# Question
Title: Parse Data on runtime into JSON
I have been trying to work out a subscription form for my game and thanks to you guys here, I came to a solution which works but still needs some changes.

The idea is to have an input field in the scene that takes the users email and convert it into JSON (to do a POST request). I have made the post request and everything works fine but I have to manually type the email in the inspector. What I would want is to get that value from the input field!

```
    public class testing : MonoBehaviour
    {
        public TMP_InputField myField;
        //public InputField field;
        [SerializeField]
        private Email _email = new Email();
        private string URL = "";

        public void SaveData()
        {
            string data = JsonUtility.ToJson(_email); // this part here needs to be like _email.text
            System.IO.File.WriteAllText(Application.persistentDataPath + "Data.json", data);
            StartCoroutine(SaveIntoJson(URL , data));
        }
        IEnumerator SaveIntoJson(string url, string data)
        {
            var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
            request.SetRequestHeader("Content-Type", "application/json");
            var jsonBytes = Encoding.UTF8.GetBytes(data);
            request.uploadHandler = new UploadHandlerRaw(jsonBytes);
            request.downloadHandler = new DownloadHandlerBuffer();

            yield return request.SendWebRequest();
            if (request.isNetworkError || request.isHttpError)
            {
                Debug.Log(request.error);
                Debug.Log(request.downloadHandler.text);
            }
            else
            {
                Debug.Log("Form upload complete!");
            }
            Debug.Log(data);
        }
    }
    [System.Serializable]
    public class Email
    {
        public List<Profiles> profiles = new List<Profiles>();
    }
    [System.Serializable]
    public class Profiles
    {
        [SerializeField]
        public string email; // this part here works but i need to type the email in the inspector
    }

```

also the requirements for the json are like this

```
 {"profiles":[{"email":"testing@tes.com"}]}

```

# Answer
> 0 votes
JsonUtility.ToJson only works with objects of a class which inherits from `MonoBehaviour` or `ScriptableObject` or which has the `[Serializable]` attribute. So when you want to use it to create a Json message for some external API, then you should build classes with the `[Serializable]` attribute which mimic the JSON objects that API expects.

When that API exects a format like this:

```
 {"profiles": [
     {"email":"email1@example.com"},
     {"email":"email2@example.com"} ]
 }`

```

then you can create two classes like this:

```
[Serializable]
private class ApiDataProfile {
     public string email;
}
[Serializable]
private class ApiData {
     public ApiDataProfile[] profiles;
}

```

These classes can be declared within the class which uses them. So you don't necessarily need to create new sourcecode files for them.

You can then create your JSON string by using object and collection initializers:

```
string data = JsonUtility.ToJson(
      new ApiData {
         profiles = new ApiDataProfile[] {
             new ApiDataProfile { email = "email1@example.com" },
             new ApiDataProfile { email = "email2@example.com" }
         }
      }
);

```

In some cases the API might expect keys which are not valid C# identifier names. They might start with a number or are reserved C# keywords and thus can not be used as variable names. In that case you can help yourself by using the `@` character in front of them:

```
[Serializable]
private class EmailApiData {
     public string _email;
     public string @for;
     public int @1stLoginTimestamp;
}

public void SaveData() {
    string data = JsonUtility.ToJson(new EmailApiData() {
         _email = email.text
         @for = someOtherString
         @1stLoginTimestamp = DateTime.Now
    });
    //...
}

```

---
Tags: unity, unity-networking, json
---


# Question
Title: Analog sticks, deadzones, diagonals, etc
I'm messing about with a knockoff PS3 controller and SDL2 on windows, and noticed that despite the circular restriction, when I position the stick as close as I can to an extreme diagonal, I am reading a max value for displacement on the X and Y axis. Now as a newbie, I would not expect this as obviously in this position the stick is some way from being as far displaced in either axis as it could be. So it seems that the region for min and max readings is a square whose limits are well within the full circular range of movement of the stick, and anything outside this region is deadspace.

I guess different controllers might have different exact sizes for deadzones, but in general, is it the case that all analog controllers are going to exhibit this general behaviour?

# Answer
> 1 votes
Yes, this is a common issue with analog stick inputs, on most if not all gamepad hardware.

We typically apply a circular clamping function a little like this:

```
Vector2 ClampAnalogInput(Vector2 input, float innerDeadzone, float outerDeadzone) {

    float magnitude = input.magnitude;

    float scale = (magnitude - innerDeadZone)/(outerDeadZone - innerDeadZone);

    return input * Clamp(scale, 0, 1)/magnitude;
}

```

This preserves the direction of the input, while scaling the magnitude of the output to lie between 0 and 1, so diagonals have the same maximum magnitude as the cardinal directions.

The two tuning parameters represent...

* the size of the inner dead zone: input inside this radius will be mapped to 0, clamping out drift and noise
* the outer dead zone: input at or beyond this radius will be mapped to 1 - shrink this if you find your device isn't able to hit the full 1.0 magnitude in a particular direction

Unfortunately all gamepad models are a little different out of the box, and their parameters change in different ways as they age, so it's hard to pin down one set of tuning values that works ideally for all devices. The best advice we can give is to experiment with a range of new and old controllers, or expose these parameters as tunable options for your players to be able to support their pad's idiosyncrasies.

Exposing these tuning options can also help make your game more accessible for players using custom input devices, with reduced range of motion making it hard to move the stick all the way to the limit, or tremors that make hard to hold the stick steady.

---
Tags: sdl2, controllers
---


# Question
Title: Make Unity Text Area to act like a logger
I'm trying to create a text area in Unity using `UI.Text` that contains multi-line text which should act like a log view, i.e the text area `Vertical Overflow` is set to `Truncate` and a new line of text is added to the `text` property every now and then but instead of the text being eventually cut of at the bottom when the text area is full I want the text to 'scroll' up so that the newest added line is always the last displayed at the bottom of the text area, e.g.

```
  Line 1
  Line 2
+------------------------------------------+
| Line 3                                   |
| Line 4                                   |
| Line 5                                   |
| Line 6                                   |
| Line 7                                   |
| Line 8                                   |
+------------------------------------------+

```

... When Line 7 is logged Line 1 goes out of the text area at the top, when Line 8 is logged, Line 2 goes out, etc. Can this be done with UI.Text?

# Answer
> 1 votes
I know this is an old post but it came up for me in a Google search so I thought I'd post the solution I came up with. In short Use a string FIFO Queue the same size as the text box.

```
// outputText is the text box.
private Queue textQueue = new Queue();
public void SetOutputText(string outputmsg) {
    if (textQueue.Count > 4) {
        textQueue.Dequeue();
    }
    // you should strip out newlines and handle long lines before storing in the queue
    // that code is not shown here.
    textQueue.Enqueue(outputmsg);
    // rewrite the text each time by joining the FIFO queue elements with a \n newline.
    outputText.text = string.Join("\n", textQueue.ToArray());
}

```

This is not bulletproof. If your outputmsg is too long and wraps, or it contains new lines, it will not fit in outputText so you need to write additional code here to account for that. Also if you use larger fonts for part of the text or anything else that dynamically changes line spacing this won't work.

---
Tags: unity, gui, text
---


# Question
Title: Mesh does not translate accordingly to WheelCollider
So I am trying to implement a car controller script in Unity were the `WheelTransform` position and rotation is set with every update as the same as the `WheelCollider` position and rotation, it all works fine except for one thing: when translating the `WheelTransform`, if the car goes slowly, `WheelTransform` translates as expected, but when the car goes faster, there's a clear offset between the `WheelTransform` position and the actual position of `WheelCollider`. Here's the code were `WheelTransform` position and rotation is set as the same as the `WheelCollider` position and rotation:

```
private void UpdateWheels()
    {
        UpdateWheelPos(frontLeftWheelCollider, frontLeftWheelTransform);
        UpdateWheelPos(frontRightWheelCollider, frontRightWheelTransform);
        UpdateWheelPos(rearLeftWheelCollider, rearLeftWheelTransform);
        UpdateWheelPos(rearRightWheelCollider, rearRightWheelTransform);
    }

    private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans)
    {
        Vector3 pos;
        Quaternion rot;
        wheelCollider.GetWorldPose(out pos, out rot);
        trans.rotation = rot;
        trans.position = pos;
    }

```

Every single one of the car controller scripts I've found and tried use the same code for this section, I have also tried with 2d sprites without any colliders as `WheelTransform` but neither the scripts or changing `WheelTransform` solved the problem. Thanks in advance for the help.

# Answer
This type of issue can occur if two different components are updating an object's position during the frame Update cycle. In this case, `WheelCollider` might be recalculating the pose during `Update()`.

The specific order that `Update()` is called on scripts is undefined (and should be considered random) unless you've explicitly set a Script Execution Order.

If your script is calling `UpdateWheels()` from an `Update()` function, you would see synchronization issues if your script happens to be updating *before* WheelCollider each update. In other words, your script moves the transform to match the pose, *then* the pose changes, and then the frame is rendered with your transform no longer matching the pose.

One way to fix this is to edit the Script Execution Order, but I recommend never editing the execution order unless you absolutely have to, because it is a sort of hacky solution (and the UI for changing it in the Unity Editor is atrocious). In this case, you can instead change your script so that `UpdateWheels()` is called from `LateUpdate()`; that will ensure your code always runs after the WheelCollider has already updated its pose.
> 0 votes

---
Tags: unity, transformation
---


title: How can I apply the changes in runtime?

text:
# Question
Title: How can I apply the changes in runtime?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimFlyertransportationController : MonoBehaviour
{
    public GameObject JetFlame;
    public bool turnOffOn = false;

    // Start is called before the first frame update
    void Start()
    {
        TurnAllAnimtorsOff(transform, turnOffOn);

        if (turnOffOn)
        {
            JetFlame.SetActive(false);
        }
        else
        {
            JetFlame.SetActive(true);
        }
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void TurnAllAnimtorsOff(Transform root, bool onOff)
    {
        Animator[] animators = root.GetComponentsInChildren<Animator>();

        foreach (Animator a in animators)
        {
            if (onOff)
            {
                a.enabled = false;
            }
            else
            {
                a.enabled = true;
            }
        }
    }
}

```

I want that if in runtime I change the turnOffOn flag state apply the changes in real time in the Update for all Animators and also for the JetFlame. Now it's only aply the changes in the editor before running the game.

# Answer
> 0 votes
Just change the function to a public function:

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

public class AnimFlyerTransportationController : MonoBehaviour
{
    [SerializeField] private GameObject JetFlame;
    [SerializeField] private bool startOn = false;

    void Start() {
        SetAnimatorsOn(startOn);
    }

    public void SetAnimatorsOn(bool onOff) {
        Animator[] animators = transform.GetComponentsInChildren<Animator>();
        foreach (Animator a in animators) {
            a.enabled = onOff;
        }
        JetFlame.SetActive(onOff);
    }
}

public class SomeOtherClass : MonoBehaviour {
    [SerializeField] private AnimFlyerTransportationController controller;

    void Update() {
        if (someCondition) controller.SetAnimatorsOn(true);
    }
}

```

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


# Question
Title: Dialogue System only plays the same words
I'm trying to modify brackeys dialogue system using raycast in an interactableOjects Script so that I can talk with multiple characters, however, when I talk to Character A it appears Characters B text and if I go to Character B the same text shows up (which in character B's Case wouldn't be a problem haha). is there a way that I can tell my script to identify both different objects and play different script (I mean without having to create different layers or tags)

InteractableObjects Script:

```
public void PersonInteract()
{
    int layer_mask = LayerMask.GetMask("Person");

    RaycastHit hit;
    if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range, layer_mask))
    {
        Debug.Log("Speak");

        FindObjectOfType<DialogueTrigger>().TriggerDialogue();

    }
}

```

DialogueTrigger Script(the one that is attached to the NPC's):

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

public class DialogueTrigger : MonoBehaviour
{
    public Dialogue dialogue;

    public void TriggerDialogue()
    {
        Debug.Log("Talk");
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);

    }

}

```

# Answer
> 1 votes
`FindObjectOfType` searches your entire scene for the *first* `GameObject` with a component matching the type you asked for, even if that object has nothing whatsoever to do with the object you hit with the raycast.

If you want a `DialogueTrigger` *on the object your raycast hit*, then you should ask that object for *its* `DialogueTrigger` component:

```
public void PersonInteract()
{
    int layer_mask = LayerMask.GetMask("Person");

    RaycastHit hit;
    if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range, layer_mask))
    {
        if (hit.transform.TryGetComponent(out DialogueTrigger trigger)) {
            trigger.TriggerDialogue();
        }
    }
}

```

If your `DialogueTrigger` component sits at a different level of the hierarchy from the object that has the collider your raycast hits (ie. a child or parent object), then you might want `GetComponentInChildren` or `GetComponentInParent` instead.

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


# Question
Title: In collision detection/resolution, what is a "collide and slide" algorithm?
Can anyone help me to better understand the concepts behind this algorithm?

I've seen this phrase come up several times during my research into creating a 3D character controller, but am having issues finding much information about it. One example is from a user manual that accompanies a character controller asset on the Unity asset store.

I'm used to handling collisions in 2D that involve primitive colliders, so most of the time I simply move my entity, check for overlaps, and then calculate the shortest distance out of the primitive (if one is using Unity, he or she can also use the ColliderDistance2D API for this). It seems like "collide and slide" might be a bit more involved, especially in 3D where contact with a mesh may be the norm instead of contact with primitives. From the manual I linked earlier it seems that an entity's movement vector is altered based on the normal of the surface with which that entity collides, but where does the actual collision (overlap) occur, and how do we resolve it?

# Answer
> 1 votes
When we are talking about Collide and Slide, it means that whenever our controlled collider contacts with another collider (for example a wall), instead of stopping our movement, we can use the angle between our wall-normal and hit vector, to slide along the wall, which can be achieved by vector projection.

Unity has a nice method called Vector3.ProjectOnPlane for this job. Of course there are many other ways to achieve this effect or customize it base on your needs.

The Unity character controller component handles this algorithm automatically, so if you use a character controller component for movement, whenever you hit on a wall with an angle you can see the sliding effect.

---
Tags: unity, collision-detection, collision-resolution
---


title: How can I remove Godot's splash screen?

text:
# Question
Title: How can I remove Godot's splash screen?
I started using Godot lately (mostly because the editor supports Linux).

There is one thing that bothers me: the Godot splash screen. I know that I can (somehow) remove it and I saw something about C but I'm not sure.

Is there any way to remove it? Or maybe it is only in the editor and once you export the game it'll disappear?

# Answer
Go to Scene \> Project Settings \> Application and change the `boot_splash` property.
> 20 votes

# Answer
Go to "Project" menu, select "Project settings…" which opens the "Project Settings" dialog. On the left panel select "Application" and inside "Boot Splash". On the right you will find the setting "Image", you can select the image you want to appear there.

Leaving it blank will result in the default image.

And yes, you can place a path that does not exist, and it will fail loading the image (instead you get a white screen), and the game still shows up. However, I suggest to place your own image instead.

I'll also suggest to use an image with transparency, and have black background. Why black? Well, if you export for Android and rotate the screen while the splash screen is up, it will show black bars while rotating. If the background is also black, the user won't notice.

---

As you know, the splash screen will stay up as long as it takes to load the start scene. This means that a start scene that loads faster translates to less splash screen time.

You may take this to your advantage: create a small scene that shows a picture that matches the splash screen (so the user does not notice the change), and loads your main scene in the background (see Background loading). That way you can have a progress bar, have animation, and fade out to reveal your main scene.
> 5 votes

# Answer
Project settings \> application. Enter in `boot_splash`: `null.png`. The engine will not find the image "null" and will leave an empty background.
> 0 votes

---
Tags: godot
---


# Question
Title: Can you help me resolve a bug in mesh collision code?
I have entities which walk along a 3D mesh. I move the units along their x,z axis, and every frame I update their y-position according to the quad or triangle they are standing on, using Barycentric coordinates. They do walk along the mesh, however every time they enter a new quad or triangle, they "bob" up and down on the y-axis.

Height testing is done by finding the "bottom-left" vertex of a "sqaure" of four vertices made by converting the unit's x,z position into a 1d index into an array of vertices.

They move smoothly until they enter a new part of the mesh, where it looks like their y-coordinate shifts once very noticeably and then keep moving smoothly. It happens both when testing against the square made by the four vertices around the unit, and with testing against triangles of mesh.

Here is the code to find y-coordinate on a square:

```
float px = batchTranslation[ i ].Value.x;
float pz = batchTranslation[ i ].Value.z;

int index = ( int ) ( ( math.floor( pz / MAP_SCALE ) ) * MAP_SIZE + ( math.floor( px / MAP_SCALE ) ) );

int bL = index;
int bR = index + 1;
int tL = index + MAP_SIZE;

float3 p1 = vertices[ bL ];
float3 p2 = vertices[ bR ];
float3 p3 = vertices[ tL ];

float3 normal = math.cross( ( p2 - p1 ) , ( p3 - p1 ) );

float py = ( normal.x * ( p1.x - px ) + normal.z * ( p1.z - pz ) + normal.y * p1.y ) / normal.y + HALF_HEIGHT;

batchTranslation[ i ] = new Translation { Value = new float3( px , py , pz ) };

```

Here is the code for finding the y-coordinate on the triangles of the mesh:

float px = batchTranslation[ i ].Value.x;
float pz = batchTranslation[ i ].Value.z;

int index = ( int ) ( ( math.floor( pz / MAP_SCALE ) ) * MAP_SIZE + ( math.floor( px / MAP_SCALE ) ) );

int bL = index;
int bR = index + 1;
int tL = index + MAP_SIZE;
int tR = index + MAP_SIZE + 1;

float3 V1 = vertices[ bL ];
float3 V2 = vertices[ bR ];
float3 V3 = vertices[ tL ];
float3 V4 = vertices[ tR ];

float py = batchTranslation[ i ].Value.y;

if ( IsInside( V1.x , V1.z , V2.x , V2.z , V3.x , V3.z , px , pz ) )
    py = CalcY( V1 , V2 , V3 , px , pz );
else if ( IsInside( V1.x , V1.z , V2.x , V2.z , V4.x , V4.z , px , pz ) )
    py = CalcY( V1 , V2 , V4 , px , pz );

batchTranslation[ i ] = new Translation { Value = new float3( px , py , pz ) };

private float Area( float x1 , float z1 , float x2 , float z2 , float x3 , float z3 )
{
    return math.abs( ( x1 * ( z2 - z3 ) + x2 * ( z3 - z1 ) + x3 * ( z1 - z2 ) ) / 2.0f );
}

private bool IsInside( float x1 , float y1 , float x2 , float y2 , float x3 , float y3 , float x , float y )
{
    float A = Area( x1 , y1 , x2 , y2 , x3 , y3 ); // Calculate area of triangle ABC
    float A1 = Area( x , y , x2 , y2 , x3 , y3 ); // Calculate area of triangle PBC
    float A2 = Area( x1 , y1 , x , y , x3 , y3 ); // Calculate area of triangle PAC
    float A3 = Area( x1 , y1 , x2 , y2 , x , y ); // Calculate area of triangle PAB
    return ( A == A1 + A2 + A3 ); // Check if sum of A1, A2 and A3 is same as A
}

// Returns y coordinate of point on triangle given point x and z coordinates
private float CalcY( float3 p1 , float3 p2 , float3 p3 , float x , float z )
{
    // determinant
    float det = ( p2.z - p3.z ) * ( p1.x - p3.x ) + ( p3.x - p2.x ) * ( p1.z - p3.z );

    float l1 = ( ( p2.z - p3.z ) * ( x - p3.x ) + ( p3.x - p2.x ) * ( z - p3.z ) ) / det;
    float l2 = ( ( p3.z - p1.z ) * ( x - p3.x ) + ( p1.x - p3.x ) * ( z - p3.z ) ) / det;
    float l3 = 1.0f - l1 - l2;

    return l1 * p1.y + l2 * p2.y + l3 * p3.y;
}
```
</code></pre>

# Answer
Turns out I was using the wrong vertices it should be:

```
IsInside( V1.x , V1.z , V2.x , V2.z , V4.x , V4.z , px , pz )

```

And :

```
py = CalcY( V1 , V2 , V4 , px , pz );

```

Or:

```
py = CalcY( V1 , V3 , V4 , px , pz );

```

Also, use doubles instead of floats for accuracy.
> 0 votes

---
Tags: collision-detection, geometry, mesh, barycentric-coordinates
---


# Question
Title: Determining the price of a trade good depending on supply and demand of a marketplace
I've been meaning to add a market/trading system in my space-themed game where a player can buy from one station and sell it to another for profit, etc. (Examples would be Starsector, Elite: Dangerous, EVE Online)

The problem I've been having is actually determining the price of an item based on parameters like: Base Value, Supply, Demand, Transaction costs, Markup, and maybe others if I can think of them. I'm not particularly sure where to start with a price formula.

Any ideas on how to best decide on this?

# Answer
The approach I am using in my current prototype for a space economy simulation is quite simple.

Each market keeps track of how much it has of each resource over time. When the amount of a resource increases over the past x minutes, lower the price. When the amount decreases, increase the price. That way each trading post will reach an equilibrium price where supply and demand will be equal and the stock will stay constant.

This, of course, relies on two features you need in your game:

* It relies on trading. You need lots of agents in the game world who try to make a profit through trading between markets. These can be either human players or AI actors.
* It relies on production output and consumption input adjusting to price developments. When production and consumption never change, then all prices will over time either go to the minimum or the maximum, depending on whether overall production or consumption is larger across the whole game world. So you need a dynamic economy system where the actors adjust their productivity depending on the profitability of their business. When the price for raw materials is low and the price for products is high, then that industry has to grow. When the raw materials are expensive and the products sell for very little, that industry has to shrink. This can either be done by allowing agents to build (and destroy) production facilities or by having any automatic resource siphons or resource drains in the game adjust their output over time to the current prices.

This system will over time reach an equilibrium where supply and demand match exactly and where all prices are constant. Now this is of course a rather boring world to play in. So in order to create interesting business opportunities for the players, you need to shake things up occasionally. There need to be some events which happen occasionally and:

* Destroy production capabilities or resources.
* Create a sudden influx of cheap raw materials.
* Create a sudden demand for products.
* Interrupt supply lines.

All of these will open up new business opportunities for the players to slip into.
> 1 votes

---
Tags: mathematics, game-design, algorithm, economy
---


# Question
Title: Move vector A to vector B but stop X distance before reaching vector B and always be in front
I believe this is basic vector math, but I'm struggling with it.

I have 2 objects (3D space, x, y, z), A (weapon) and B (camera). I want to move A to B's location, but then offset A from B so that it is always in view of the camera.

```
endPosition = objA.worldPosition
startPosition = objB.worldPosition
distance = endPosition - startPosition

objA.worldPosition = distance

```

How do I offset object A so that it will always be an certain distance away from B so it will be in view?

To give you an idea of what I am doing... I have a weapon in the world that the player can click on and inspect to modify from anywhere (no fixed rotation or position). I want to move this weapon closer to the camera so they can turn it around, add attachments etc. Right now the weapon clips into the camera so I need to apply an offset.

# Answer
> 1 votes
You can use the *normalized* `distance` vector (actually a `direction` vector) in order to offset the weapon after moving it on top of the camera. Also, moving the weapon on top of the camera as a first step does not require the `distance` vector itself, you can directly assign the camera position to the weapon.

```
direction = normalize(objA.worldPosition - objB.worldPosition) // get the direction between the camera and the weapon
objA.worldPosition = objB.worldPosition // move the weapon on top of the camera
objA.worldPosition = objA.worldPosition + direction * 10 // 10 is the number of 'units' you want to offset the weapon from the camera, you should decide this via trial and error

```

---
Tags: mathematics, vector
---


# Question
Title: Rotating quaternion smoothly with acceleration and deceleration
I have this code for my linear acceleration and deceleration.

```
var currentSpeed = velocity.translation.z;
var decelerationDistance = ((currentSpeed * currentSpeed) / movementSettings.acceleration) * 0.5f;
if (distanceFromTarget > decelerationDistance)
{
    velocity.translation = float3(0f, 0f, min(currentSpeed + (movementSettings.acceleration * deltaTime), movementSettings.maxSpeed));

}
else
{
    velocity.translation = float3(0f, 0f, max(currentSpeed - (movementSettings.acceleration * deltaTime), 0f));
}

```

Assuming the object is already pointed at the target, this accelerates an object up to its maximum speed at its acceleration rate, and then slows it down by the acceleration rate so that it comes to a stop exactly on the target.

I'd like to have the same behaviour apply to rotation (which is a quaternion). i.e. Assuming the object is stationary, smoothly rotate to a target rotation, obeying acceleration and max rotation speed limits.

I have made a start of converting this code to work on quaternions:

```
private static float Magnitude(Unity.Mathematics.quaternion quat)
{
    return CalculateQuaternionDifference(Unity.Mathematics.quaternion.identity, quat);
}

private static float CalculateQuaternionDifference(Unity.Mathematics.quaternion a, Unity.Mathematics.quaternion b)
{
    float dotProduct = dot(a, b);
    return dotProduct > 0.99999f ? 0f : acos(min(abs(dotProduct), 1f)) * 2f;
}

...

var currentRotSpeed = Magnitude(velocity.rotation);
var rotDecelerationDistance = ((currentRotSpeed * currentRotSpeed) / movementSettings.acceleration) * 0.5f;
if (distance > rotDecelerationDistance)
{
    velocity.rotation = slerp(Unity.Mathematics.quaternion.identity, mul(rotationDiff, velocity.rotation), movementSettings.acceleration);
}
else
{
    velocity.rotation = slerp(Unity.Mathematics.quaternion.identity, mul(inverse(rotationDiff), velocity.rotation), movementSettings.acceleration);
}

```

My questions are:

1. `Unity.Mathematics.math.slerp()` doesn't seem to play well with values of `t` over 1. When `acceleration` and `deltaTime` are low it works, but if they increase too much it breaks in ways I don't understand. How can I multiply a Quaternion by a scalar the same way I multiply the linear acceleration by `deltaTime`.
2. This doesn't follow any max rotational speed limits or stop at 0. What is the equivalent of `min/max()` for a quaternion?
3. `rotationDiff` is the rotational difference between the current orientation and the target orientation. As the current orientation gets closer to the target orientation, this distance gets smaller. I know I should be using some static value instead, but I'm not sure what. Is there a way to normalize `rotationDiff` so it always has a magnitude of 1 radian?

# Answer
For an angular velocity, I think you'll have an easier time expressing it in angle-axis form:

```
Vector3 rotationAxis;
float rotationSpeed;

```

You're still storing just 4 floats, so it's the same weight as a quaternion, just easier to reason about. I'll assume you've chosen your axis so that `rotationSpeed` is non-negative, and that we're working in units of degrees, since that's what Unity's quaternion methods expose.

Then your translation speed code converts quite simply to angular speed:

```
var currentSpeed = velocity.rotationSpeed;
var decelerationDistance = ((currentSpeed * currentSpeed) / movementSettings.acceleration) * 0.5f;

float distanceFromTarget = Quaternion.Angle(currentRotation, targetRotation);

if (distanceFromTarget > decelerationDistance)
{
    velocity.rotationSpeed = min(currentSpeed + (movementSettings.acceleration * deltaTime), movementSettings.maxSpeed);
}
else
{
    velocity.rotationSpeed = max(currentSpeed - (movementSettings.acceleration * deltaTime), 0f);
}

```

You can apply this angular velocity like so:

```
Quaternion travel = Quaternion.AngleAxis(velocity.rotationSpeed * deltaTime, velocity.rotationAxis);

Quaternion newRotation = travel * currentRotation;

```
> 1 votes

# Answer
1. Multiplying a quaternion with a scalar doesn't do anything. To get the double quaternion you will need to multiply it with itself. (then you can slerp with adjusted t to get a quaternion at other locations).
2. the w component follows the cosine of the half angle of the rotation. This means that going from the identity rotation of 0 degrees to full 360 degree rotation the w component changes from 1 to -1 monotonically. So for 2 quaternions rotating along the same axis you can use min on w to select the greater rotation.
3. you can extract the axis out of the quaternion and then pass back into the angle/axis constructor with fixed angle.

```
Vector3 axis = Vector3(rotationDiff.x, rotationDiff.y, rotationDiff.z);
rotationDiff = Quaternion.AngleAxis(1/PI*180, axis);

```
> 0 votes

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


# Question
Title: How to make the Steam overlay work with WPF?
I have developed a game using C#+WPF and the game is currently on Steam (private branch until release). However Steam's overlay isn't working with WPF. Sometimes it tries to appear in the popups of comboboxs.

I've tried several options, the best so far was to render a black screen using SharpGL under my application :

```
<sharpGL:OpenGLControl
            Name="openGLControl"
            DrawFPS="False" RenderContextType="FBO" FrameRate="14"/>
<Grid Name="gridContainingMyApplication">

</Grid>

```

But as you can imagine this decreases the performance of the application and some effects can appear delayed (mouseover for example).

It was not a major concern until now but since we are planning on adding multiplayer we would like to find a way to make Steam's overlay work.

I know that WPF isn't the best option to create games but in our case we thought it would be. We've created a simulation game and since we have a lot of tables/stats/etc. we thought WPF was great, and excepting this overlay issue WPF seems perfect for us.

Is there a way to make Steam's overlay work with WPF ?

Thank you,

# Answer
> 2 votes
It's because WPF only refreshes areas that need updating.

So you can create something transparent that covers the whole window and refresh it repeatedly when `OnGameOverlayActivated` fires to ensure everything gets re-drawn.

For the pop-up, just cover the bottom right corner when the game starts.

---
Tags: c#, steam, wpf
---


title: Lerp performance for camera movement

text:
# Question
Title: Lerp performance for camera movement
In my current script responsible for camera movement, I use `Mathf.Lerp` to smoothly move the camera to the desired position (with WASD movement, panning with MMB, and zooming with the scrollwheel).

However, due to the nature of the Lerp method, I have performance concerns. Does it ever stop calculating the distance and slightly moving the camera towards the location, or do I have to have an if statement that checks if a distance is \< 0.0005f, then stop lerping? If so, which is more performant / better practice?

As a bonus question, I've seen there are other smoothing functions such as `MoveTowards`, `Slerp`, `SmoothDamp`... is there any benefit to using any of those over lerp? My main priority is the camera movement being as performant as possible, and I don't understand how these functions work behind the scenes, despite doing much research.

The entire code to my CameraController is here (the lerping is done in `LateUpdate`): https://pastebin.com/URZhq3MA

# Answer
> 2 votes
All of these functions are simply math functions. When you call them, they do math on the numbers you give them, and give you back a number. Nothing more mysterious than that.

> Does it ever stop calculating the distance and slightly moving the camera towards the location

`Lerp` *never* calculates a distance and it *never* moves your camera.

*Your code* might do those things, and your code calls `Lerp` somewhere in that process. Every time your code calls `Lerp`, it does its work, which is very simple:

```
public static Vector3 Lerp(Vector3 a, Vector3 b, float t)
{
    t = Mathf.Clamp01(t);
    return new Vector3(
        a.x + (b.x - a.x) * t,
        a.y + (b.y - a.y) * t,
        a.z + (b.z - a.z) * t
    );
}

```

You can see there's no distance calculation or branching logic to decide whether it should do anything hiding in there. It's just six addition/subtractions and three multiplications. You'd have to run this millions of times in a frame to measure the cost, it's so cheap.

For one-off scripts like your camera controller, this simply is not something to worry about. You're going to be taking a cache miss when you fetch the camera control script and data from memory anyway, which is already hundreds of times more expensive than this little bit of math. (And your processor might be twiddling its thumbs waiting for the *next* object it needs to arrive in cache, so you might be able to do a significant amount of work here "for free" while you're waiting anyway)

`MoveTowards` and `SmoothDamp` are a little more complicated (you can see their implementations too at the link above), and `Slerp` involves some trigonometry, but they all fall into that "effectively free when you're using them in a one-off script" category.

New coders often think that the way you make a program fast is to make little micro-optimizations to every line, believing that any excess cost adds up / that any minor saving should add up to a significant speed-up, if you do enough of them. Unfortunately that's not how modern computers work. You'll typically be bottlenecked on a few rate-determining steps, like the time it takes to render the frame. Making other parts of your code faster doesn't make the game as a whole run any faster if it's still waiting on those bottlenecks.

So: **always profile first**. Measure what parts of your game are *actually* making it slow, then investigate ways to solve those.

---
Tags: unity, camera, lerp
---


title: track 2D offset after rotation

text:
# Question
Title: track 2D offset after rotation
red is my origin point, blue is my offset, both are 2D vectors, how can calculate blue after rotation?

this is the code I've been trying(just throwing things against a wall to see what sticks)

```
public static Vector2F CalcPointWithRotation(Vector2F origin, Vector2F point, float rotation)
{
    return new Vector2F((float)Math.Cos(rotation) * origin.x, (float)Math.Sin(rotation) * origin.y);
}

```

# Answer
Assuming your `rotation` variable is an angle in radians around your object's `origin` point, and your `point` variable is an offset vector relative to the origin in the object's local coordinate space, then this is simply:

```
public static Vector2F CalcPointWithRotation(Vector2F origin, Vector2F point, float rotation)
{
    float c = (float)Math.Cos(rotation);
    float s = (float)Math.Sin(rotation);

    return new Vector2F(
                        origin.x + c * point.x - s * point.y,
                        origin.y + s * point.x + c * point.y,
    );
}

```

You may recognize this as a matrix multiplication:

$$\vec p ^\prime = \begin{bmatrix} \cos\theta &-\sin\theta\\\sin \theta & cos\theta \end{bmatrix}\vec p + \vec o$$

Or with a homogeneous matrix...

$$\begin{bmatrix}p^\prime\_x \\ p^\prime\_y \\ 1 \end{bmatrix} = \begin{bmatrix} \cos\theta &-\sin\theta & o\_x\\\sin \theta & cos\theta & o\_y \\ 0 & 0 & 1\end{bmatrix} \begin{bmatrix}p\_x \\ p\_y \\ 1 \end{bmatrix}$$

When rotation is 0 (or 2 pi, 4 pi, etc.) then this just gives origin + point. As the rotation value increases, the offset from the origin swings around, tracing a circle around that point.
> 1 votes

---
Tags: mathematics, rotation, transformation
---


# Question
Title: Maintaining facing direction at the end of a movement
I want to make my 2D top-down walking animation stop and revert to the idle animation while continuing to face in the same direction as the previous movement.

For example, when I go up then stop, my character should continue to look up. If I go down, it should continue to look down.

I use `lastmoveX` and `lastmoveY` floats for idle and for walking I use `moveX` and `moveY` floats. `moveX` and `moveY` change when I move with the joystick, but `lastmoveX` and `lastmoveY` do not change, and I don't know how to fix this.

Here is my code:

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

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D myRB;
    private Animator myAnim;
    public Joystick joystick;
    public MoveByTouch controller;

    [SerializeField]
    private float speed;

    // Use this for initialization
    void Start ()
    {
        myRB = GetComponent<Rigidbody2D>();
        myAnim = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update ()
    {
        myRB.velocity = new Vector2(joystick.Horizontal, joystick.Vertical) * speed * Time.deltaTime;

        myAnim.SetFloat("moveX", myRB.velocity.x);
        myAnim.SetFloat("moveY", myRB.velocity.y);

        if(joystick.Horizontal == 1 || joystick.Horizontal == -1 || joystick.Vertical == 1 || joystick.Vertical == -1)
        {
            myAnim.SetFloat("lastMoveX", joystick.Horizontal);
            myAnim.SetFloat("lastMoveY", joystick.Vertical);
        }

    }
}

```

# Answer
My guess is that your joystick is never hitting *exactly* +-1 on either axis. maybe it hits 0.999, which is far enough away that `joystick.Horizontal == 1` would report "false", fail the `if`, and never execute the code that updates the `lastMove` variables. (This is why we have to be careful about comparing floating point numbers for exact equality)

Have you tried making the `if` condition more permissive, to trigger on any non-zero input? Something like this should do decently:

```
void Update ()
{
    myRB.velocity = new Vector2(joystick.Horizontal, joystick.Vertical) * speed;

    myAnim.SetFloat("moveX", myRB.velocity.x);
    myAnim.SetFloat("moveY", myRB.velocity.y);

    if(!Mathf.Approximately(joystick.Horizontal, 0) || !Mathf.Approximately(joystick.Vertical, 0))
    {
        myAnim.SetFloat("lastMoveX", joystick.Horizontal);
        myAnim.SetFloat("lastMoveY", joystick.Vertical);
    }
}

```

(I deleted the `* Time.deltaTime` from your velocity calculation, as it is not appropriate to use there)
> 0 votes

---
Tags: unity, 2d, android, animation, movement
---


# Question
Title: How could I make the character sound beeps like in old school games?
I've been searching around, but I haven't found any resource on how I could achieve this, like those old school character beeps.

I want to have my characters talk with beeps like in Undertale, or Phoenix Wright, or any other games like that, but I've no luck finding anything helpful.

How could I achieve a similar effect?

Edit : Here is an example video of what i mean : https://www.youtube.com/watch?v=V5tX0GyG3\_I When the text goes by, there's that deep beeping sound, that's what i meant

Edit 2 : What i mean is not how i get it to work, but rather how do i make a sound like that using a program?

# Answer
> 3 votes
I think what you're looking for are 8-bit vocal synths, an example of which can be found on the following page:

http://www.freesound.org/people/TheOnlyPKMNmaster/sounds/182332/

Also a comment on the page suggests that http://www.blastbay.com/ produces software that will let you generate your own custom sound files producing this effect.

# Answer
> 0 votes
This sounds like an ideal situation for getting into procedural content.

What you need is relatively simple and doesn't matter if it sounds synthetic. A perfect fit for learning the ropes of procedural audio.

A good program to get into procedural audio with is PureData. It's free, cross-platform and open-source. It uses a graphical flowchart-like system for representing things that's designed with audio in mind.

Andy Farnell's book "Designing Sound" is all about designing procedural sound effects using PureData and includes a decent tutorial on the language (yes, PD is technically a programming language), but more importantly, helps you get a head for figuring out what you need to make a sound.

When it comes to actually getting what you've designed into your game, what you're making here is so simple you could just translate it by hand into C++ or whatever main language you're using. If you get into much more sophisticated procedural sounds later, you'll probably want to consider using a library like libpd to provide an actual PureData implementation in your game and just load in .pd files from disk.

---
Tags: sound-effects, voice
---