# Question
Title: Calculation of distance while switching between two speeds
There are two speed values, that are used by moving object. After a while speed switching occurs from V1 to V2. I need the formula that can be used for calculation of current distance (at specified time).

Input variable:

* T - Current time

Constants:

* V1 - first speed
* V2 - second speed
* Ts - switching time between V1 and V2
* P - switching power

Output variable:

* S = ?

I tried to use next formula: `S = Lerp[Clamp(T / Ts, 0, 1) ^ P), V1, V2] * T`

But in this case the moving object will be returned back after time and moves forward again.

Probably acceleration should be used in the formula?

# Answer
> 2 votes
Rewriting your speed transition formula as

```
float blend = clamp((currentTime - startTime)/transitionDuration), 0, 1);

Vector3 currentVelocity = startVelocity + (endVelocity - startVelocity) * blend;

```

Then during the transition we're applying a constant acceleration of:

```
Vector3 acceleration = (endVelocity - startVelocity) / transitionDuration;

```

Now we can integrate this to get the total displacement from the starting position at time T=0 in three parts.

**First**, for `currentTime <= startTime`,

```
Vector3 currentPosition= startPosition + startVelocity * currentTime;

```

Which at the end of this interval reaches a value of:

```
Vector3 accelerationStartPosition = startPosition + startVelocity * startTime;

```

**Second**, for `startTime < currentTime <= startTime + transitionDuration`, we can use the formula for position under constant acceleration:

$$\vec p(\Delta t) = \vec p\_0 + \vec v\_0 \cdot \Delta t + \frac 1 2 \vec a \cdot \Delta t^2$$

in code:

```
float transitionTime = currentTime - startTime;

currentPosition = accelerationStartPosition
             + startVelocity * transitionTime
             + 0.5f * acceleration * transitionTime*transitionTime;

```

Which we can simplify to:

```
 currentPosition = startPosition + startVelocity * currentTime
            + 0.5f * acceleration * transitionTime*transitionTime;

```

Which again, at the end of the transition interval, takes a value of:

```
float endTime = startTime + transitionDuration;

Vector3 transitionEndPosition = startPosition
               + startVelocity * endTime
               + 0.5f * acceleration * transitionDuration*transitionDuration;

```

**And lastly**, for `currentTime > startTime + transitionDuration`:

```
currentPosition = transitionEndPosition + endVelocity * (currentTime - endTime);

```

---
Tags: mathematics, movement
---


# Question
Title: PlayClipAtPoint() playing multiple times on enemy death
I am having problems with `PLayClipAtPoint()`. I want to play a given sound as soon as a gameObject is destroyed. Here is my code (the concerned parts):

```
void Update()
{
    if (health <= 0)
    {
        StartCoroutine(Death());
    }
}

public IEnumerator Death() {
    anim.SetBool("isDying", true);
    AudioSource.PlayClipAtPoint(dmgSounds[0], transform.position);
    Destroy(gameObject, 3f);

    yield return null;
}

```

I assume that the problem is due to the fact that as soon as the conditions are achieved, in this case the health reaching zero, the coroutine starts and it will keep starting for each frame, but how else should I call it? Anybody has some hint to give?

**EDIT:** I have already tried to wrap the logic in a bool as suggested in the comment so that it would work only when the bool condition is valid, without success. Here is the code with the flag bool:

```
void Update()
{
    if (health <= 0)
    {
        if(isAlive){
            isAlive = false;
            StartCoroutine(Death());
        }
    }
}

```

# Answer
The comment actually gave me another idea which in the end worked. I previously created for other needs a set of states, so I just created another one for the death state and it did the trick!

```
    void Update()
{
    if (health <= 0 && currentState != EnemyState.die )
    {
            StartCoroutine(Death());
        currentState = EnemyState.die;
    }
}

```

I wonder however why it did not work using a simple bool :/
> 0 votes

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


# Question
Title: Could I run two functions inside OnTriggerEnter?
My weapon fire a gameobject "clone bullet" with a script attached on it. There is a part from the script doesn't work. That part is when this "clone bullet" hit object with "enemy" tag, check if this bullet named "rpg)\_bullet(Clone)".

```
    public GameObject Blood_prefab,dust_prefab;

void OnTriggerEnter(Collider bulletv)
{

    if (bulletv.gameObject.CompareTag("enemy"))
    {

        if (gameObject.transform.name == "rpg)_bullet(Clone)")
        {
            // this part doesn't work
            gameObject.GetComponent<Rigidbody>().useGravity = false;
            Instantiate(Blood_prefab, transform.position, transform.rotation);

            foreach (Transform ty in transform)
            {
                if (ty.transform.name == "Heavygun_bullet")
                {
                    Destroy(ty);
                }

                if (ty.transform.name == "Particle_System")
                {
                    ty.transform.position = gameObject.transform.position;
                }

            }

        }
        else
        {
            Destroy(this.gameObject);
            Instantiate(Blood_prefab, transform.position, transform.rotation);
        }

    }

}

```

# Update 1

In case someone looking for a solution for this. I solve it by using One empty object with two childs objects (particleSystem for smoke and bullet shape object). And attach this script on Empty object.

```
    public GameObject Blood_prefab,dust_prefab;
public Transform bullet_shape;
public bool Smoke_Bullet = false;

public void Start()
{
    if (Smoke_Bullet == true)
    {
        foreach (Transform Bullet in gameObject.transform)
        {
            if (Bullet.name == "Heavygun_bullet")
            {
                 bullet_shape = Bullet;
            }
        }
    }
} // End start................

public void Update()
{
    if (Smoke_Bullet == true)
    {
        if ( bullet_shape.gameObject.activeSelf == false)
        {
            Destroy(gameObject, 1); // destroy after 1 second
        }
    }
} // end Update..............

void OnTriggerEnter(Collider bulletv)
{

    if (Smoke_Bullet == false)
    {
        if (bulletv.gameObject.CompareTag("enemy"))
        {

            Destroy(this.gameObject);
            Instantiate(Blood_prefab, transform.position, transform.rotation);

        }
    }
    else
    {
        if (bulletv.gameObject.CompareTag("enemy"))
        {
            gameObject.GetComponent<CapsuleCollider>().isTrigger = false; // use Capsule to fit bullet shape and sphere have bigger radius. For my bullet, Capsule [Radius 3.3,Height 10] Sphere [Raidus 10]. Both triggers are true.
            bullet_shape.gameObject.SetActive(false); // to have time for smoke
            gameObject.GetComponent<Rigidbody>().isKinematic = true; // to stop bullet movement
            Instantiate(Blood_prefab, transform.position, transform.rotation);

        }
    }
}

```

# Answer
Please read Update 1. script...

```
    public GameObject Blood_prefab,dust_prefab;
    public Transform bullet_shape;
    public bool Smoke_Bullet = false;

    public void Start()
{
if (Smoke_Bullet == true)
{
    foreach (Transform Bullet in gameObject.transform)
    {
        if (Bullet.name == "Heavygun_bullet")
        {
             bullet_shape = Bullet;
        }
    }
}
} // End start................

public void Update()
{
if (Smoke_Bullet == true)
{
    if ( bullet_shape.gameObject.activeSelf == false)
    {
        Destroy(gameObject, 1); // destroy after 1 second
    }
}
} // end Update..............

void OnTriggerEnter(Collider bulletv)
{

if (Smoke_Bullet == false)
{
    if (bulletv.gameObject.CompareTag("enemy"))
    {

        Destroy(this.gameObject);
        Instantiate(Blood_prefab, transform.position, transform.rotation);

    }
}
else
{
    if (bulletv.gameObject.CompareTag("enemy"))
    {
        gameObject.GetComponent<CapsuleCollider>().isTrigger = false; // use Capsule to fit bullet shape and sphere have bigger radius. For my bullet, Capsule [Radius 3.3,Height 10] Sphere [Raidus 10]. Both triggers are true.
        bullet_shape.gameObject.SetActive(false); // to have time for smoke
        gameObject.GetComponent<Rigidbody>().isKinematic = true; // to stop bullet movement
        Instantiate(Blood_prefab, transform.position, transform.rotation);

    }
}
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: How to increase the thickness (Size) of a plane in Unity
I am making a small game where you have to roll around and not fall of a platform. I am using a plane to simulate the ground, but it is really thin. Is there a way to make it thicker by increasing a variable?

# Answer
> 2 votes
You can't set thickness to plane because if you add thickness to plane then it will not remain a plan but it will become cube so i will suggest to use cube instead of plane.

If you need more complexity (Tries and vertices) on the cube then you have to create the cube in 3d software like maya, 3ds max, Blinder etc.

---
Tags: unity, graphics
---


# Question
Title: How to prevent a cube from falling through a plane in Unity
I am trying to prevent a player cube from falling through the plane (Battleground) in Unity, but after adding Mesh collider to both the cube and plane, as well as adding a rigidbody, nothing seems to work. The only way I can prevent this from happening is by locking the y axis of the cube, but this is a problem because I am adding in a jumping ability, and the player needs to be able to fall of the map. Is this something I can do within the Unity editor, or do I need to make a script that does that.

To verify, all 3 colliders have "Is Trigger" Enabled, the platform is not designed to be moved, so the X, Y and Z of both the plan's rotation and position are locked, and the material for the colliders are all default. Each of the cubes and the plane's material are custom (Not the collider's material). The X, Y and Z of the cube's rotation are locked. Both cubes have the tag 'player'

The code for player movement is:

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

public class PlayerMove : MonoBehaviour {
    private Rigidbody rb;
    // Use this for initialization
    void Start() {
        rb = GetComponent<Rigidbody>();
    }

    //Update is called once per frame
    void FixedUpdate() {
        float h = Input.GetAxis("Horizontal") * 5;
        float v = Input.GetAxis("Vertical") * 5;

        Vector3 vel = rb.velocity;
        vel.x = h;
        vel.z = v;
        rb.velocity = vel;
    }

}
```

# Answer
Unchecked "Is Trigger". Because it will your object non solid as on the Unity page mentioned:

A trigger doesn't register a collision with an incoming Rigidbody. Instead, it sends OnTriggerEnter, OnTriggerExit and OnTriggerStay message when a rigidbody enters or exits the trigger volume.
> 0 votes

---
Tags: unity
---


# Question
Title: How do I use the keyboard to activate buttons?
I have two buttons on my canvas: **Play** and **Option**. I use arrows to highlight the selected button. If I select any button and press `space` from the keyboard, it should active the button without needing to click on it with mouse.

I have already tried doing so with `if(button_option== EventSystem.current.currentSelectedGameObject) { Debug.Log(" option selected " ); }`, but it simply did not work.

How do I activate buttons using the keyboard?

# Answer
In theory, you shouldn't use a keyboard to activate your buttons. You should use the keyboard to activate *the same methods* as your buttons. You use your buttons to provide direct interface with the actions you want those buttons to represent - why take the extra time to trigger the event through the button, when you can call it directly from your code?

As for *selecting* your buttons, you can handle that as its own event and use code to trigger the "on" or "off" states, as well as determine the correct method to invoke when you hit `space`. I have provided two solutions to achieve this goal; both may involve concepts you are unfamiliar with. If that is the case, ***follow the links and read up on them***. Otherwise, it will be could be much harder to extend the implementation to include more buttons, in the future.

In such form, if you do not intend to offer mouse interaction of the buttons, you should probably remove the `Button` component. The below implementations rely entirely on the `Image` component. If you *do* wish to provide mouse interaction, ensure that the `onClick()` methods you invoke match the methods you invoke for keyboard input. **The below solutions *will not* match the `onClick()` implementations on the same object, unless you ensure they call the same method.**

Both implementations give the following results:

---

## Using a manual `struct` to house your "button" data

In the below implementation, we use the `struct` and `delegate` function to create an array of objects that individually reference an `Image` and the desired method we intend to call when the user presses `space`.

```
using UnityEngine;
using UnityEngine.UI;

public class ButtonHandler : MonoBehaviour
{
    ///<summary>Placeholder delegate function for our buttonList</summary>
    public delegate void ButtonAction();
    ///<summary>Array of buttons, created from a struct, below.</summary>
    public MyButton[] buttonList;
    ///<summary>Index reference to our currently selected button.</summary>
    public int selectedButton = 0;

    void Start()
    {
        // Instantiate buttonList to hold the amount of buttons we are using.
        buttonList = new MyButton[2];
        // Set up the first button, finding the game object based off its name. We also
        // must set the expected onClick method, and should trigger the selected colour.
        buttonList[0].image = GameObject.Find("PlayButton").GetComponent<Image>();
        buttonList[0].image.color = Color.yellow;
        buttonList[0].action = PlayButtonAction;
        // Do the same for the second button. We are also ensuring the image colour is
        // set to our normalColor, to ensure uniformity.
        buttonList[1].image = GameObject.Find("OptionsButton").GetComponent<Image>();
        buttonList[1].image.color = Color.white;
        buttonList[1].action = OptionsButtonAction;
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.LeftArrow))
        {
            MoveToNextButton();
        }
        else if(Input.GetKeyDown(KeyCode.RightArrow))
        {
            MoveToPreviousButton();
        }

        if(Input.GetKeyDown(KeyCode.Space))
        {
            buttonList[selectedButton].action();
        }
    }

    void MoveToNextButton()
    {
        // Reset the currently selected button to the default colour.
        buttonList[selectedButton].image.color = Color.white;
        // Increment our selected button index by 1.
        selectedButton++;
        // Check that our new index does not move outside of our array.
        if(selectedButton >= buttonList.Length)
        {
            // If you want to reset to the first button, reset the index.
            selectedButton = 0;
            // If you do not, simply move it back by 1, instead.
        }
        // Set the currently selected button to the "selected" colour.
        buttonList[selectedButton].image.color = Color.yellow;
    }

    void MoveToPreviousButton()
    {
        // Should be self explanatory; similar in function to MoveToNextButton,
        // but instead, we are moving back a button.
        buttonList[selectedButton].image.color = Color.white;
        selectedButton--;
        if(selectedButton < 0)
        {
            selectedButton = (buttonList.Length - 1);
        }
        buttonList[selectedButton].image.color = Color.yellow;
    }

    ///<summary>This is the method that will call when selecting "Play".</summary>
    void PlayButtonAction()
    {
        Debug.Log("Play");
    }

    ///<summary>This is the method that will call when selecting "Options".</summary>
    void OptionsButtonAction()
    {
        Debug.Log("Options");
    }

    ///<summary>A struct to represent individual buttons. This makes it easier to wrap
    /// the required variables into a single container. Don't forget
    /// [System.Serializable], if you wish to see your final array in the inspector.
    [System.Serializable]
    public struct MyButton
    {
        /// <summary>The image contained in the button.</summary>
        public Image image;
        /// <summary>The delegate method to invoke on action.</summary>
        public ButtonAction action;
    }
}

```

## Using an automatically generated array to broadcast method calls

A simpler, less controlled way to reach similar functionality is with the simple use of `this.BroadcastMessage()`. This option gives greater flexibility, as you do not need to manually provide the details of each button, nor the specific location of each "button action".

This comes with two specific requirements1. First and foremost, the script *must* be on a game object that has your `Canvas` component as its child. Secondly, all "button actions" must *also* be accessible within the object holding your script and its children. They can attached as individual scripts to the actual buttons, they can be in a seperate "button actions" script attached to the `Canvas` object, or they can even be in the same script (as seen in the example). It doesn't really matter.

For the below example, we use the name of the "button" object. A button with the object name of "Play" will invoke `PlayAction()`. A button with the object name of "Options" will invoke `OptionsAction()`.

```
using UnityEngine;
using UnityEngine.UI;

public class ButtonHandler : MonoBehaviour
{
    public int selectedButton = 0;
    public Image[] buttonList;

    void Start()
    {
        buttonList = GetComponentsInChildren<Image>();
        buttonList[0].color = Color.yellow;
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.LeftArrow))
        {
            MoveToNextButton();
        }
        else if(Input.GetKeyDown(KeyCode.RightArrow))
        {
            MoveToPreviousButton();
        }

        if(Input.GetKeyDown(KeyCode.Space))
        {
            this.BroadcastMessage(buttonList[selectedButton].name + "Action");
        }
    }

    /// <summary>Identical to first example.</summary>
    void MoveToNextButton() {...}

    /// <summary>Identical to first example.</summary>
    void MoveToPreviousButton() {...}

    /// <summary>Will call when user selects "PlayButton".</summary>
    void PlayButtonAction() {...}

    /// <summary>Will call when user selects "OptionsButton"</summary>
    void OptionsButtonAction() {...}
}

```

1 It should be addressed that these are only requirements due to the way I have implemented it in the example. I feel this is the most suitable implementation for the context.
> 3 votes

# Answer
so here are quick setup that doesn't need additional programming and everyone (like designers) can change it for the sake of project:

* first of all OnClick event will call whether you are touching or clicking or pressing a key on the keyboard (EventSystem will look at 'Submit' key in the input manager for that)
* second, the first one explained everything. just set the 'Cancel' and 'Submit' button in the input manager (It is set up by default) you can use 'First Selected' in the EventSystem to select a button by default and that's pretty much it, use your submit key to press the button and OnClick event to call your events
> 2 votes

---
Tags: unity, gui
---


title: Mapping a Texture to a 2d Quadrilateral

text:
# Question
Title: Mapping a Texture to a 2d Quadrilateral
I want to map a 2d picture onto an arbitrary 2d quadrilateral, for the purpose of particle system. To do that, I split the picture into two triangles, and then linearly interpolated u,v along the triangle edges, using the following code:

```
struct tlerp {
  double x,i;
  double u,v;
  double ui,vi;
} tlerp;

void tlerp_init(tlerp *l
                      , double first_step, double steps
                      , double sx, double ex
                      , double su, double eu
                      , double sv, double ev) {
  l->i  = (ex - sx) / steps;
  l->ui = (eu - su) / steps;
  l->vi = (ev - sv) / steps;
  l->x = sx + first_step*l->i;
  l->u = su + first_step*l->ui;
  l->v = sv + first_step*l->vi;
}

void tlerp_advance(tlerp *l) {
  l->x += l->i;
  l->u += l->ui;
  l->v += l->vi;
}

```

But the result is garbled. My guess is that linear interpolation can't be used here, because the space inside quadrilateral is obviously non-linear (on the attached picture it gets more compressed the closer it gets to the top). Is there some way to make it linear again?

As always, I'm not using an OpenGL/DirectX, so can't use any built-in solution.

# Answer
> 1 votes
I've solved the problem by following DMGregory's suggestion to introduce this imaginary Z, which I calculated based on distances between quad vertices. Here is a basic C code, because many people seems struggle getting it right, it is like most common pitfall of 2d and 3d graphics:

```
//usual euclidean distance
float distance(int ax, int ay, int bx, int by) {
  int x = ax-bx;
  int y = ay-by;
  return sqrtf((float)(x*x + y*y));
}

void gfx_quad(gfx_t *dst //destination texture, we are rendering into
             ,gfx_t *src //source texture
             ,int *quad  // quadrilateral vertices
             )
{
  int *v = quad; //quad vertices
  float z = 20.0;
  float top = distance(v[0],v[1],v[2],v[3]); //top
  float bot = distance(v[4],v[5],v[6],v[7]); //bottom
  float lft = distance(v[0],v[1],v[4],v[5]); //left
  float rgt = distance(v[2],v[3],v[6],v[7]); //right

  // By default all vertices lie on the screen plane
  float az = 1.0;
  float bz = 1.0;
  float cz = 1.0;
  float dz = 1.0;

  // Move Z from screen, if based on distance ratios.
  if (top<bot) {
    az *= top/bot;
    bz *= top/bot;
  } else {
    cz *= bot/top;
    dz *= bot/top;
  }

  if (lft<rgt) {
    az *= lft/rgt;
    cz *= lft/rgt;
  } else {
    bz *= rgt/lft;
    dz *= rgt/lft;
  }

  // draw our quad as two textured triangles
  gfx_textured(dst, src
              , v[0],v[1],az, v[2],v[3],bz, v[4],v[5],cz
              , 0.0,0.0,      1.0,0.0,      0.0,1.0);
  gfx_textured(dst, src
              , v[2],v[3],bz, v[4],v[5],cz, v[6],v[7],dz
              , 1.0,0.0,      0.0,1.0,      1.0,1.0);
}

```

---
Tags: mathematics, graphics, graphics-programming
---


# Question
Title: Character Controller pulling Table in Unity Engine
I have setup a scene with one GameObject that has CharacterController component (Player) and another one Cube that represents Table with RigidBody and BoxCollider components.

Now, when I get close to this table I can press E and grab the table. Now I can pull or push table. What I do is when I press E key on keyboard I just attach this "table" to the Player gameobject with `table.transform.SetParent(player.transform);` Everything works great except when I add second cube that should prevent table to be moved any further.

As you can see, if I pull table in the direction of the arrow at some point, table will collide with blue cube. However, if I keep pressing `S` (for backward movement), player will continue to move, but table will not be moving (because I froze rotation on table's rigidbody component intentionally). What I want is to prevent player movement if the object that is currently being pushed or pulled cannot move any further...

Any ideas how to accomplish this?

**EDIT:**

```
public void PlayerMovement()
{
    float horizontal = Input.GetAxis("Horizontal") * MovementSpeed;
    float vertical = Input.GetAxis("Vertical") * MovementSpeed;

    if (_isMovingObject)
    {
        horizontal = 0f;
        float ppoDistance = Vector3.Distance(transform.position, _pushPullObject.transform.position);
        float diffDistance = ppoDistance - _pushPullObjectDistance;

        // distance between object and player is greater than at the start meaning pulling object
        // bumped into collider while pulling backward, but we are now trying to move forward
        // so wee need to restore diffDistance to 0
        if (diffDistance > 0.001f && vertical > 0f)
        {
            //transform.position += transform.forward * diffDistance;
            _pushPullObject.transform.position -= transform.forward * diffDistance;
        }

        // same thing but move backward after hitting obsticle while moving forward
        if (diffDistance < -0.001f && vertical < 0f)
        {
            //transform.position -= transform.forward * diffDistance;
            _pushPullObject.transform.position += transform.forward * diffDistance;

        }

        // stop backward movement if we hit something with pulling object
        if (diffDistance > 0.001f && vertical < 0f)
            vertical = 0f;

        // stop forward movement if we hit something with pull/push object
        if (diffDistance < -0.001f && vertical > 0f)
            vertical = 0f;
    }

    Vector3 forwardMovement = transform.forward * vertical;
    Vector3 rightMovement = transform.right * horizontal;

    characterController.SimpleMove(forwardMovement + rightMovement);
}

```

This is what I came up with. I calculate original distance at the time of parenting table to Player object, then I keep track if that distance changed...

# Answer
> -1 votes
**Problem:**
As it seems, your player as well as your table have each a rigidbody.
That means, that even though the table is part of player, it can move in local space, thus allow the player to move independendly.

**Solution:**
You can fix that relatively easy by removing the rigidbody from the table as soon as the player takes a hold of it.
Then the physics engine will recognize the table to be a part of the player's collider, thus any table collision will be in fact a player collision.

**Note:**
It's recommended not to move a rigidbody via transform.position = \[...\].
Instead use rigidbody.position to change the position.
See the API for more information.

---
Tags: unity, character, rigidbody
---


# Question
Title: How do you turn off all scene lighting in the game view like you would with the scene view button?
In the scene view, there's a control bar with a 'lighting' button that lets you toggle scene view lighting. This turns off all shadows and all light sources, i.e. makes it so that all objects are seen as fully bright on all sides. How do I do the same for the game view?

# Answer
> 1 votes
The scene lightning button doesn't just disable scene lights, it activates another lighting mode or adds hidden lights to the scene.
If you would just turn of all lights, all objects would apear black.

I don't know how exactly the scene is illuminated while the lights are off in the scene view.
According to this (very old) post, the scene lighting is done with a directional light that is parented to the camera.
It's about 0.75 itensity and of gray color.
It looks the same way as the camera.

The scene lighting might have changed, as that post is from 2008.

**Another way how to do it:**
Blender does something similar.
It adds 4 lights to the scene and attaches them to the scene camera.
This adds some more smoothing to the light while still giving a sense of shading and direction.

Screenshot of Blender settings for the scene lighting.

---
Tags: unity, lighting
---


# Question
Title: How do I position a mesh just outside the camera view?
I want to slide in an object into view, coming from the right of the screen.

In order to achieve this, I need to position the object next to the camera view, so that it is still not visible, but close enough for a quick slide in.

For example, placing the object at X=1000000 (so that it is surely outside the camera view) for safety wouldn't work as it couldn't slide in quickly enough. For a reasonable slide, I would need to have it really close next to the camera view.

How could I calculate the object's position for that?

Thank you.

Edit:

Here is the script that I'm now using and which I'm still having problems with:

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

public class NewBehaviourScript : MonoBehaviour
{
    void Update()
    {
        float fDist = Mathf.Abs(Camera.main.transform.position.z - this.transform.position.z);
        Bounds b = BoundsFromTransform(this.transform);

        this.transform.position = GetPointLeftOfCamera(Camera.main, fDist, b.size.magnitude / 2);
    }

    public static Bounds BoundsFromTransform(Transform uTransform)
    {

        Bounds bounds = new Bounds(uTransform.position, Vector3.zero);

        foreach (Renderer renderer in uTransform.GetComponentsInChildren<Renderer>())
        {
            bounds.Encapsulate(renderer.bounds);
        }

        Vector3 nOff = bounds.center - uTransform.position;

        return new Bounds(nOff, bounds.size);
    }
    public static Vector3 GetPointLeftOfCamera(Camera camera, float distance, float goDiameter)
    {
        // 1.
        var ray = camera.ScreenPointToRay(new Vector3(0, camera.pixelHeight / 2f, 0));

        // 2.
        var borderPoint = ray.GetPoint(distance);

        // 3.
        var leftPlane = GeometryUtility.CalculateFrustumPlanes(camera)[0];
        var frustumLeft = leftPlane.normal;

        // 4.
        var halfDiameter = goDiameter / 2f;
        return borderPoint + frustumLeft * halfDiameter;
    }
    public static Vector3 GetPointRightOfCamera(Camera camera, float distance, float goDiameter)
    {
        var ray = camera.ScreenPointToRay(new Vector3(camera.pixelWidth - 1, camera.pixelHeight / 2f, 0));
        var borderPoint = ray.GetPoint(distance);

        var rightPlane = GeometryUtility.CalculateFrustumPlanes(camera)[1];
        var frustumRight = rightPlane.normal;

        var halfDiameter = goDiameter / 2f;
        return borderPoint + frustumRight * halfDiameter;
    }
}

```

# Answer
> 1 votes
You could do that using Camera.ScreenPointToRay() like this:

1. Get the camera ray of the left/right most edge at the desired height.
2. Then from that ray, take the point at the desired distance.
3. Get the plane normal for the left/right camera frustum plane
4. From that point, move to the left/right by half the renderer diameter.

If you place your object that that end point, it is just out of view, at a desired distance and near the edge of your camera frustum.

**Code example:**

```
public static Vector3 PlaceOutsideFrustum(this Camera camera, Bounds bounds, float distance, bool left)
{
    var frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
    Ray ray;
    Plane plane;

    if (left)
    {
        // 1.
        ray = camera.ScreenPointToRay(new Vector3(0, camera.pixelHeight / 2f, 0));
        plane = frustumPlanes[0];
    }
    else
    {
        ray = camera.ScreenPointToRay(new Vector3(camera.pixelWidth - 1, camera.pixelHeight / 2f, 0));
        plane = frustumPlanes[1];
    }

    // 2.
    var borderPoint = ray.GetPoint(distance);

    // 3.
    var frustumOutside = -plane.normal;

    // 4.
    var halfDiameter = bounds.size.magnitude / 2f;
    return borderPoint + frustumOutside * halfDiameter;
}

```

**Usage example:**

```
[RequireComponent(typeof(Renderer))]
public class PlaceOutsideCamera : MonoBehaviour
{
    public bool left = true;
    public float distance = 20f;
    public Camera camera;

    void OnEnable()
    {
        if (camera == null)
        {
            return;
        }

        var myRenderer = this.GetComponent<Renderer>();
        var bounds = myRenderer.bounds;
        this.transform.position = camera.PlaceOutsideFrustum(bounds, distance, left);
    }
}

```

**Note:**
Keep in mind, the goDiameter is the magnitude of the object renderer (mesh diameter in world space).
Also the object won't be directly touching the border of the camera frustum, as I approximated the mesh to a sphere by using the goDiameter.

If you need more precision, you can still use the same approach and replace the diameter offset calculation with your own.

**Note 2:**
The distance is not exact.
Because of the offset along the frustum left/right vector, the distance between the camera and the object is slightly larger than the distance passed to the method.
If that is a problem, one can fix that by normalizing the direction vector and scaling it to the desired length:

```
[...]
var position = camera.PlaceOutsideFrustum(bounds, distance, true);
var direction = (position - camera.transform.position).normalized;
this.transform.position = camera.transform.position + direction * distance;

```

# Answer
> 0 votes
You would need to place the object just outside the camera's view frustum.

There are many ways to get frustum info. You can see here for one method with the Unity API.

# Answer
> 0 votes
You could add an "ObjectSpawner" game object as a child of your camera and place it slightly outside of the field of view of the camera. When the camera moves or rotates, so will your object spawner.

The object spawner would be pretty standard: Instantiate a prefab at its own world position and with its own world rotation.

---
Tags: unity
---


# Question
Title: Is it possible to have vehicles with physics like GTA in an MMO game?
I haven't seen any MMO games with vehicles with realistic physics and that could achieve high speed, why? Is it because of network bandwidth limitations?

Second Life has vehicles, but physics are poor and max speed is pathetic.

# Answer
Yes and no (but mostly, no).

Any MMO game has several limitations that affect its physics. The most important of these is *latency*. Latency is time it takes a client to send a request to server and receive an answer back. Even in very best circumstances, this time is around 50-100 milliseconds. In real world, it can be as high as 500 ms. This means, that whenever a players does something - like, say, turns his car's wheel - he can see the game react to it only 100-500 ms later.

100 ms is actually quite a lot. Any game that has as much latency will feel unresponsive, and 500 ms feels downright unplayable. That's why game clients employ a lot of tricks to mask this latency. For example, the player's car can begin turning the moment he turns the wheel, without waiting for the server. However, these tricks only *mask* latency, and can never actually reduce it.

Suppose, for example, that we have *two* players in cars steering simultaneously towards one another. Each client will start turning its *own* car immediately; but the *other* player's car will not turn - because the information of it changing course has not yet reached the client, because of latency. Both players happily steer theirs cars, and then bam! - the server notices that they actually crashed into each other.

Situations like this cannot be prevented. No matter what clever prediction schemes we use, where there are other players, there's always a chance for things to go wrong. In any MMO game, about half a second that you just saw *hasn't really happened yet*, and can change in any moment. Now, in slower-paced games like traditional MMORPG's, half a second is not really that long. Characters only move maybe a meter or two during this time. However, if we're talking about fast-paced car race, half a second is a really long time! You could crash, like, three times in half a second (-8

Actually, a fast-paced game can work even with these limitations. It would have some unpleasant moments, but as long as all players have good connections, it would be playable. That's how multiplayer racing games work. However, there's another MMO limitation: the N-squared update count.

Imagine 10 players playing simultaneously. For them to see each other, the server has to send every player information about every other player. This means, in our example, 10x10 = 100 pieces of information to prepare and send. That's the number of players squared, hence "N-squared". This number grows quite fast, and even traditional MMORPG's begin to struggle when there are lots of players in the same area. For our imaginary fast-paced game with cars, these pieces of information have to be sent much faster than in a slower game. AND they probably are bigger themselves - you have se send not only positions, but velocities, acceleration, angular velocities etc. This means that any fast multi-player game can only have a limited number of players.

Both above problems *cannot* in principle be solved by software, only masked to some extent. They can be reduced a bit by limiting number of players - so, for example, a game where fast cars are only used in instances with limited number of players is probably doable. I believe that's what APB did. But a full open-world MMO game with fast cars is just not gonna happen. Not until we have quantum-entaglement network interfaces or something.
> 19 votes

# Answer
Yes.

You have to deal with network latency and syncing the game state across the network. The faster the cars move the more notable the network latency becomes. Players might crash into a wall, because their game client fails to update the game state on the server due to network issues. Which isn't an issue when players move at walk speed ;-)

An MMO server has more load. A multiplayer racing game might run fine with 10 people connected, but will crash and burn if the server gets unresponsive under heavy load from hundreds of users.

Second Life's vehicle physics are just badly implemented. (Is this still alive?)
> 3 votes

# Answer
Garry's Mod is pretty much all physics. I don't think it counts as an MMO as such - though it will support 32 players per server - and that has the most realistic physics I've seen (not just vehicles).

I guess that there hasn't been an MMO designed with physics in mind.
> 2 votes

# Answer
They tried to accomplish this in a major fail of a game called all points bulletin. Well the concept was great the execution not so much. Random cars would appear out of nowhere. You would be driving and just hit a wall which would then turn into a car. I can see it being done somehow in the next five years though more cpu less gpu.
> 1 votes

# Answer
Let's look at your reference first.

GTA itself has a few problems with multiplayer, but this is to be expected. An example is when latency turns your car chase into a nightmare. Sometimes players kill each other because of the latency.

But latency is not the only problem, you can not run an MMO only with clients, you need servers and these servers have to manage most if not all of the physics to avoid cheaters.

So imagine having to run with thousands of players. Imagine also the stress on the CPUs during physics intensive activities. You can offset a chunk of the stress to dedicated GPUs. Bullet Physics has an implementation that runs on CPU.

But to avoid overload in a server you will need to implement a mechanism to handle dynamic zones redefinitions depending on players density. It is much more important in that case than in other MMOs.

It is doable. The issue here is the need to scale the game to handle more players and to run the main instance of the game distributed across servers.

If you manage to optimize your physics, transfer objects quickly and efficiently across servers and find a way to avoid mega crowds (instances for example), then you can do it with similar limitations as your reference and a few other ones due to the MMO nature of the game.

Remember that you don't have to send all game state updates to all players all the time, just the changes that are immediately relevant to the player should be sent constantly, the rest can be sent at a lower rate.
> 0 votes

# Answer
check gta 5 rage mp mode, russian red age or FiveStar roleplay have about at maximum 1200 up to 1600 players at single server, pretty impressive, yet they are trying ot add back AI traffic with version 0.4
> 0 votes

---
Tags: physics, mmo
---


title: Auto key bones with controller helpers

text:
# Question
Title: Auto key bones with controller helpers
I have skinned and rigged a human character with IK / FK and helper objects to control the position of the IK goals and the rotation of the bones. For example, the characters' left arm IK goal is parented to a point helper, to make it easier to select and move around and the arm IK solves accordingly.

I have the skeleton (without the helpers) set up as an avatar in Unity and I want to use this rig to create and export animations to work with the avatar.

I create animations by moving the helpers in Auto Key mode in 3DS Max, so that when the helpers move, their new transform details (pos, rot, scale) are recorded in key frames.

My questions is this: using Auto Key only records the transform of the helpers I'm moving, it does not record the bone transforms, even though they have been changed by moving the linked helpers. Is there any way to record bone positions using Auto Key with this rigging method, or do I have to select the affected bones every time a movement is made and use Set Key?

# Answer
> 1 votes
Found the answer - bake the animation when exporting as fbx. This includes the movement of the bones even if they were not keyframed.

Select all bones \> Export Selected, under Animation, tick Bake.

---
Tags: unity, animation, 3dsmax, rigging
---


title: How to add a bolt into my unity project

text:
# Question
Title: How to add a bolt into my unity project
In my game, one of the character you pick as a special ability called the dash. It allows the player to quickly move forward. Included below is the code. It just throws up a bunch of errors. This is a 3d scene

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

public class PlayerJump : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
        {
            if (Input.GetKeyDown("q"))
            {
                transform.Translate(Vector3.KeyDirection * 260 * Time.deltaTime, Space.World);
            }

        }
    }
```
</code></pre>

# Answer
**Vector3** does not have a **keyDirection** property, so that is the main error.

Replace this code in your Update method:

```
if(Input.GetKey(KeyCode.Q))
{
    transform.Translate(0.1f,0,0);
}

```
> 1 votes

---
Tags: unity
---


title: Using ECS in a custom Unity package

text:
# Question
Title: Using ECS in a custom Unity package
I have built a custom package for Unity called `world-renderer`. This is the folder structure.

Inside "Runtime" is all my source code. To use it inside a Unity project, I add this line into the `manifest.json` of that project.

```
"com.tamagames.extinction.word-renderer": "file:C:/Users/dbugger/projects/unity/world-renderer",

```

This has worked great so far, but now I want to start using ECS inside my custom package. so I add its namespace to one of the files:

```
using Unity.Entities;

```

and now when I return to the Unity Editor, I see the following error message:

> CS0234: The type or namespace name 'Entities' does not exist in the namespace 'Unity' (are you missing an assembly reference?)

I figured I needed to add the dependency to the `package.json` of my custom package, so I wrote updated it like this:

```
{
  "name": "com.tamagames.extinction.word-renderer",
  "version": "1.0.4",
  "displayName": "Extinction - World renderer",
  "description": "World renderer for Extinction",
  "unity": "2019.1",
  "unityRelease": "0b5",
  "keywords": [],
  "dependencies": {
    "com.unity.entities": "0.1.1-preview" // Dependency added
 },
  "author": {
    "name": "Enrique Moreno Tent",
    "email": "enriquemorenotent@gmail.com",
    "url": "https://enriquemorenotent.com"
  }
}

```

But I still keep getting the same error.

What am I doing wrong?

**UPDATE**

I try adding the reference to the Assembly of my package, like this:

```
{
    "name": "Unity.com.tamagames.extinction.world-renderer-ecs",
    "optionalUnityReferences": ["com.unity.entities"],
    "includePlatforms": [],
    "excludePlatforms": [],
    "allowUnsafeCode": false,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": [],
    "versionDefines": []
}

```

That did solve the problem with "Unity.Entities" not found, but now, in the Unity Project, the classes inside my source code cannot be found!

# Answer
Well, I got it to work.

First of all, I should not have used `optionalUnityReferences`, but `references`.

But the big mistake is that, event though the dependency in the `package.json` is called `com.unity.entities`, the one in the Assembly file should have been called `Unity.Entities`.
> 3 votes

# Answer
I've replicated your problem, and think that I know what causes it.

When you have a package, it needs to be in the Packages folder.
This folder is next (not in) the Assets folder.
Only then, Unity will recognize your package as such and try to fix missing dependencies.

There are multiple ways how to import packages:

* Simply move the package folder to the Packages folder
* In the packages manager, click the small + sign in the top left and select your package.json file.

As long as you are actively developing the package, it might be usefull to keep it in the assets folder.
To resolve the Entities issue, you can manually add the package using the package manager.
Later, when you give the package to other people (asset store, github, whatever) make sure they import it correctly.
Then the dependencies should be resolved by Unity.
> 0 votes

---
Tags: unity
---


# Question
Title: How do I replace the enemy with a different graphic when it gets hit?
I am able to draw my space ship and a an enemy (called "bug\_one" in the code below) and move my bullet. When the bullet hits the enemy, it draws a collision bmp.

But currently my code draws both the collision bmp and the enemy bmp after the enemy got hit.

What I want instead is that after the bullet hits the enemy, to no longer draw the enemy bmp and draw the collision bmp instead. I'd like also the collision bmp to disappear after some time. here is my reworked code

```
        bool draw_flag_coll = false;
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.Clear(Color.Black);
        e.Graphics.DrawImage(ship, 350 + x, 530);
        e.Graphics.DrawImage(bullet, 375 + x, 520 + y);
        e.Graphics.DrawImage(bug_one, 350, 0);
        if(draw_flag_coll==true)
        {
            e.Graphics.DrawImage(coll, 350, 0);
        }
    }
    int count = 0;
    private void timer2_Tick(object sender, EventArgs e)
    {
        if (y <= -510 && x >= -15 && x <= 15)
        {
            draw_flag_coll = true;
            count++;
            if(count == 100)
            {
                this.Invalidate(true);
                count = 0;
            }
        }
    }

```

# Answer
> 1 votes
Well the solution can be quite simple, you already used it to draw the collision image when the bullet hits. This is one approach, just do everything with if else cases, its not the best way to go though. For example:

```
if(draw_flag_coll==true){
   e.Graphics.DrawImage(coll, 350, 0);
}else{
   e.Graphics.DrawImage(ship, 350 + x, 530);
}

```

For this solution you would need to delete the line e.Graphics.DrawImage(ship, 350 + x, 530); above and place it inside the 'else' part of your if/else structure.

This has 2 downsides. First of all your parameter values for the Coll image call are hard coded, it would always be drawn on the same spot. The other downside is the concept itself. Imagine you will add more animations (turning, casting shield etc). You would need many if/else structures, stacked into each other and so on.

I think a better approach is giving the ship an animation Object (current Animation) this animation has a timer controlling /looping the animation. you would always update this one animation, but switch it with different animations as you need. This involves just little work but grants high reusability and good code overview. You would at least need one extra class (animation) that describes how an animation works with different variables like number of frames, eventually adjustable, a texture image object (sprite sheet) which represents the used images, methods to start the animation, adjust time of a timer etc.

Then you could set the players current animation to an animation instance which you instantiate with your ship image. Upon game start you prepare an array of other animations with their corresponding images. When collision occurs you could do something like:

player.setCurrentAnimation(collisonAnimation);

still you would have to figure out how to return to an other animation when the currently one is not looped (like collision animation). But it should not be hard and there are many ways to do so.

# Answer
> 0 votes
Sorry just joined so I can't post as a comment.

You error most likely lies outside of the code you posted. You are using an if-else statement, so none of these three images can be drawn at the same time.

```
    if (draw_flag_bug == true)
    {
        e.Graphics.DrawImage(bug_one, 350, 0);
    }
    else if (draw_flag_coll == true)
    {
        e.Graphics.DrawImage(coll, 350, 0);
    }
    else if(draw_flag_bug == false)
    {
        e.Graphics.DrawImage(black, 350, 0);
    }

```

My best bet is your error comes from having multiple instances of the object. Try to print out the value of draw\_flag\_bug just before e.Graphics.Clear(Color.Black); I think you might find that both values will be printed.

Could you please provide some more code, otherwise it is hard to pinpoint the exact issue.

---
Tags: c#, windows-forms
---


# Question
Title: How do I make an image appear based on the current state I'm in?
I am following a tutorial called Complete C# Unity Developer 2D: Learn to Code Making Games. In one section we create a text-based game, where we display a canvas with some UI elements to the user. The text changes based on the current state, which is setup through a couple of scripts. Just for future knowledge (it isn't part of the tutorial), I want to make an image display for each state.

Before I post the scripts, here is what I have tried: 1) I serialized a Sprite field in one of the scripts so that I could assign a .jpg asset sprite to it. At that point I was not sure how to get it to appear based on the state, which is an array of states. 2) I created a UI Image and added it to the canvas, then disabled it. My intent here was to enable it when the state.name == x. Unfortunately, I can't seem to get that to work either.

I am using two scripts, 1) AdventureGame.cs & 2) State.cs:

1) AdventureGame.cs

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

public class AdventureGame : MonoBehaviour
{
    [SerializeField]
    Text m_textComponent;
    [SerializeField]
    State startingState;
    // I added this Sprite field
    [SerializeField]
    Sprite m_spriteComponent;

    State state;

    void Start()
    {
        state = startingState;
        m_textComponent.text = state.GetStateStory();
        // This is what I added, a call to a method in the other script
        m_spriteComponent = state.GetStateSprite();
        Debug.Log(m_spriteComponent);
        // The sprite is called HellDoor
    }

    void Update()
    {
        ManageState();
    }

    private void ManageState()
    {
        var nextStates = state.GetNextStates();
        for (int index = 0; index < nextStates.Length; index++)
        {
            if (Input.GetKeyDown(KeyCode.Alpha1 + index))
            {
                state = nextStates[index];
            }
            m_textComponent.text = state.GetStateStory();

        }
        // Tested for state name to be sure, Door is one of them

        Debug.Log(state.name);
        if (state.name == "Door")
        {
            // Not sure what to put here
        }

    }

}

```

2) State.cs

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

// Creates a new slot called State in the Create menu!
[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject
{
    // First number determines minimum size of the field, and the second number
    // determines the amount of lines before you start to scroll
    [TextArea(10, 14)]
    [SerializeField]
    string m_storyText;
    [SerializeField]
    State[] nextStates;
    // This is the field I added
    [SerializeField]
    Sprite m_stateSprite;

    public string GetStateStory()
    {
        return m_storyText;
    }

    public State[] GetNextStates()
    {
        return nextStates;
    }
    // This is the method I added
    public Sprite GetStateSprite()
    {
        return m_stateSprite;
    }
}

```

Additionally, this is what I have setup in the editor.

# Answer
I am not familiar with unity but as far as I can see you only call m\_spriteComponent = state.GetStateSprite(); inside the create Method.

When is the current state drawn ( where do you find it in code ) ? Make sure the variable and everything that goes with it is set accordingly when you register touch down events.

Also I wonder about the array of states. Where is it initialized? But maybe I am wrong about this and it is handled by unity.
> 0 votes

---
Tags: unity, c#, image, state, ui-design
---


# Question
Title: How to temporarily increase the speed of a character in a Unity game
As the title would suggest, I want to give a character a speed boost for x amount of seconds, while increasing their Gameobject's mass. During this little speed boost, I also want to add a script to another player that disappears when the speed boost dies out I am new to C#, and Unity in general, any help would be appreciated.

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

public class PlayerAddMass : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Q))
        {
            rb = GetComponent<Rigidbody>();
            rb.mass = 10;
            rb = GetComponent<Rigidbody>();
            rb.speed = 5;
        }
    }
}

```

The code above was found on a unity website of some sorts, and I modified it to set the speed and mass numbers (I changed the 0s into a 10 and a 5) The errors I get are "rb does not exist in the current context" x 4

# Answer
> 0 votes
I created a quick test for boosting player speed.

When your player is moving and you press "B" player speed will be boosted for "boostTime " with the speed of "boostIncrease". I hope it works for you.

You just attach the script to the player and you are ready to go. By the way using "GetComponent" in update is not a good idea so pleas avoid it as much as possible.

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

    [RequireComponent(typeof(Rigidbody))]
    public class TemporarySpeedBoost : MonoBehaviour
    {
        [SerializeField] private Rigidbody rb;

        [Header("Player movement Settings")]
        [SerializeField] private float steadySpeed = 5.0f;

        [Space(10)]
        [SerializeField] private float boostIncrease = 5.0f;
        [SerializeField] private float boostTime = 10.0f;

        private bool isBoostActivated = false;

        void Start()
        {
            if (rb == null)
            {
                rb = GetComponent<Rigidbody>();
            }
        }

        void Update()
        {
            if (Input.GetKey(KeyCode.Q))
            {
                rb.mass = 10;
                if (isBoostActivated)
                {
                    rb.velocity = transform.forward * (steadySpeed + boostIncrease);
                }
                else
                {
                    rb.velocity = transform.forward * steadySpeed;
                }
            }

            if (Input.GetKey(KeyCode.B))
            {
                if (!isBoostActivated)
                {
                    Debug.Log("Boosting player speed");
                    isBoostActivated = true;
                    Invoke("EndBoost", boostTime);
                }
            }
            Debug.Log(rb.velocity);
        }

        private void EndBoost()
        {
            isBoostActivated = false;
        }
    }

```

---
Tags: unity
---


# Question
Title: Prevent VS Code opening the Unity scripts twice
Is it possible to prevent VS Code opening the Unity scripts twice?

E.g. I opened Unity project, double clicked a script and got my project (Assets folder) opened in VS Code, now I go to Unity make a few changes and open another script file. The script file opens another instance of the VS Code. I would like to have the file opened in the currently opened instance instead of opening a new one. Is it possible?

Thank you.

# Answer
Thanks to baheard

I believe it was related to upgrading a project to a new version of unity. I resolved it by deleting the .csproj files and the .sln file form the project folder. Unity will just recreated them immediately, and the files correctly opened in the same instance of VS.
> 2 votes

---
Tags: unity, editors, ide, settings, visual-studio-code
---


# Question
Title: Tiles in the Tilemap dont overlap properly
This is my first try making a "proper" game in Unity. I'm using the latest version (2019.2.2 at the time of writing) and I'm writing with C#. This is a project I'm doing for my studies, together with another person (he makes tiles, sound, music and I'm at charge of the programming).

We are making a 2D Roguelike RPG using the Unity tilemap feature.

My algorithm to generate dungeons works really well, but only used one ground tile and one wall tile. We found that to be very boring and changed it.

Now comes the problem. If I let the algorithm pick between fewer than 3 tiles, everything works fine.

If I let the algorithm pick from more than 2 tiles, something strange happens and the some tiles don't overlap properly.

I hope somebody can help me understand why this happens.

Here the important settings of camera and tilemap:

1. Camera
2. Grid
3. GroundLayer
4. WallLayer

One weird think I have been able to find out: The tiles that don't overlap will change if I change the position of the camera.

As a gif:

# Answer
> 1 votes
"Pack all the individual Sprites that make up the Tilemap into a single Sprite Atlas to solve this issue. To do this:

1. Create a Sprite Atlas from the Assets menu (go to: Atlas \> Create \> Sprite Atlas).
2. Add the Sprites to the Sprite Atlas by dragging them to the Objects for Packing list in the Atlas’ Inspector window.
3. Click Pack Preview. Unity packs the Sprites into the Sprite Atlas during Play mode, and correctly sorts and renders them. This is only visible in the Editor during Play"

This solved my problem. https://docs.unity3d.com/Manual/Tilemap-Isometric-RenderModes.html

---
Tags: unity, c#, tilemap, tiles
---


# Question
Title: Clockwise / counter-clockwise convention for Vector2.Rotate(float angle)
I am making a 2D game in Unity, and from what I understand, their **convention is that an angle of 0 is up and increasing the angle rotates the object counter-clockwise**.

> Sidenote: I made this assumption by looking at the `rotation.z` value in a transform's Inspector window. When it is 0, the object's `transform.up` points towards positive y. Increasing `rotation.z` rotates the object counter-clockwise, i.e. the object's `transform.up` points to negative X at an angle of 90 degrees. Let me know if this is wrong.

Considering the convention, where increasing the angle rotates counter-clockwise, what should my extension method `Vector2.Rotate(this Vector2 vector, float angle)` do?

**My question is whether doing `Vector2.up.Rotate(90)` would result in a clockwise or counter-clockwise rotation,** where clockwise would give `Vector2.right` and counter-clockwise would give `Vector2.left`.

At first it seemed initiative to me that it would *obviously* rotate clockwise. It's a positive number so therefore it rotates clockwise. I'm not sure where that bias comes from, but using `Rotate(90)` feels like it should rotate it to the right (clockwise).

After reasoning about it, I think it would make more sense to have `Rotate(90)` rotate counter-clockwise. Because the universe assumes higher/positive angle results in counter-clockwise rotation, the method must also respect that rule. But for some reason it doesn't seem intuitive to me that to rotate something clockwise, I would have to call Rotate with a negative number, `Rotate(-90) // clockwise`.

Is there an evidence-based way to make this decision?

# Answer
I was tempted to vote to close this as primarily opinion-based, but we may be able to provide an evidence-based argument here.

I'd recommend that your method rotate counter-clockwise for positive angles, for the sake of interoperability, and mathematical convention:

1. **Interoperability**

As you've pointed out, Unity's API already picks a side by using left-handed coordinates and treating the z rotation angle as being about the positive z axis. So several methods of the `Transform`, `Rigidbody2D`, and `Vector*`/`Quaternion` math classes all agree that a positive z angle rotates counter-clockwise (from the default camera viewpoint).

If we "go with the flow" then we have one less exception or special rule to remember, and fewer corrective adjustments to apply. Let's say you need to coordinate the movement of several objects of different types in your game, based on the change in angle of another vector:

`float myAngleDelta = Vector2.SignedAngle(oldReferenceVector, newReferenceVector);`

If we use Unity's convention, we can plug this value straight through into our custom method:

`Vector2 newAimVector = aimVector.Rotate(myAngleDelta);`

And we can also apply this very same value to all our other operations, without needing to negate/adjust it:

```
Transform aimReticle = GetReticle();
reticle.Rotate(0, 0, myAngleDelta);

Rigidbody2D tank = GetTank();
tank.MoveRotation(tank.rotation + myAngleDelta);

Quaternion twist = Quaternion.Euler(0, 0, myAngleDelta);

```

`Vector3 newAim3D = twist * aim3D;`

Notice we didn't have to remember to flip `myAngeDelta` anywhere, across 4 different types and methods - the same calculated number works in all of these contexts. I could read an angle directly out of `Rigidbody2D.rotation` and feed it into your custom method, no conversion required. That alone is a big win in simplicity, clarifying the meaning of your code, and avoiding new special cases to keep track of.

2. **Mathematical Convention**

This also happens to agree with the way angles are conventionally described in a mathematical context. When working with the unit circle or polar coordinates, we say a 2D vector has the form...

$$\vec v = r \cdot \left( \cos \theta , \sin \theta \right)$$

(or if you want to get fancy)

$$x + i y = r \cdot e ^ {i \theta}$$

...where theta is an angle counter-clockwise from the positive x-axis.

This gives us a different kind of interoperability: we now match the bulk of math formulas we might find on the net or in a textbook about how to compute particular angles we care about. So we can convert them clearly into code without extra correction factors (besides the often-unavoidable conversion to & from radians)

One such formula in particular is so common it's baked right into the standard `Math` or `Mathf` classes of many languages/environemnts:

`float radianAngle = Mathf.Atan2(vector.y, vector.x);`

`Atan2(y, x)`, when used as directed, converts from a vector to an angle measured counter-clockwise from the positive x-axis. Once again, going with the flow helps you keep compatibility with the bulk of what's already out there.

This also gives you a third kind of interoperability: clarity to the minds of other programmers, gamedevs, or math geeks who are used to these conventions. So if you bring a new person onto your team, or post a question here for help, they'll have an easier time understanding what you're doing if you stick to convention, and their contributions are more likely to have the desired result because they haven't overlooked a hidden convention flip.
> 1 votes

---
Tags: unity, rotation, angles
---


# Question
Title: Modeling complex requirements for populating loot/drop tables
I have a set of items and a data structure that describes where and how those items may be dropped. I'm looking to implement a roguelike/randomizer element to the game and want to include the special items that control progression.\* Ensuring the game remains completable is an absolute requirement but I'm having trouble handling all the different constraints that mixing up the progression item locations brings.

I'm looking for a way to model the requirements that isn't just hard-wiring them into the randomizer logic and hoping I got it right. Preferably some kind of DSL that is processed and kicks out a partial drop table that at least guarantees completion is possible that I can slot less important items into afterwards. Does this kind of modeling tool exist?

\*: for reference the game is a Metroidvania-style platformer, so progression items are things that unlock traversal abilities like a double-jump, swimming, immunity to lava, etc. They are not necessarily acquired in order though many are locked behind others in the vanilla game.

---

# Detailed explanation of specific problem:

Let `A`,`B`,`C`,... be special progression items.

Each location in the drop table has a boolean constraint describing what items are necessary to access that location. For example `A | (B & C)` would imply two possible paths: get `A`, or get `B` and `C`.

Early-stage locations are easy to model because they generally have no or very short constraints. Later-stage locations become very complex as the boolean expression must expand to cover every possible progression path and very quickly become something like `(A | B | C) | (D & (E ^ F)) | ...` with another 4-5 terms following after. Getting these constraints wrong means it's possible to generate an impossible-to-complete game.

Trying to handle the constraints in code quickly become intractable and very difficult to debug. Thus the search for a better way to model the constraints.

In the end it's a kind of recursive boolean satisfiability problem. In theory I could build a giant expression for the entire game complete-able state and repeatedly run it through a SAT solver until completion is achieved or it stalls. Food for thought in case anyone else has this same problem.

# Answer
> 1 votes
I'm still not fully sure I understand the way your generator works, producing / using these constraints, but I'll walk through one possibility and we can use that as a starting point for clarifications & corrections.

Let's say we've already generated a map that requires specific items/unlockable abilities to access various regions. We want to populate that map with pseudo-random rewards, so that the player is guaranteed to be able to get the items they need to access region X without already passing through region X, so that the map remains solvable.

Let's start by fixing a sequence of the key items to be collected. Note that when we do this, we're not forcing the game to be linear, nor mandating that the player will collect them in this order. All we're doing is ensuring there is at least one viable solution order - and other orderings may also be possible.

This choice to focus on ensuring one guaranteed solution path, rather than modelling every possible path, cuts the complex boolean satisfiability problem of multiple routes down to comparing indices in a single route. We still get alternative paths as a side effect, but they're no longer necessary to evaluate in aggregate in order to guarantee solvablity.

We could approach this in one of two ways:

* Pick the sequence of items first, then generate the map so that barriers that need early items occur early in the map. (It doesn't benefit the player to get the fire resistance boots if there's no fire in the part of the map they can reach so far, so they won't be able to see immediate benefit)

The Lenna's Inception strategy I mentioned in the comments works this way, growing the map as a tree with nodes labelled by the number of key items collected before reaching that point, which only increase as we grow the tree outward. Then cross-links are added for non-linearity, and barriers requiring key item `X` are added to any link between rooms `A` and `B` where `(itemsRequired(A) != itemsRequired(B) && max(itemsRequired(A), itemsRequired(B)) == X`
* Generate the map first, then do a breadth-first search through it, passing through only barriers we already have the items to cross, and noting which uncrossable barriers we've encountered. When we run out of reachable regions, add an item that will pass one of the uncrossable barriers we've met so far to the end of our sequence, and resume our search with these barriers as the frontier.

Either way we go, we now have two related sequences:

1. A sequence in which the key items can be obtained
2. An expanding sequence of "tiers" of the map, accessible once the player has all of the first `X` items from the item sequence. Tier 0 is the area around the starting location that is accessible without passing through any barriers at all. Tier 1 is the area the player can reach with only the first item, etc.

Note that each tier includes the tiers before it, rather than only the new addition - we'll use this to allow multiple solution paths.

Now we can place our items. For each item `i`, enumerate all the opportunities in map tier `i-1` where it could drop. (Say if the fire resistance boots can only drop from a fire-type enemy or a red chest, count up all the fire enemies/red chests) You can do this without explicitly coding constraints in advance: just search the drop table to see if item `i` appears in it.

If you ever encounter an item that has no opportunities to drop in the preceding tier, then it's time to locally modify the map to put at least one opportunity somewhere. You can often do this without re-generating the whole map. Or, to avoid this possibility, you could start by stamping some spot in every tier with one opportunity for the next item, before you populate the rest of the region's contents to match this seeded bit.

Because tier 2 includes tier 1, which includes tier 0, it's possible that the first two items are both accessible in the starting area - that the player may get item 2 before they get item 1. So they might be able to access regions in a different order than our tier list. That's how we can get multiple solution paths/non-linearity, even though we only rigidly guaranteed a solution path with item 1 first.

This doesn't break our solvability guarantee, though it can allow opportunities for sequence breaks, where the player finds a way to beat the level without getting one of the items. This can be controlled for if it's not a desirable outcome.

Now you have two choices: you can either fix one of the opportunities in each tier as the one that will give the next item, or make it stochastic during play:

Each time the player hits one of these opportunities, in the preceding tier and it *doesn't* award the key item, decrement your count of remaining opportunities for this item. You can skew your loot probability so that it reaches 100% drop rate when the player is down to their last opportunity, or shape it to typically drop 3/4 of the way through, etc.

In pseudo-code, that might look like this:

```
foreach(keyItem in guaranteedSolutionSequence) {
    if(rewardSource.CanContain(keyItem)) {
        probability = 1f / keyItem.remainingOpportunities;

        if(random() < probability)
            reward.Add(keyItem);
        else if (GetTierIndex(rewardSource.position) <= keyItem.index)
            keyItem.remainingOpportunities--;
    }
}

```

Here I allow one opportunity to drop multiple key items, so even if there's only one chest in the first 3 tiers you can still make progress. But you can ensure your generator drops opportunities in every tier so that this isn't necessary.

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


# Question
Title: Updating connected states in a "build the pipeline" puzzle game
I'm trying to make the pulse system in a "build the pipeline" puzzle game to check if tiles are connected to the starting tile.

There is a weird bug that prevents tiles on the right and tiles on the top of any powered up tile (including starting one) to change state, but it works fine with tiles on the left and bottom.

I tried to log this and it happened that the cycle is going trough these tiles, but their state doesn't change. Here is an example:

Here is the code. If I remove this bit:

```
 else
              p.GetComponent<piece>().ConnectedToStart = false;

```

then it is changing the state as it should, but I have no idea how to disable tiles that should be unpowered in any other way. Also, the question is still there - why does it only work for the tiles on the left and bottom?

<pre><code>    public class Puzzle
    {

        public int winValue;
        public int curValue;

        public int width;
        public int height;
        public piece[,] pieces;

    }

        public Puzzle puzzle;

        GameObject[] pieces;
    void Start()
    {
        pieces = GameObject.FindGameObjectsWithTag("Piece");
    }

    void Update()
    {
        CheckForStartConnections();
    }

    public void CheckForStartConnections()
    {

        foreach (var p in pieces)
        {
            if (p.GetComponent<piece>().StartPiece)
                Pulse((int)p.transform.position.x, (int)p.transform.position.y);
            else
              p.GetComponent<piece>().ConnectedToStart = false;
        }
    }

    void Pulse(int w, int h)
    {
        puzzle.pieces[w, h].GetComponent<piece>().ConnectedToStart = true;
        //compares left
        if (w != 0)
            if (puzzle.pieces[w, h].values[3] == 1 && puzzle.pieces[w - 1, h].values[1] == 1)
            {
                if (!puzzle.pieces[w - 1, h].GetComponent<piece>().ConnectedToStart)
                    Pulse((int)puzzle.pieces[w - 1, h].transform.position.x, (int)puzzle.pieces[w - 1, h].transform.position.y);
            }
        //compares bottom
        if (h != 0)
            if (puzzle.pieces[w, h].values[2] == 1 && puzzle.pieces[w, h - 1].values[0] == 1)
            {
                if (!puzzle.pieces[w, h - 1].GetComponent<piece>().ConnectedToStart)
                    Pulse((int)puzzle.pieces[w, h - 1].transform.position.x, (int)puzzle.pieces[w, h - 1].transform.position.y);
            }
        //compares top
        if (h != puzzle.height - 1)
            if ((puzzle.pieces[w, h].values[0] == 1 && puzzle.pieces[w, h + 1].values[2] == 1))
            {
                if (!puzzle.pieces[w, h + 1].GetComponent<piece>().ConnectedToStart)
                {
                    Pulse((int)puzzle.pieces[w, h + 1].transform.position.x, (int)puzzle.pieces[w, h + 1].transform.position.y);
                }
            }
        //compares right
        if (w != puzzle.width - 1)
            if (puzzle.pieces[w, h].values[1] == 1 && puzzle.pieces[w + 1, h].values[3] == 1)
            {
                if (!puzzle.pieces[w + 1, h].GetComponent<piece>().ConnectedToStart)
                {
                    Pulse((int)puzzle.pieces[w + 1, h].transform.position.x, (int)puzzle.pieces[w + 1, h].transform.position.y);
                }
            }
}
```
</code></pre>

# Answer
> 1 votes
I think this is a problem of ordering. Let's look at this code

```
foreach (var p in pieces) {
    if (p.GetComponent<piece>().StartPiece)
         Pulse((int)p.transform.position.x, (int)p.transform.position.y);
    else
         p.GetComponent<piece>().ConnectedToStart = false;
}

```

Imagine you have 5 pieces, all of them connected.

The first two pieces you visit are not the start piece, so mark them not connected to the start.

The third piece you visit is the start piece, so you pulse from there and recursively mark all the pieces as connected to the start.

Then your `foreach` loop *keeps going*.

It visits the fourth and fifth pieces, which are not the start piece, so it marks them not connected, overwriting the value you wrote in your pulse call!

So, what you want to do is separate your two steps:

1. Clearing all previous `ConnectedToStart` markings, *then*
2. Propagating new `ConnectedToStart` values with a call to `Pulse` for each start piece.

This might look like...

```
Stack<Piece> frontier = new Stack<Piece>();

void UpdateConnectedness() {
    foreach(var piece in pieces) {
        if(piece.StartPiece)
             frontier.Push(piece);
        else
             piece.ConnectedToStart = false;
    }

    while(frontier.Count > 0) {
         Pulse(frontier.Pop());
    }
}

```

(Here I propose we use the `Piece` type throughout, using `FindObjectsOfType` instead of tags to collect our pieces, and using a piece as the argument to `Pulse`, since we need to look it up in there anyway)

One handy thing with this approach: instead of recursing, `Pulse` can just mark the tile connected and then push it onto the stack. This will prevent you from overflowing the callstack, even on truly immense maps. Or you could trade the stack for a queue to iterate in breadth-first order, which would let you compute distance from the start at the same time — helpful if you ever want to draw animated water/electrical current flowing outward.

---
Tags: unity, 2d, algorithm, puzzle
---


# Question
Title: Remove tutorial projects from learn tab in Unity
In Unity I downloaded one of the tutorial projects in the learn tab. However I don't need it anymore. What should I do to get rid of it?

# Answer
The example tutorials are located in:

## windows:

C:\Users{Username}\AppData\Roaming\Unity\Asset Store-5.x\Unity Technologies\Unity EssentialsSample Projects

## mac

C:\Users{Username}\Library\Unity\Asset Store-5.x\Unity Technologies

(You need to delete them manually)
> 2 votes

# Answer
To expand on the other answer:

**On Linux:**

~/.local/share/unity3d/Asset Store-5.x/Unity Technologies/Project/
> 2 votes

---
Tags: unity
---


# Question
Title: Memory tracker allocates while outputting results
I've written a memory tracker for use in my game engine. I based it on this slide in a talk by Nicolai Josuttis.

One problem I'm having is that, during reporting, the implicit string conversion and output stream operator functions allocate. This results in calls to `new`. Since I've overloaded `new` the tracker tries to track the new allocations and ends up invalidating the results.

**Is there a way to output the results without allocating?**

Memory.hpp

```
#pragma once
//https://www.youtube.com/watch?v=e2ZQyYr0Oi0
//C++17 - The Best Features - Nicolai Josuttis [ACCU 2018]

#include "Engine/Core/BuildConfig.hpp"
#include "Engine/Core/ErrorWarningAssert.hpp"

//#include "Engine/Profiling/StackTrace.hpp"

#include <new>
#include <sstream>
#include <iostream>
#include <ostream>

class Memory {
public:

    struct status_t {
        std::size_t leaked_objs  = 0;
        std::size_t leaked_bytes = 0;
        operator bool() const noexcept {
            return leaked_objs || leaked_bytes;
        }
        operator std::string() const noexcept {
#ifdef TRACK_MEMORY
            std::ostringstream ss;
            std::string s = ss.str();
            ss << "Leaked objects: " << leaked_objs << " for " << leaked_bytes << " bytes.\n";
            return s;
#else
            return {};
#endif
        }
        friend std::ostream& operator<<(std::ostream& os, [[maybe_unused]]const status_t& s) noexcept {
#ifdef TRACK_MEMORY
            os << "Leaked objects: " << s.leaked_objs << " for " << s.leaked_bytes << " bytes.\n";
#endif
            return os;
        }
    };
    struct status_frame_t {
        std::size_t frame_id = 0;
        std::size_t leaked_objs = 0;
        std::size_t leaked_bytes = 0;
        operator bool() const noexcept {
            return leaked_objs || leaked_bytes;
        }
        operator std::string() const noexcept {
#ifdef TRACK_MEMORY
            std::ostringstream ss;
            ss << "Frame " << frame_id << ": Leaked objects: " << leaked_objs << " for " << leaked_bytes << " bytes.\n";
            std::string s = ss.str();
            return s;
#else
            return {};
#endif
        }
        friend std::ostream& operator<<(std::ostream& os, [[maybe_unused]]const status_frame_t& s) noexcept {
#ifdef TRACK_MEMORY
            os << "Frame " << s.frame_id << ": Leaked objects: " << s.leaked_objs << " for " << s.leaked_bytes << " bytes.\n";
#endif
            return os;
        }
    };

    [[nodiscard]] static void* allocate(std::size_t n) noexcept {
        if(is_enabled()) {
            ++frameCount;
            frameSize += n;
            ++allocCount;
            allocSize += n;
            if(maxSize < allocSize) {
                maxSize = allocSize;
            }
            if(maxCount < allocCount) {
                maxCount = allocCount;
            }
        }
        return std::malloc(n);
    }

    static void deallocate(void* ptr, std::size_t size) noexcept {
        if(is_enabled()) {
            ++framefreeCount;
            framefreeSize += size;
            ++freeCount;
            freeSize += size;
        }
        std::free(ptr);
    }

    static void enable([[maybe_unused]]bool e) noexcept {
#ifdef TRACK_MEMORY
        _active = e;
#endif
    }

    static bool is_enabled() noexcept {
#ifdef TRACK_MEMORY
        return _active;
#else
        return false;
#endif
    }

    static void trace([[maybe_unused]]bool doTrace) noexcept {
#ifdef TRACK_MEMORY
        _trace = doTrace;
#endif
    }

    static void tick() noexcept {
#ifdef TRACK_MEMORY
        if(auto f = Memory::frame_status()) {
            std::cout << f << '\n';
        }
        ++frameCounter;
        resetframecounters();
#endif
    }

    static void resetframecounters() noexcept {
#ifdef TRACK_MEMORY
        frameSize = 0;
        frameCount = 0;
        framefreeCount = 0;
        framefreeSize = 0;
#endif
    }

    static status_t status() noexcept {
        return { allocCount - freeCount, allocSize - freeSize };
    }

    static status_frame_t frame_status() noexcept {
        return { frameCounter, frameCount - framefreeCount, frameSize - framefreeSize };
    }

    inline static std::size_t maxSize = 0;
    inline static std::size_t maxCount = 0;
    inline static std::size_t allocSize = 0;
    inline static std::size_t allocCount = 0;
    inline static std::size_t frameSize = 0;
    inline static std::size_t frameCount = 0;
    inline static std::size_t frameCounter = 0;
    inline static std::size_t freeCount = 0;
    inline static std::size_t freeSize = 0;
    inline static std::size_t framefreeCount = 0;
    inline static std::size_t framefreeSize = 0;
protected:
private:
    inline static bool _active = false;
    inline static bool _trace = false;
};

#ifdef TRACK_MEMORY

void* operator new(std::size_t size);
void* operator new[](std::size_t size);
void operator delete(void* ptr, std::size_t size) noexcept;
void operator delete[](void* ptr, std::size_t size) noexcept;

#endif

```

Memory.cpp

```
#include "Engine/Profiling/Memory.hpp"

#ifdef TRACK_MEMORY

void* operator new(std::size_t size) {
    return Memory::allocate(size);
}

void* operator new[](std::size_t size) {
    return Memory::allocate(size);
}

void operator delete(void* ptr, std::size_t size) noexcept {
    Memory::deallocate(ptr, size);
}

void operator delete[](void* ptr, std::size_t size) noexcept {
    Memory::deallocate(ptr, size);
}

#endif

```

# Answer
I used a combination of the new-fangled (and non-allocating!) `std::to_chars` and `std::string_view` with a `static std::array` for a buffer. It works okay, but having to deal with the buffer being overwritten is a little annoying. The use of `std::strlen` is unavoidable but shouldn't be an issue due to the short strings.

I also refactored the code to not use the `std::string` implicit operators. The use case didn't need them anyway since the results were being output into an in-memory stream.

Updated `status_t::operator<<`:

```
        friend std::ostream& operator<<(std::ostream& os, [[maybe_unused]]const status_t& s) noexcept {
#ifdef TRACK_MEMORY
            static std::array<char, 1024> str{ "Leaked objects: %f for %f bytes.\n" };
            std::to_chars_result first_result;
            if (first_result = std::to_chars(str.data() + 16, str.data() + 20, static_cast<float>(s.leaked_objs));
                first_result.ec != std::errc()) {
                DebuggerPrintf("Error code %d: Memory profiler could not convert leaked objects value for printing", first_result.ec);
                return os;
            }
            //Put remainder of string back into buffer because to_chars overwrites.
            std::memcpy(first_result.ptr, " for %f bytes.\n", 16);
            std::to_chars_result second_result;
            if (second_result = std::to_chars(first_result.ptr + 5, first_result.ptr + 11, static_cast<float>(s.leaked_bytes));
                second_result.ec != std::errc()) {
                DebuggerPrintf("Error code %d: Memory profiler could not convert leaked bytes value for printing", second_result.ec);
                return os;
            }
            std::memcpy(second_result.ptr, " bytes.\n", 9);
            os << std::string_view(str.data(), std::strlen(str.data()));
#endif
            return os;
        }

```

Updated `status_frame_t::operator<<`:

```
        friend std::ostream& operator<<(std::ostream& os, [[maybe_unused]]const status_frame_t& s) noexcept {
#ifdef TRACK_MEMORY
            static std::array<char, 1024> str{ "Frame %f: Leaked objects: %f for %f bytes.\n" };
            std::to_chars_result frame_result;
            if (frame_result = std::to_chars(str.data() + 6, str.data() + 26, static_cast<float>(s.frame_id));
                frame_result.ec != std::errc()) {
                DebuggerPrintf("Error code %d: Memory profiler could not convert frame id value for printing", frame_result.ec);
                return os;
            }
            //Put remainder of string back into buffer because to_chars overwrites.
            std::memcpy(frame_result.ptr, ": Leaked objects: %f for %f bytes.\n", 36);
            std::to_chars_result objects_result;
            if (objects_result = std::to_chars(frame_result.ptr + 18, frame_result.ptr + 38, static_cast<float>(s.leaked_objs));
                objects_result.ec != std::errc()) {
                DebuggerPrintf("Error code %d: Memory profiler could not convert leaked objects value for printing", objects_result.ec);
                return os;
            }
            std::memcpy(objects_result.ptr, " for %f bytes.\n", 16);
            std::to_chars_result bytes_result;
            if (bytes_result = std::to_chars(objects_result.ptr + 5, objects_result.ptr + 25, static_cast<float>(s.leaked_bytes));
                bytes_result.ec != std::errc()) {
                DebuggerPrintf("Error code %d: Memory profiler could not convert leaked bytes value for printing", bytes_result.ec);
                return os;
            }
            std::memcpy(bytes_result.ptr, " bytes.\n", 9);
            os << std::string_view(str.data(), std::strlen(str.data()));
#endif
            return os;
        }

```
> 1 votes

---
Tags: memory-efficiency, memory, c++
---


title: C++ Assimp - Transformation Hierarchy

text:
# Question
Title: C++ Assimp - Transformation Hierarchy
I have a question regarding model imports using ASSIMP. I've been working on an Entity and Component (e.g. unity gameobject component) based game engine for fun and to learn in my spare time. I've decided to tackle frustum culling, because it interests me and seems like a relatively simple optimisation to make. I had the algorithm implemented and noticed a problem, while the culling works as expected, the entire sponza scene i have loaded disappears when looking in certain orientations. This happens because it uses the entity the mesh is attached to's position, which in all cases is (0,0,0) or something similar.

This means, despite the fact each mesh of the sponza scene is drawn using it's own model matrix and each entity has the same position (Meaning each mesh should be overlapping surely?) the scene looks entirely normal. Now i know ASSIMP does provide you the transformation for each note (guessing this would be what im looking for) but I can't figure out why the scene just looks normal, does assimp pre-offset the vertices based on the node transform? if so how can i disable this feature?

Any and all literature / tidbits would be welcome, Apologies for not being a super well defined question.

TLDR; How do node transformations work in Assimp

# Answer
I don't understood everything, but the anwser to this question :

> does assimp pre-offset the vertices based on the node transform ?

is **yes**, or at least, I came across the same observation.

You extracted the vertices data from `your_scene->mMeshes[]->mVertices[]`, right ?

**EDIT**

What you could do is getting the transformation matrices for all your meshes by reading the node hierarchy starting with your\_scene-\>mMeshes-\>mRootNode and stacking the transforms. Once you have them, pre-transform the meshes by their inverse offset transform. That way you will have all your meshes overlapping at (0,0,0)
> 2 votes

---
Tags: c++, transformation, assimp
---


# Question
Title: How to use CreateGridMesh in RuntimeMeshComponent
I don't know to pass on the 5th parameter. I'm still new with C++ so if someone could help me with the pointer

```
void AGrid::GenerateMeshes_Implementation()
{
    FRuntimeMeshDataPtr Data = GetRuntimeMeshComponent()->GetOrCreateRuntimeMesh()->GetRuntimeMeshData();
    Data->EnterSerializedMode();

    Data->CreateMeshSection(0, false, false, 1, false, true, EUpdateFrequency::Average);

    auto Section = Data->BeginSectionUpdate(0);

    FVector BoxSize = FVector(100, 100, 100);
    URuntimeMeshShapeGenerator::CreateBoxMesh(BoxSize, *Section.Get());
    URuntimeMeshShapeGenerator::CreateGridMesh(128.0f, 128.0f, 64, 64, *Section.Get()); // <---- This one

    Section->Commit();
}

```

It says it needs to be a `TSharedPtr<FRuntimeMeshAccessor>&`

```
void URuntimeMeshShapeGenerator::CreateGridMesh(float Width, float Height, int32 NumSubdivisionsX, int32 NumSubdivisionsY, const TSharedPtr<FRuntimeMeshAccessor>& MeshBuilder)
{
    MeshBuilder->EmptyVertices(CREATEGRIDMESHTRIANGLES_NUMVERTS(NumSubdivisionsX, NumSubdivisionsY));
    MeshBuilder->EmptyIndices(CREATEGRIDMESHTRIANGLES_NUMTRIS(NumSubdivisionsX, NumSubdivisionsY));
    FVerticesBuilderFunction VerticesBuilder = [&](const FVector& Position, const FVector& Normal, const FRuntimeMeshTangent& Tangent, const FVector2D& UV0)
    {
        int32 NewVertex = MeshBuilder->AddVertex(Position);
        MeshBuilder->SetNormalTangent(NewVertex, Normal, Tangent);
        MeshBuilder->SetUV(NewVertex, UV0);
    };

    FTrianglesBuilderFunction TrianglesBuilder = [&](int32 Index)
    {
        MeshBuilder->AddIndex(Index);
    };

    CreateGridMesh(Width, Height, NumSubdivisionsX, NumSubdivisionsY, VerticesBuilder, TrianglesBuilder);
}

```

# Answer
**Change this:**

```
URuntimeMeshShapeGenerator::CreateGridMesh(128.0f, 128.0f, 64, 64, *Section.Get());

```

**to this:**

```
URuntimeMeshShapeGenerator::CreateGridMesh(128.0f, 128.0f, 64, 64, Section->GetReadonlyMeshAccessor());

```

### More Info

It looks like you are using Koderz/RuntimeMeshComponent.

The 5th parameter of `URuntimeMeshShapeGenerator::CreateGridMesh` is a `const TSharedPtr<FRuntimeMeshAccessor>&`.

The type returned from `FRuntimeMeshData::BeginSectionUpdate` is a `TUniquePtr<FRuntimeMeshScopedUpdater>`. Your `Section` variable also has this type.

When you call `*Section.Get()` for the 5th parameter, you are attempting to pass in a `FRuntimeMeshScopedUpdater`, which does match and results in the compilation error.

You need to get the `FRuntimeMeshAccessor` with `FRuntimeMeshData::GetReadonlyMeshAccessor`.

The `Get()` method you were calling was a Get() on TUniquePtr, part of the Unreal Smart Pointer Library. It did not get the `FRuntimeMeshAccessor` you needed.
> 1 votes

---
Tags: c++, unreal-4, unreal
---


# Question
Title: Batching a bunch of gameObjects that change their color
So I have a bunch of cubes instantiated. Each time the player hits one of these cubes (which is quite often) they change their color to match that of the player. What would be a performant way to do this? So far i am doing this on OnTriggerEnter then grab my player’s mesh renderer, get its material and get the color. This is quite an expensive process. I was wondering if there is any better way. The cubes do not move by the way, so if they can somehow be batched as well that would be a plus! Also, the player’s color is random.

# Answer
I would add a static refrense to the color in the player, something like: `public static Color publicColor` (keep in mind to update this color as well) and when any cubes want to chage color they just say `meshrenderer.material.color = myPlayer.publicColor` If you want a performance boost, but also keep in mind that this will only work with 1 player.
> -1 votes

---
Tags: unity
---


# Question
Title: Unable to download assets from Unity Asset Store
I have a problem with the Asset Store on openSUSE Tumbleweed, running Unity 2019.1.0f2.

I can connect, log in, view the download button, and click it.

Then, a "Downloading" message appearsb but nothing more happens.

This is strange because on Arch it is working perfectly.

I disabled my firewall and other security things, without success.

# Answer
Well, after a hard search, I found the problem. Unity can't found

> /etc/ssl/certs/ca-certificates.crt

, and symlink is needed to

> /etc/ssl/ca-bundle.pem

exactly the solution is:

> sudo ln -s /etc/ssl/ca-bundle.pem /etc/ssl/certs/ca-certificates.crt

From : https://forum.unity.com/threads/solved-unity-cant-connect-to-any-unity-services-and-collab-is-not-working.618199/
> 2 votes

# Answer
Try these two methods it might help:

**Solution # 1**: First make sure Hidden item is visible if not then do the check hidden item check box in the view. then follow the steps below:

1. Close Unity.
2. Deleted directory under "~/Library/Unity/Asset Store-5.x/myAssetName for windows and for Mac - User \> Library \> Unity \> Asset Store. As you are using openSUSE which I have never used so I think you got the idea where the file will be.
3. Relaunch Unity.

**Solution # 2:**

1. close asset store in unity if opened.
2. In your browser go to asset store and log out from your account.
3. Log in again.
4. Click on open in unity and it should open now.
5. Now click on download.
> 0 votes

---
Tags: unity
---


# Question
Title: How to properly scale from natural coordinates to screen coordinate system in OpenGL?
I am working on a Physics Engine, and I have been using opengl to visualize what it's doing. I think I have a scaling issue when going from natural coordinate system to the opengl screen coordinate system, which is between -1 and 1. I am saying that 1 is 150 meters and -1 is -150 meters. Therefore, to get to scale I should be able to take the natural coordinate system point say \<0,100\>, and scale to screen by doing \<0,100/150\>, which is approximately \<0,.667\> screen coordinates.

When I watch a 1 kg ball fall from 100 meters, it seems too be falling to slow, as if it's falling under water (see https://www.youtube.com/watch?v=KiZODHIvJ4A for reference). The physics engine seems to be correct. I think it has something to do with the coordinate system translation (just dividing by 150 scalar right now). Does anyone know if I am doing this correctly?

# Answer
I think your simulation is correct. A 100 meter fall should be 4.5 seconds on earth gravity (ignoring air resistance). And those 4.5 seconds seem to match the time in the video.

I think it is fine. I believe the "under water" impression comes from the size of the ball.

Doing a rough estimation of the size of the ball, I think it has about 10 meters of diameter. The volume would be 523.599 cubic meters (thanks Wolfram|Alpha).

That is a big ball, with only 1kg, the density is 1.90986 g/m^3 (thanks again Wolfram|Alpha), this is the density of air as per Wikipedia: 0.001225 g/cm^3. So, we see a ball moving through a medium much denser than it. Yeah, I think the "under water" feeling is purely psychological based on the size of the ball relative to the span it moves.

Your mind imagines the ball smaller, and the fall distance shorter, and then the fall is too slow, as if the medium were too dense. Draw some background, some tall buildings for reference, and your mind will get the right cue. *I apologize for reading your mind without permission.*

---

That does not mean you are handing OpenGL coordinates correctly. There is a mistake when it comes to resizing the view port. Which is something that probably you do not do at all, which means that what I describe below has nothing to do with the "under water" feeling...

Take premise that the coordinates in OpenGl goes from -1 to 1. These are called normalized device coordinates (NDC). They are not what you see. What you see are screen coordinates (SC). There is a transformation that must happen to map normalized device coordinates (that go from -1 to 1) to screen coordinates (that are in pixels).

How is that transformation defined? By the view port. You tell OpenGl about the size of your view port, and that is what OpenGL uses to map the NDC to SC for rasterisation.

That means that resizing the view port will make thing appear to move faster or slower in screen because -1 to 1 will stretch to more or less pixels, and the simulation is taking the same time.

Now, before the coordinates were in NDC, they were in whatever scale and dimensions you want when you pass the vertices to OpenGL. You have decided to use a scale factor of 150 and called it meters (you can say it is whatever unit you want, that is not the problem). *By the way, you are doing that scaling in a shader, right? RIGHT?*

The mistake is that this scale of 150 is fixed. It does not take into account the size of the view port. You need to consider the size of the view port if you want to compensate for the stretching I described earlier.

Please refer to How to setup glOrtho and Viewport and the difference between glOrtho and glViewPort in openGL.

*Well, if the size of the window is fixed too, then this is moot. I stand by the statement that the "under water" feeling is psychological.*
> 2 votes

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