title: confusion on desired velocity

text:
# Question
Title: confusion on desired velocity
In one of the videos of the dead earth game dev series , the author mentions of calculating a local desired velocity of a `NavMeshAgent`.

My point of confusion was, wasn't the desired velocity local to begin with? From the docs, it's given that desired velocity is:

> The desired velocity of the agent including any potential contribution from avoidance. (Read Only)

since the agent is dynamic shouldn't the velocity already be calculated in the agent's local space, I thought so atleast because it would make sense because most useful case for us is to calculate a certain angle based on the orthogonal vector of one of the axes of the agent's local space and the desired velocity for which desired velocity should be in local space?

And, then he converts the `desiredVelocity` to local space of the agent by doing `transform.InverseTransformVector(desiredVelocity)`. It's using this means that there's an inverse transformation matrix cached by unity. Since, the navAgent is dynamic, it's origin moves about, i.e. the local space moves about as well. So, does that mean the inverse of the transformation matrix from world to local space is calculated for each frame?

EDIT: Consider the following diagram:  There are two vector spaces here, 1) The world space(`w-space`), and 2) the agent space(`a-space`). So, (a, b) in `w-space` is (c, d) in `a-space`, and so on.

So, this I faintly recall is a problem related to change-of-basis of vector spaces? The transformation between these spaces should be guide by a transformation matrices say `M`, assuming both these spaces are orthogonal, and the bases for each is of unit length, the transformation composition is typically: `M=TR`, where T is a transformation matrix and R is a rotation matrix.

Now, the question is, if (a, b) in w-space is equal to (a, b) in a-space, then T should be an identity matrix, which means no `transform.InverseTransformVector(....)` should be required at all, since there's no translation at all, but, if it is required, then what is the translation? And as you demonstrate in your code that it could just be an inverse-rotation, then, why the need to convert it into localspace at all? It could just be the inverse-rotation in world space itself.

# Answer
Velocities in Unity are almost always in world space coordinates. So unless you see something that specifically promises you a local space velocity, world space should be your default assumption. This is the easiest coordinate system to use for handling interactions with objects outside this single entity (like the navmesh, or collisions).

On the occasion when you want to do computations on the velocity relative to the agent's facing direction - as is the case in this tutorial - you can convert the velocity into local coordinates using `InverseTransformVector` or `InverseTransformDirection`, as demonstrated in the source you're referencing. That gives you a version of the velocity in the agent's local coordinate system, making it easy to compute the angles as you describe.

> using this means that there's an inverse transformation matrix cached by Unity

No, that is not an absolute requirement. I'd argue what you really want here is `InverseTransformDirection`, which can be implemented as simply as this:

```
Vector3 InverseTransformDirection(Vector3 input) {
    // This is 3 multiplications, not a full matrix inverse.
    Quaternion q = Quaternion.Inverse(this.rotation);
    return q * input;

}

```

> Since the NavMeshAgent is dynamic, its origin moves about.

That does not matter when we're transforming offset vectors like directions, displacements, or velocities - note how the example function above does not use the origin at all. We only need the origin when we're transforming points / position vectors.

> So, does that mean the inverse of the transformation matrix from world to local space is calculated for each frame?

Not necessarily. It could be computed only when something changes, or only on demand, or not computed at all if the route Unity uses does not include a matrix, like the example above. What matters here is that the API gives us ways to move vectors between coordinate systems on demand - the details of how the engine facilitates this should not matter. It's not our responsibility.
> 1 votes

---
Tags: unity, physics, transformation, linear-algebra, navmesh
---


title: Terracing mountain features

text:
# Question
Title: Terracing mountain features
I'm looking to replicate a procedural terrain effect I found on a portfolio/blog site a few days ago.

Quoting the site, the terracing was generated through, "multiplying \[the final height\] by some damping value within a certain height range, to create beautiful canyon features."

I was wondering, would anyone be able to provide a more technical example or procedure for going about this? Over the past week, I've been researching and learning a lot about procedural terrain/texture methods and practices but I still haven't come across anything that explains in detail what 'clamping' is, and I'm starting to become frustrated.

# Answer
After a *very* long break, I now understand how the effect was achieved, and it's incredibly simple. There are 4 parts to this effect:

* The initial heightmap of the terrain
* Defining a terrace 'range', with the lowest height of the terrace being h1 and the highest height of the terrace being h2
* A damping value that flattens out the ground within the range of the terrace height
* A second, longer-range heightmap to modify the h1 and h2 values, which is how the continuous ramps between terraces are formed (a third heightmap could be used to increase or decrease h1 and h2 independent of eachother, creating larger or smaller terraces)

Here is the procedure to create the effect:

```
h1 = 1
h2 = 2
damp = .01

h = gen_noise(position)
hm = heightmod_noise(position)
if h1+hm <= initial_terrain_height =< h2+hm
  th = h * damp
elseif h2+hm < h
  th = h - (h2-h1) * damp
else
  th = h

```

(th, of course, is the height of the terrain after the terracing effect is applied)
> 1 votes

# Answer
I don't know what their project does but you can apply a reshaping function to height. Here's an example that takes `h` from 0.0 to 1.0 and returns a new height from 0.0 to 1.0:

```
function R(h) {
    var W = 0.4; // width of terracing bands
    var k = Math.floor(h / W);
    var f = (h - k*W) / W;
    var s = Math.min(2 * f, 1.0);
    return (k+s) * W;
}

```

It's a function that looks like this when plotted — the x axis is the original height and the y axis is the new height:

I applied it to my own code and got this:

You can put in any sort of reshaping function, or chain them together, to get neat effects. You get terraces when there are flat sections of the output.
> 11 votes

# Answer
I wanted to smooth out the edge between a terrace and its cliff and made this function for it:

`sin((x - round(x)) * 2.45)^11 + round(x)`

Here is a plot of the curve:

You can find an interactive preview on Wolfram.

The higher the exponent (eg. 11) the steeper is the cliff.

The constant 2.45 is empirically (trial and error) found value. Its purpose is to make the terraces connected. It depends on the exponent. I would be delighted if someone would figure out a way to exactly compute the value. I think it should be the x where first derivative of `sin(x)^11` is one.
> 4 votes

# Answer
Damping is physics term for an influence within or upon an oscillatory system that has the effect of reducing, restricting or preventing its oscillations.

I suspect your source article might have a typo & have meant clamping, which generally refers to restricting a value to a given range.

As for achieving the visual effect, you might be able to get something similar by clamping bands of noise as the terrain is being built up, but the solution given by @amitp more closely matches the original description & is probably easier to implement & tune.

A third option might be to use erosion techniques. Here's one for creating a cliff & beach combination by dropping a section of sloped land. Here's another that can erode peaks into plateaus.
> 1 votes

# Answer
I'd like to add, Pikaleks response above mine is perfect but additionally you can use a "moisture map" calculated with a different noise seed and affected by your elevation/temperature maps, then use that moisture map to control the power of the terracing to introduce "ramps" between terraces with more realistic accuracy.
> 0 votes

---
Tags: mathematics, procedural-generation
---


# Question
Title: What is Animator.Update(float deltaTime) doing?
It looks like it does the same thing as `Time.timeScale`, only for the Animator. But it works somehow specifically. You need to call each frame for it to work + you can only speed up the animation of the Animator, but not slow it down.

Scaling the playing time of the Animator is easily and clearly carried out through the `Animator.speed`, then why do we need `Animator.Update()`, which for me does not even understand how it works?

# Answer
`Animator.Update()` is a function that you can call to *step* the animator forward by the given interval.

You would use this when the animator is otherwise **paused** (and *not* automatically advancing every frame according to `Time.timeScale` and `Animator.speed`). This lets you take complete control of when the animator should update and by how much. This can also be used (even with an argument of 0) to nudge the animator and ensure a transition is executed immediately, or sync the bones to their current animated positions to override a ragdoll pose, rather than waiting a frame for it to catch up to the newest gameplay state.

If all you want to do is adjust the animation speed, not take full control of its update loop, then `Animator.speed` is the correct property to use.
> 2 votes

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


title: opengl two vbo names

text:
# Question
Title: opengl two vbo names
I'm a newbie in OpenGL trying to learn VBO. I have two arrays (`point0` with 3 points and `point1` with 6 points). Suppose I have two separate VBO names and I initialize them:

```
glGenBuffers(1, &vbo0);
glBindBuffer(GL_ARRAY_BUFFER, vbo0);
glBufferData(GL_ARRAY_BUFFER, sizeof(point0), point0, GL_STATIC_DRAW);
glGenBuffers(1, &vbo1);
glBindBuffer(GL_ARRAY_BUFFER, vbo1);
glBufferData(GL_ARRAY_BUFFER, sizeof(point1), point1, GL_STATIC_DRAW);

```

In my display function, I have

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// draw first triangle (point0) in red
glBindBuffer(GL_ARRAY_BUFFER, vbo0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glColor3f(1,0,0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);

// draw second and third triangle (point1) in blue
glBindBuffer(GL_ARRAY_BUFFER, vbo1);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 6, GL_FLOAT, GL_FALSE, 0, 0);
glColor3f(0,0,1);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(0);

```

I was expecting a red triangle from v`b`o0 and two blue triangles from `vbo1`. But I get a blue triangle from the points in array `point0`. Why is that?

# Answer
> 3 votes
```
glVertexAttribPointer(0, 6, GL_FLOAT, GL_FALSE, 0, 0);

```

This GL call is illegal; if we read the documentation for glVertexAttribPointer we will see:

> *size*
> Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4.

The correct value here would be 3; each triangle you draw has 3 components per point: x, y and z.

If you added some error checking to this you'd see that this call throws a GL\_INVALID\_VALUE error. The subsequent behaviour of other GL calls that depend on it is not explicitly defined, so may be reasonably assumed to be undefined, and anything can happen.

So step 1 in resolving your problem is to make sure that you have a legal GL program using correct GL calls; once you have that, you should be more easily able to identify the cause of any unwanted behaviours.

# Answer
> 1 votes
Your problem is this call:

```
glVertexAttribPointer(0, 6, GL_FLOAT, GL_FALSE, 0, 0);

```

In the documentation here size, parameter 2 should be between 1-4. You specified 6 because that is the amount of vertices you put. You should put the amount of floats that there are per position. Example: (0, 1, 2) 3 (1.0, 0.5).
GLuint index,
GLint size,
GLenum type,
GLboolean normalized,
GLsizei stride,
const GLvoid * pointer

I'm not gonna go over all of these since it is already in the documentation and my favorite one is https://docs.gl. I'm assuming that you don't understand much about glVertexAttribPointer() so i'll show you how you can use it. The first parameter index which is 0 is where we store all of our vert positions in a vec2/vec3. We can use this in our shader as

```
layout (location=0) in vec3 position

```

and use that data that we told OpenGL how to interpret. Since we gave them a vec3 we take in vec3 and name the variable whatever. We can use this variable for many things like gl\_Position in our vertex shader.

```
#version 330 core
layout (location = 0) in vec3 aPos;
// layout (location = 1) in vec2 aTexCoord; we can do this if we want multiple things in our data and not just position for example color or textures as well

void main()
{
    gl_Position = aPos;
}

```

Overview of the thing, we told OpenGL to store data in location 0, we told them 1 piece is a vec3 and for every 3 items in our array we can assign this to one vec3, we told them that it is a float, that it is not normalized (read the docs please), and the offset for our each times is 0 because we want to check all items, the last one is the pointer and just read it yourself since I will probably explain it worse.

---
Tags: opengl, vbo
---


# Question
Title: Is there an "official" term for the "key-door problem"?
The "key-door problem" is a term I've come up with, after playing a number of Metroidvania or Zelda style indie games.

One distinctive feature of these games, is that the player is free to explore the world, but the world is full of obstacles the player cannot overcome from the start. The player is encouraged to explore as far as they can, until they find a new item or learn a new skill, which will allow them to overcome some of the obstacles, and allow them to explore where they previously couldn't. Backtracking usually makes up a big part of the game's experience.

For example, in Zelda, bushes can block Link's way, until he finds a sword to cut them, and cracked walls can be blown away with bombs. And in Metroid, Samus cannot crawl through small tunnels until she finds the Morph Ball upgrade, while large canyons require that she can jump indefinitely in mid-air.

This dynamic is what I like most about these games.

However, I've noticed that some indie games (not all) trying to reproduce the same dynamic, actually feel boring precisely because of it. Unlike in Zelda or Metroid, where you're acquiring a new skill or tool to help you progress, these games feel like you're searching for keys to open specific doors instead.

This is what I call the "key-door problem". I've also tried to make my own Zelda-like game, only to notice that it suffers from the same "key-door problem".

Unfortunately, I'm having a very hard time finding anything about it online (such as what causes it, and how to avoid it). When I search for "key door problem game design", all I get is an article about the "Door problem of Game Design" by Liz England, which is about how much effort it can take to add something as mundane as a door to a game.

Therefore, I'd like to know what the "official" term is for the "key-door problem", if there is one.

---

**To clarify:** I'm not looking for a term that describes "*stopping the player from proceeding until they're ready*", I'm looking for a term that describes "*when players feel like they're collecting keys, rather than upgrades or new abilities*" instead.

# Answer
TVTropes calls mechanics where the player needs to acquire an item in location A which serves no purpose but to allow them to progress beyond an obstacle in location B a lock and key puzzle.

The problem described in the question seems to be either an over-reliance on lock and key puzzles. For example, having lock and key puzzles again and again until they become repetitive and predictable. Or using them in ways which make the game less fun. For example by using them to force continuous traversal of the same areas over and over again or by causing the player to get lost.

I don't think there is a more specific term for it, and neither do I think there is a need for one. Any game mechanic can become an anti-pattern when it isn't used well or used beyond the point where it overstays its welcome.
> 5 votes

# Answer
One word close to what you describe is "gating". This means to take a part of the game they may not be ready for (or you just decide they aren't) and put an arbitrary block on it until ... something (they reach level 20 or have played for 20 hours, or whatever).

World of Warcraft had/has a nice counter-example: there was a deadly area you could easily walk-through from a starting zone, where you'd be insta-killed by the first monster to see you. There was no good reason to go there, but the game let you. Other games might put a "you must be level 40+ to enter" gate in front. Or they might be more indirect but the same -- you need lockpicking to go in, which you only get at level 40.
> 2 votes

# Answer
Maybe **Player Progression** (Or Character Progression) is the closest I can get to describe your problem.

If you only get a 'key' to unlock a 'door', then the player itself does not improve. (This doesn't necesarry have to be a key or a door, but it's just one that functions similair without giving additional traits to the character)

If you focus on player progression, then you want to see the player visibly improve when they get a new item, and you don't want to keep stuck with the same abilities in multiple areas.

Implementing items that not only as useful to progress in the level, but also benefits in combat are good examples of player progression. Movement is also a major progression factor, as that allows you to backtrack previous areas easier as well. Been able to take new shortcuts may also take part of that, but keep in mind that shortcuts may start to look like 'doors' again, as they don't improve on the character themselves.

Player Progression is not only limited to combat or mobility. One other example is the Stealth ability in Metroid Dread. While it works to open doors with sensors, it also helps to avoid an EMMI Encounter.
> 1 votes

---
Tags: game-design, terminology
---


# Question
Title: What's the relationship between the actor's pose and shape's pose in PhysX?
I have 2 Meshes and I want to add physics to them. The first is a primitive box, the second is a terrain.

The box and terrain are made with DirectXMath

Using the PhysX library, I made a copy of the terrain and used it to create a Triangle mesh, and I created a box using `physx::PxBoxGeometry` as you can see here:

```
        physx::PxTransform boxPos(physx::PxVec3(0.0f, 20, 0.0f));
        physx::PxBoxGeometry boxGeometry(physx::PxVec3(0.5f, 0.5f, 0.5f));
        physx::PxShape* shape =m_pPhysics->createShape(boxGeometry, *m_pMaterial);
        physx::PxRigidDynamic* boxRigid = m_pPhysics->createRigidDynamic(boxPos);
        boxRigid->attachShape(*shape);
        physx::PxRigidBodyExt::updateMassAndInertia(*boxRigid, .15f);

        m_pScene->addActor(*boxRigid);
        m_pPhysicsActors.push_back(boxRigid);

```

I added them to the scene and I ran the simulation and I can see the box is dropped and flipped couple times using Physx Visual Debugger (though, on some runs the debugger shows artifacts, anyway)

I found out that I can get the translation and rotation by using `m_pPhysicsActors[]->getGlobalPose()` which is both quaternion for rotation and vector for position so I thought that's it

But in the hello world snippets they made this function:

```
/**
\brief Retrieves the world space pose of the shape.

\param[in] shape The shape for which to get the global pose.
\param[in] actor The actor to which the shape is attached

\return Global pose of shape.
*/
static PX_INLINE    PxTransform     getGlobalPose(const PxShape& shape, const PxRigidActor& actor)
{
    return actor.getGlobalPose() * shape.getLocalPose();
}

```

then they put the output in a matrix

Now I am confused, why multiply `actor.getGlobalPose() * shape.getLocalPose();`?

I thought the shape and the actor are the same thing, like a relationship or a property. Since I assign a shape to an actor, I imagine that if I rotate a shape, I rotate the actor vice versa as it is one thing.

This is where I am lost! Can someone walk me through how to update render items from PhysX?

# Answer
As **DMGregory** mentioned

An actor can have many shapes(parts), all together ensembles the overall actor's behaviour, thus each shape can have it's own position(in local space) relative to the actor's position(in world space).

Even if one actor has one shape, the shape may not always be at the centre of the actor

> think of a pendulum where the weight is a distance away from the pivot

Thus, we still need to use the shape's world pose instead of the actor pose.

so we will still need this conversion `actor.getGlobalPose() * shape.getLocalPose();` to get the shape's world pose
> 1 votes

---
Tags: directx12, physx, directxmath
---


# Question
Title: Internal representation of checkers board
I am creating a game of checkers using the but am struggling to find a good internal representation for the game. My initial thoughts were to store the game board in a 2d list, with 0=empty, 1=always empty, 2=team 1, 3=team 2. My second idea was to create a Piece class and append piece objects to an list, passing the x, y co-ordinates of each piece as I do this. Would anyone be able to suggest the best way to go about this. I later want to implement the min max algorithm.

# Answer
Both of your proposals can work.

* **A 2D list for the board** gives you the advantage that you can check whether a space contains a piece just by indexing with the coordinates of that space.

But when you want to iterate over all of the pieces for a player (say, to check all their available moves, or evaluate the victory condition/heuristic), you have to iterate over the whole board. (Not dire, when it's only 64 iterations)
* **A list of piece objects** gives you the advantage that you can easily iterate over all of the pieces, particularly if you partition them by their owning player.

But when you want to check whether a particular tile contains a piece, you have to iterate over the whole list checking for a piece with matching coordinates. (Not dire, when it's only 24 iterations at max)

You might notice that these pros and cons are exactly complementary: one representation excels where the other representation is weakest. So that gives you a third option: **use both**. That way you can use the most convenient structure for each task. You just need a little book-keeping to keep the two structures in-sync, so they never disagree about where the pieces are. It might seem redundant, but we're talking a matter of bytes here - this whole thing will fit in your CPU cache, so there's no need to be stingy with data structure memory here if it makes your other code simpler.
> 1 votes

---
Tags: python, pygame, board-game
---


# Question
Title: How would I actually implement A* pathfinding in a 3D world?
I have been trying to implement pathfinding in Minecraft for a while. Everything is in blocks, so this shouldn't be too difficult. I have gone through a lot of different posts and articles but I haven't seen any actual implementation for A\* pathfinding in Java. I can't find any libraries that can help me with this either. Many existing solutions use a grid implementation for their pathfinding. For example, using the Slick2D library, I would implement 2D pathfinding using the following:

1 -\> Transform the area around the player into a grid of 1 and 0, where 0 is walkable and 1 is not. This seems pretty inefficient.

2-\> Run the pathfinding on this grid.

This is not what I want, as this is very inefficient. How would I go about actually coding pathfinding that does the following:

1: Interacts **directly** with the Minecraft world, so I wouldn't have to keep generating a grid that can be used with libraries.

2: It has to be 3D, as in it could navigate terrain that isn't flat.

Thank you very much for the help! I am not asking for code, but I just want to know how I would go about this.

Have a great day :)

# Answer
> 7 votes
What A\* needs to work is the following:

* Given the current node, get the list of possible nodes it can move to, with their costs.
* The ability to evaluate the heuristic function.

Please notice I've said nothing of a grid. A\* will work with any graph, with nodes and links. If you could have the graph pre-made, you would just execute on the graph. But you don't have to. So, instead of having links, we will have a function that give you the neighbors of a node.

---

For your case, of course, the nodes would be the cubes/blocks/cells/voxels of the world. And you will have reference to them. *Given that we are talking Java, perhaps you have a reference type for the nodes. Alternatively, you have them in some indexed data structures, and you can reference them by that index (the index could be the 3D coordinates, for example).*

So, you will have a function that takes a reference to a block, and gives you a array/list/iterable of the references to the blocks the character can move into. *Considering whatever mobility options are available (e.g. walking, jumping, swimming, and so on).* Those would be the links.

You would do that by querying the neighbor blocks to the given one, checking what are they of, and determining whatever or not the character could move there.

However, you also need the costs. You probably are better off computing that at the same time, in which case you would not return references to blocks, but pairs of references to blocks and costs. Another option is to have a function that will take references to two neighbor blocks, and tell you the cost.

What is the cost? Well, presumably it consider mobility options and terrain type. For example: walking over mud costing more than walking over stone (that is, the character walks faster/easier on stone than on mud), or for example jumping costs more than walking. *And if you can't go there, you can say cost is infinite.*

Note: You could have a pre-computed graph with all information, perhaps update it when a block changes, and execute A\* there. In fact, you could store store that in the same structure in memory that has the blocks (so each block would know how much it cost to move from it to its neighbor blocks).

---

And of course, you need the heuristic function is an estimate of the cost to get to the goal. Presumably you would start by the distance in strighline to the goal, perhaps add extra cost for verticality (i.e. if getting there must require at least x jumps, and each jump costs z more that walking, add x\*z extra to the heuristic).

---

Now, you can implement A\*. Go find the pseudocode somewhere. For example: A\* pseudocode on wikipedia. Or try Rosetta stone. I will also advise to read about some variants and optimizations. In particular Iterative Deepening A\* and Memory bounded A\*.

I suppose you will have to modify the code anyway. And thus I should advocate for you to understand it. And for that, I think you should start by understanding Dijkstra's Algorithm. I'll let Computerphile help with that:

---

**Addendum**: See also Amit Patel's Introduction to the A\* Algorithm at Red Blob Games.

# Answer
> 1 votes
The same way you do for a 2D world (or flat 3D world). The only differences would be the cost calculation and movement possible to get to neighbors.

---
Tags: java, 3d, path-finding, minecraft-modding
---


# Question
Title: Why doesn't the scene name change when loading another scene?
I have two scenes: "Main Menu" and "Game."

When running the game it starts with the Main Menu scene loaded. Then, when starting a new game the Main Menu scene is unloaded and the Game scene is loaded. However, even if the Game scene is loaded it keeps showing the Main Menu scene in the name:

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

public class AudioManager : MonoBehaviour
{
    public GameObject gameAudio;

    private AudioSource audioSource;
    private string sceneName;
    private bool currentScene = false;

    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }

    // Start is called before the first frame update
    void Start()
    {
        // Create a temporary reference to the current scene.
        Scene currentScene = SceneManager.GetActiveScene();

        // Retrieve the name of this scene.
        sceneName = currentScene.name;

        audioSource = gameAudio.GetComponent<AudioSource>();

        var mainmenumusic = GameObject.Find("Main Menu Settings");
        audioSource.volume = mainmenumusic.GetComponent<AudioSource>().volume;
    }

    // Update is called once per frame
    void Update()
    {
        if (sceneName == "Game" && currentScene == false)
        {
            audioSource.Play();
            currentScene = true;
        }
        else
        {
            if (sceneName != "Game")
            {
                audioSource.Stop();
                currentScene = false;
            }
        }
    }

    //Called when Slider is moved
    public void changeVolume(float sliderValue)
    {
        audioSource = gameAudio.GetComponent<AudioSource>();
        audioSource.volume = sliderValue;
    }
}

```

During `Update`, even if the Game scene has loaded (and only the Game scene is loaded) `sceneName` is still set to "Main Menu":

```
if (sceneName == "Game" && currentScene == false)

```

`sceneName` is never "Game."

And a side question:

When I press the escape key back to the main menu it keeps creating the `DontDestroyOnLoad` object over and over again. How can I avoid creating the `DontDestroyOnLoad` all the time? This script is in my Game scene:

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

public class BackToMainMenu : MonoBehaviour
{
    public GameObject[] objsToDisable;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (Time.timeScale == 0)
            {
                DisableEnableUiTexts(true);
                SceneManager.UnloadSceneAsync(0);
                Cursor.visible = false;
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
                MenuController.LoadSceneForSavedGame = false;
                SceneManager.LoadScene(0, LoadSceneMode.Additive);
                SceneManager.sceneLoaded += SceneManager_sceneLoaded;

                Cursor.visible = true;
            }
        }
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        DisableEnableUiTexts(false);
    }

    private void DisableEnableUiTexts(bool enabled)
    {
        foreach (GameObject go in objsToDisable)
        {
            if (go.name == "Cameras")
            {
                foreach(Transform child in go.transform)
                {
                    if(child.name == "Main Camera")
                    {
                        if (enabled == false)
                        {
                            child.GetComponent<Camera>().enabled = false;
                        }
                        else
                        {
                            child.GetComponent<Camera>().enabled = true;
                        }
                    }
                }
            }
            else
            {
                go.SetActive(enabled);
            }
        }
    }
}

```

# Answer
The reason for this behavior is that you are loading your scenes with `LoadSceneMode.Additive`. This parameter allows you to have more than one scene at the same time. So the concept of "active scene" becomes a bit fuzzy.

What happens in this situation is that the currently "active scene" *stays* the "active scene", and the content of the new scene gets added as another scene which is also being executed. However, you can make that new scene the active scene with `SceneManager.SetActiveScene`. Or if you don't actually want to keep the main menu scene, then you can avoid all that and use `LoadSceneMode.Single`. That will unload the old scene, load the new scene and set the new scene to the active scene.

But what does the "active scene" actually mean? The documentation says:

> The currently active Scene is the Scene which will be used as the target for new GameObjects instantiated by scripts.

What you are apparently trying to do here is to use the "active scene" as a proxy for what state your game is currently in. This might not be the best idea, especially if combined with additive scene loading. When you want your game to behave differently depending on the current state it is in, then you might want to implement a proper state-handling mechanism. But when you just want your audio manager to behave differently in the main menu and in the game, then perhaps you don't need one audio manager with `DontDestroyOnLoad`. Perhaps what you might need are two audio managers with each one being a part of their respective scene.
> 1 votes

# Answer
To answer your side question first, You are trying to create a persistent class and for that what you can do is:

```
using UnityEngine;

public class UnitySingletonPersistent<T> : MonoBehaviour where T : Component
    {
        private static T instance;

        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = FindObjectOfType<T>();
                    if (instance == null)
                    {
                        var obj = new GameObject {hideFlags = HideFlags.HideAndDontSave};
                        instance = obj.AddComponent<T>();
                    }
                }

                return instance;
            }
        }

        public virtual void Awake()
        {
            DontDestroyOnLoad(gameObject);
            if (instance == null)
            {
                instance = this as T;
            }
            else
            {
                Destroy(gameObject);
            }
        }
    }

```

Now inherit from this like:

```
public class AudioManager : UnitySingletonPersistent<AudioManager>
{
   //Remove awake from here you don't need Don't Destroy On Load here.
}

```

Now towards your main question. The problem is that you are getting SceneManager.GetActiveScene() in the **Start()** which is why when in **Update** when even scene changes you don't have updated scene name.

Try Checking name like:

```
if (SceneManager.GetActiveScene().name == "Game" && currentScene == false)
{
   //Your rest of the code
}

```

OR you could update your **currentScene** variable every time you change the scene instead of doing that only once.

```
public void Start()
    {
        SceneManager.activeSceneChanged += ChangedActiveScene;
    }

private void ChangedActiveScene(Scene current, Scene next)
    {
        string currentName = current.name;

        if (currentName == null)
        {
            // Scene1 has been removed
            currentName = "Replaced";
        }

        Debug.Log("Scenes: " + currentName + ", " + next.name);
    }

```
> 0 votes

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


# Question
Title: Can't get ThirdPersonController player to stick to a moving platform
I've followed 10+ tutorials on setting up basic C# code to allow a player gameObject to stick to a moving platform (even followed the code verbatim) and nothing works. I added some debug print statements to the console to see when the moving platform detects a collision/trigger with the player gameObject and not even the debug print statements are getting triggered.

I'm using the Unity ThirdPersonController asset with the default "Playground" scene loaded.

I created a primitive cube shaped like a platform using the default Box collider. I DID NOT add rigidbody component since this makes the platform wobble when the player bumps into it. Then I added a script component to the platform as follows:

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

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

    }

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

    }

    private void OnCollisionEnter(Collision collision)
    {
        Debug.Log("Hello Collision");
    }

    private void OnTriggerEnter(Collider other)
    {
        Debug.Log("Hello Trigger");
        other.transform.parent = transform;
    }

    private void OnTriggerExit(Collider other)
    {
        Debug.Log("Goodbye Trigger");
        other.transform.parent = null;
    }
}

```

I used the animator to move the platform left and right. When I jump onto the platform, none of the Debug statements print to console. Does this mean collisions aren't being detected? I also added a second box collider that extends slightly above the platform and checked the box for "Is Trigger".

I'm new to Unity and don't understand why nothing I try is working despite copying tutorials online step by step.

Please help!

# Answer
Fixed. How the hell would anyone know to do this? Found in some youtube comments:

> For the people using a character controller that are having their characters not transform with the platform there's a simple fix!
>
> (Edit -\> Project Settings -\> Physics (or Physics 2d) -\> Auto Sync Transforms
>
> Newer versions of unity don't have Auto Sync Transforms enabled, so check the box and watch your code work!
> 1 votes

---
Tags: unity, movement, moving-platforms
---


# Question
Title: How can I efficiently store Vertex data in C#/XNA?
I am creating a terrain system using voxels in a somewhat minecraft-like style and I was wondering if there was anything I could do to increase the number of vertices I am able to store (and therefore render).

Based on different suggestions I have read I created a number of "chunks" of size 32x32x32 cubes and all of the vertices for these cubes are pre-calculated and stored in a VertexBuffer. I then have 7x7x7 of these creating a larger map. Therefore this is around 11 million cubes.

I was unable to render all 11 million cubes, so I removed any vertex in the buffer which would be completely hidden by an adjacent block (this removes all the interior/invisible surfaces/vertices). Overall this reduced the number of vertices by a factor of 36 in the simplified terrain example I am using!

However, this appears to be the absolute limit on the number of blocks I can render. This already takes about 1 GB of RAM according to the task manager (although the vertices themselves are closer to half of this - GC and all).

Do I have to simplify my terrain and/or accept this limit, or is there a better way to do this? I previously tried using instancing but that slowed down after only 20,000 cubes or so.

Thanks.

# Answer
I know this is an old post but I will send my reply for others to see. What you can do is possibly save ALL the chunks in their OWN chunk files on your computer. Have like two float/into variables

```
//disable the unseen chunks
float m_maxRenderDistance =100.0f;

// Load the necessary chunk files into your game BUT have them disabled unless player distance is near the m_maxRenderDistance
float m_maxStartLoadDistance =150.0f;

```

Of course since this post is old, you may have found a much better way of solving this. Just wanted to share what I have learned recently.
> 1 votes

---
Tags: xna, c#, vertex-arrays
---


title: Infinite Stairs Design

text:
# Question
Title: Infinite Stairs Design
In Unity, I'm trying to create a **puzzle** in a **2D platformer** game where the **player** has to face some **infinite stairs**. The **player** can move **left**, **right** and **jump**.

The idea is that at some point the player encounters some stairs that they try to climb. They climb, and climb, and climb and soon realize there is no end to them. At whatever point they decide to go back down the stairs they realize there are only a couple of them till they found themselves where they started.

Does anyone have any rough idea how something like this can be done?

# Answer
> 1 votes
1. Create two prefabs: "stairs" and "stairs with bottom and door". Both prefabs should be larger than a whole screen.
2. Create a scene with one instance of the "stairs with bottom and door" prefab and a "stairs" prefab ahead.
3. Whenever the player moves up, `Instantiate` a new stairs prefab ahead of them and `Destroy` the prefab below them.
4. When the player moves down, `Destroy` the prefab ahead of them and `Instantiate` the "stairs with bottom and door" prefab below them.

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


# Question
Title: How to queue a paid function to run in Unity after an IAP button purchase completes to fund it?
My app will feature tokens to fund some in app functions. If someone clicks a menu button to run a paid function and has insufficient tokens, they should be prompted with a new token purchase menu to buy more tokens. After purchasing sufficient tokens, the requested function that prompted the token purchase should then run automatically.

I am having trouble figuring out the best way to make the paid function automatically run after the tokens are purchased. The best way I could think of is as follows.

In my main menus I am instantiating buttons to run paid functions essentially as follows:

```
 GameObject menuOption = Instantiate(Resources.Load<GameObject>("Menu Text Toggle Option")) as GameObject;

        //BUILD IN THE CLICK FUNCTION
        menuOption.GetComponentInChildren<Button>().onClick.AddListener(delegate {

            if (userTokens >= costOfActivity) {
                userTokens -= costOfActivity;
                Debug.Log("PURCHASED FUNCTION OCCURS HERE");
                }

            else {
                Debug.Log("OPEN TOKEN PURCHASE MENU");
                BuildAndOpenTokenPurchaseMenu();
                IAPButton[] iapButtonList = tokenPurchaseMenu.GetComponentsInChildren<IAPButton>();

                  for (int i = 0; i < iapButtonList.Length; i++) {

                    //ADD PURCHASED FUNCTION TO RUN ON COMPLETION
                    iapButtonList[i].onPurchaseComplete.AddListener(delegate {
                        userTokens -= costOfActivity;
                        Debug.Log("PURCHASED FUNCTION OCCURS");
                        GameObject.Destroy(tokenPurchaseMenu);
                    });
                }
            }
        });

```

So in other words, when you click the action button in the paid function menu, it runs the desired function if you have sufficient tokens. However, if you don't have enough tokens, it generates a token purchase menu (eg. from a prefab) and opens this.

The IAP buttons in this freshly generated token purchase menu would just have actions to buy tokens.But in this script I add the function that needs to complete after that purchase is done as a second listener based on whatever button triggered it to generate and open.

The only way this works though is if I destroy the menu and rebuild it each time. Because otherwise if the token menu survives and is just "hidden" when not needed, I would just be adding more and more listeners to it for cumulative extra functions if it's triggered multiple times.

Destroying the token purchase menu and then re-instantiating solves this, but it's wasteful. I think this method would work. But I wonder if there's a better way to do it.

Does this make sense and how would you approach it?

eg. Is there some way I could use the same approach but just remove the extra added listener at the end rather than nuking the whole token purchase menu each time and rebuilding it from scratch?

Thoughts? Thanks.

---

So if I'm not clear, my code for general function purchase menu is:

1. Instantiate regular menu button in regular purchase function menu.
2. Build into that menu button the function to generate and open a token purchase menu if there are inadequate funds.
3. Have the token purchase menu generate from its own prefab with only basic token purchase functions built in to run on purchase completion.
4. In step #2, also then add a second listener to the token purchase IAP menu buttons in #3 to run whatever function prompted the creation of the token purchase menu.
5. Destroy the token purchase menu when done (as it now has extra listeners added to its IAP buttons that I don't want to stick around).

# Answer
I'd assume you considered removing your listeners once they've done their work?

```
IAPButton[] iapButtonList = tokenPurchaseMenu.GetComponentsInChildren<IAPButton>();

// Prepare a function to add as a listener on each purchase button.
UnityAction<Product> purchaseWhenDone = null;
purchaseWhenDone = (Product product) => {
    // Deduct the cost and execute the action, whatever it is.
    CompleteAction();

    // Clean up the listeners we added to all these buttons.
    foreach(var button in iapButtonList)
        button.onPurchaseComplete.RemoveListener(purchaseWhenDone);
};

// Add listeners to each button.
foreach(var button in iapButtonList)
    button.onPurchaseComplete.AddListener(purchaseWhenDone);

// Also remove these listeners if the player cancels out of the menu.
// TODO: Also respond to Escape / Back if those are used in your app.
var cancel = tokenPurchaseMenu.transform.Find("Cancel Button").GetComponent<Button>();

cancel.onClick.addEventListener(() => {
    foreach(var button in iapButtonList)
        button.onPurchaseComplete.RemoveListener(purchaseWhenDone);
});

```
> 1 votes

---
Tags: unity, unity-ui, menu, in-app-purchase
---


title: Wait for time Unity C# when called to

text:
# Question
Title: Wait for time Unity C# when called to
I am currently programming a custom programming language and using Unity to run it. My current issue is that while loops freeze the game when their done. Is there a simple way to wait until end of frame in unity or wait for time?

# Answer
> 2 votes
Instead of using a `while loop` in Unity, you need to use a `Coroutine`. To demonstrate how to do this, I will show you what you would normally do, and then show how a `coroutine` is different.

# Traditional While Loop Structure

```
void Loop()
{
    while(running)
    {
        // Do stuff here
    }
}

```

# Unity Coroutine Structure

```
IEnumerator Loop()
{
    while(condition)
    {
        // Do stuff here
        yield return null;
    }
}

```

# Example

The following code fades text continuously.

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

public class Transitions : MonoBehaviour
{
    Coroutine fade = null;
    public Text text;
    public float speed = 1;
    void Update()
    {
        if(fade == null)
            fade = StartCoroutine(Fade());
    }

    public IEnumerator Fade()
    {
        Color c = text.color;
        Color target = Color.clear;
        float a = text.color.a;
        while(a > 0)
        {
            a -= speed * Time.deltaTime;
            text.color = new Color(c.r, c.g, c.b, a);
            yield return null;
        }
        text.color = Color.clear;
        while(a < 1)
        {
            a += speed * Time.deltaTime;
            text.color = new Color(c.r, c.g, c.b, a);
            yield return null;
        }
        text.color = c;
        fade = null;
    }
}

```

# Explanation

*(What this does line by line)*

1. When we call `StartCoroutine(Fade());`, we assign it to the `fade` Coroutine variable. This variable holds a pointer to the coroutine.
2. When `fade` completes, we assign it to null to ensure it can be used again.
3. Now that fade is null, the update loop will execute a new iteration of the the `Fade()` Coroutine.

Credit goes to @DMGregory for correcting my use of bool locks and providing the explanation above.

# Valuable Tips

We can break out of the `Coroutine` using `yield break`;

If you do not `yield return null` inside the loop, the `coroutine` does not return between frames and will wait for the loop to end as in a normal `while loop`.

We can break out of the while loop in the `Coroutine`, by using break as per normal.

# Links

For more information regarding the proper implementation and use of coroutines:

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


# Question
Title: Having trouble implementing edge collapse operation with half-edge data structure
I'm trying to make a half-edge data structure to interact with meshes in 2D space in Unity but I'm having trouble with implementing an edge collapse operation that merges one vertex into its twin half-edge vertex.

The diagram below shows how the edge collapse code is supposed to work:

After using it in Unity with a basic mesh, it seems to work for a bit until it gives a null reference exception because a triangle I'm pointing to doesn't exist in this region:

```
            do
            {
                //merge the index of the specific triangle by overwriting vertB with vertA in the triangle mesh indices
                currentHE.SourceVert = sourceVertA;
                if (triangleMeshIndices[TriangleIndex * 3] == vertIndexB)
                {
                    triangleMeshIndices[TriangleIndex * 3] = vertIndexA;
                }
                else if (triangleMeshIndices[TriangleIndex * 3 + 1] == vertIndexB)
                {
                    triangleMeshIndices[TriangleIndex * 3 + 1] = vertIndexA;
                }
                else if (triangleMeshIndices[TriangleIndex * 3 + 2] == vertIndexB)
                {
                    triangleMeshIndices[TriangleIndex * 3 + 2] = vertIndexA;
                }

                currentHE = currentHE.Twin.Next;
            } while (currentHE != startHE);

```

Here's an example of how it works in Unity: https://i.imgur.com/rQymkBh.mp4

I really want to know what special cases I'm missing and as to why this happens on occasion. Could there be a more fool-proof way to implement it?

Reference material: https://jerryyin.info/geometry-processing-algorithms/half-edge/ https://kaba.hilvi.org/homepage/blog/halfedge/halfedge.htm

Here's the function in question:

```
        public void Collapse(HalfEdge targetEdge)
        {
            //don't proceed with the collapse if triangle is by any chance located on the bounds of the mesh
            if (targetEdge.SourceTF == null || IsBoundaryTriangle(targetEdge.SourceTF) ||
                IsBoundaryTriangle(targetEdge.Twin.SourceTF)) return;

            //reference necessary mesh info for the collapse

            //first triangle
            TriangleFace triA = targetEdge.SourceTF;

            HalfEdge halfEdgeA1 = targetEdge;
            HalfEdge halfEdgeA2 = halfEdgeA1.Next;
            HalfEdge halfEdgeA3 = halfEdgeA2.Next;

            HalfEdge halfEdgeTwinA2 = halfEdgeA2.Twin;
            HalfEdge halfEdgeTwinA3 = halfEdgeA3.Twin;

            Vertex sourceVertA = halfEdgeA1.SourceVert;

            //second triangle
            TriangleFace triB = targetEdge.Twin.SourceTF;

            HalfEdge halfEdgeB1 = targetEdge.Twin;
            HalfEdge halfEdgeB2 = halfEdgeB1.Next;
            HalfEdge halfEdgeB3 = halfEdgeB2.Next;

            HalfEdge halfEdgeTwinB2 = halfEdgeB2.Twin;
            HalfEdge halfEdgeTwinB3 = halfEdgeB3.Twin;

            Vertex sourceVertB = halfEdgeB1.SourceVert;

            //Set all of the surrounding edges of the twin's vertex to use target edge's vertex as a source instead for the merge
            HalfEdge startHE = sourceVertB.SourceHE;
            HalfEdge currentHE = startHE;

            //side verts
            Vertex sourceVertA3 = halfEdgeA3.SourceVert;
            Vertex sourceVertB3 = halfEdgeB3.SourceVert;

            int vertIndexA = sourceVertA.VertIndex;
            int vertIndexB = sourceVertB.VertIndex;

            do
            {
                //merge the index of the specific triangle by overwriting vertB with vertA in the triangle mesh indices
                currentHE.SourceVert = sourceVertA;
                if (triangleMeshIndices[TriangleIndex * 3] == vertIndexB)
                {
                    triangleMeshIndices[TriangleIndex * 3] = vertIndexA;
                }
                else if (triangleMeshIndices[TriangleIndex * 3 + 1] == vertIndexB)
                {
                    triangleMeshIndices[TriangleIndex * 3 + 1] = vertIndexA;
                }
                else if (triangleMeshIndices[TriangleIndex * 3 + 2] == vertIndexB)
                {
                    triangleMeshIndices[TriangleIndex * 3 + 2] = vertIndexA;
                }

                currentHE = currentHE.Twin.Next;
            } while (currentHE != startHE);

            //attach the twins and set the side verts

            halfEdgeTwinA2.SetTwin(halfEdgeTwinA3);
            halfEdgeTwinB2.SetTwin(halfEdgeTwinB3);

            sourceVertA3.SourceHE = halfEdgeTwinA2;
            sourceVertB3.SourceHE = halfEdgeTwinB2;

            //removal
            RemoveThisTriangle(triA);
            RemoveThisTriangle(triB);

            HalfEdges.Remove(halfEdgeA1.GetHashCode());
            HalfEdges.Remove(halfEdgeA2.GetHashCode());
            HalfEdges.Remove(halfEdgeA3.GetHashCode());

            HalfEdges.Remove(halfEdgeB1.GetHashCode());
            HalfEdges.Remove(halfEdgeB2.GetHashCode());
            HalfEdges.Remove(halfEdgeB3.GetHashCode());

            //remove vertex
            sourceVertB.RemoveThisVertex();

            //set the merged vertex's source edge to its twin
            sourceVertA.SourceHE = halfEdgeTwinA3;
        }

        public void RemoveThisTriangle(TriangleFace targetTriangle)
        {
            HalfEdge startHE = targetTriangle.SourceHE;
            HalfEdge currentHE = startHE;

            int triangleIndex = targetTriangle.TriangleIndex;

            do
            {
                currentHE.SourceTF = null;
                currentHE = currentHE.Next;
            } while (currentHE != startHE);

            //remove triangle object from list
            triangleFaces.RemoveAt(triangleIndex);

            //remove mesh indices using the triangle obj's index from the mesh list of triangle indices
            triangleMeshIndices.RemoveAt(triangleIndex * 3);
            triangleMeshIndices.RemoveAt(triangleIndex * 3);
            triangleMeshIndices.RemoveAt(triangleIndex * 3);

            //readjust indices for triangle obj list
            for (int i = 0; i < triangleFaces.Count; i++)
            {
                if (triangleIndex < triangleFaces[i].TriangleIndex)
                {
                    triangleFaces[i].TriangleIndex -= 1;
                }
            }
        }

        public bool IsBoundaryTriangle(TriangleFace triangle)
        {
            HalfEdge startHE = triangle.SourceHE;
            HalfEdge currentHE = startHE;

            do
            {
                if (currentHE.Twin.SourceTF == null) return true;
                currentHE = currentHE.Next;
            } while (currentHE != startHE);

            return false;
        }

```

# Answer
This seems like it would be more robust to implement as three separate operations: First collapse the edge to fuse the two vertices, but leaving triA and triB in place as degenerate two-vertex faces. Then for each of those faces, fuse them with the neighbouring face on either side to get rid of them. Those are simpler operations that are easier to get right, and that can be then be combined to create this more complex operation.
> 2 votes

---
Tags: unity, 2d, mesh, vertex
---


# Question
Title: Is it possible to have multiple simultaneous tweens within a LeanTween sequence?
I'm trying to create a sequence that controls multiple animating objects (ObjectA and ObjectB). I want it to look like this...

> Step 1: ObjectA moves to center, while rotating.
>
> Step 2: ObjectB moves to center.
>
> Step 3: ObjectA and ObjectB move together simultaneously to left

So my initial instinct was to do it all using a single sequence. However after reviewing all the documentation and examples I can find, I have not found a way to make a sequence in which you are running multiple tweens at a single step. For instance, as far as I can tell, you can't do anything like:

```
LTSeq sequence = LeanTween.Sequence();
//step 1
sequence.append( <Move ObjectA> AND <Rotate ObjectA>);//There is no way to do this?
//step 2
sequence.append( <Move ObjectB>);
//step 3
sequence.append (<Move ObjectA> AND <Move ObjectB>); //No way to do this either?

```

So I also tried making two sequences that would run simultaneously, like so:

```
LTSeq sequenceA = LeanTween.Sequence();
LTSeq sequenceB = LeanTween.Sequence();
//step1
sequenceA.append( <Move ObjectA>);
sequenceB.append( <Rotate ObjectA>);
//step 2
sequenceA.append( <Move ObjectB>);
sequenceB.append( <Wait> );
//step 3
sequenceA.append( <Move ObjectA>);
sequenceB.append( <Move ObjectB>);

```

But when I do this, Sequences A and B still occur sequentially even though they are separate objects, instead of simultaneously as expected.

Does anyone here know how to make LeanTween perform multiple simultaneous tweens within a sequence? I'm out of ideas.

# Answer
You are looking for the `insert` method, this allows you to branch off from the regular sequence and won't delay any future `append` calls.

You can find a usage of this in the GeneralSequencer.cs file inside Examples/Scripts in the LeanTween install. The relevant bit of code...

```
// Jump up
var seq = LeanTween.sequence();

seq.append( LeanTween.moveY( avatar1, avatar1.transform.localPosition.y + 6f, 1f).setEaseOutQuad() );

// Power up star, use insert when you want to branch off from the regular sequence (this does not push back the delay of other subsequent tweens)
seq.insert( LeanTween.alpha(star, 0f, 1f) );
seq.insert( LeanTween.scale( star, Vector3.one * 3f, 1f) );

// Rotate 360
seq.append( LeanTween.rotateAround( avatar1, Vector3.forward, 360f, 0.6f ).setEaseInBack() );

```
> 1 votes

---
Tags: unity, tweening
---


# Question
Title: How can I use Blender-style UVs (and not per-vertex) in OpenGL?
In Blender, UVs are stored "per face vertex", meaning that if you have a plane made of 2 triangles, you will have 2 faces, 4 vertices but 6 UV coordinates.

I made a basic export script, and exported UVs with help from the Blender Stack Exchange, since I do not know much about Blender UV format:

```
for p in mesh.polygons:
    for vert, loop in zip(p.vertices, p.loop_indices):
        for z in (mesh.uv_layers.active.data[loop].uv
            if mesh.uv_layers.active is not None else (0.0, 0.0)):  # uv
            f.write(struct.pack('f', z))

```

The UVs are stored as a `std::vector` of `vec2`s, in the engine, and uploaded to OpenGL like so:

```
glBufferData(GL_ARRAY_BUFFER, mdl.uvs.size()
    * sizeof(mdl.uv[0]), &mdl.uvs[0], GL_STATIC_DRAW);

```

How can I use the correct Blender UV format, without wasting memory, or turn the per face vertex UVs into per vertex UVs?

# Answer
> 2 votes
Roughly speaking, you can't. That's just not how GL or the like work. For every unique set of vertex attributes you want, you must duplicate the entire vertex.

That said, that's not necessarily what you need here. You don't want to duplicate vertices, I think, you want to throw away the seemingly extraneous UVs that Blender uses.

The file formats and structures supported by 3D content tools like Blender typically have to be converted into formats suitable for runtime. This is one of the reasons that your typical game's asset folder isn't just full of .3ds files and the like; those formats are optimized for editing, not for rendering.

I recommend that you just use a library like Open Asset Importer Library unless you are doing something very unique and special. It can import `.blend` files (as well as many others) which can be used to write a renderer-friendly format. You can use it to generate your own files or you can use it to just convert to an existing well-documented runtime-friendly format like `.md5`.

# Answer
> 0 votes
You can use the blender UV in openGL if you separate all faces:

(yes this will duplicate vertices used by two or more faces)

---

goto edit mode

mark all edges as sharp

---

goto object mode

assign and apply the "edge split" modifier

---

now all faces use unique verts and edges,

thus each vertex has its own UV coord

---
Tags: opengl, blender, uv-mapping
---


# Question
Title: How can I correctly map a texture onto a sphere?
I'm trying to make a 3d model of the Earth (it doesn't have to be a fully-accurate geoid), but whenever I try with a map as a material's albedo to do so, it looks kind of weird and wonky. I assume that this is because my map is in the wrong projection - so my question is, what projection should it be in?

# Answer
The default sphere in Unity has its UV coordinates mapped like this:

You can see that the "v" coordinate (green) acts like a latitude, increasing from 0 at the bottom of the sphere (black/red) to 1 at the top (green/yellow). The "u" coordinate (red) acts like a longitude, starting at 0 at the left (x-) side of the sphere and increasing counter-clockwise or "eastward" until it comes all the way back around at 1.

But at the end of the day the mesh is made of only so many triangles, so there are places where it can't perfectly follow the latitude/longitude mapping. At the top of the sphere you can see there are notches cut out, making a zig-zag: parts of the texture space get skipped over. That leads to some noticeable distortions at the poles:

As I explain in this answer, this is a limitation of affine texture mapping in general. Lines are only able to change directions at triangle edges, so it can't represent a smooth curving of a non-linear mapping inside an individual triangle. And an equirectangular projection (latitude-longitude) gets highly non-linear at the poles!

But that's not a problem. We can compute our own non-linear map projection in the shader. For instance, if we have a texture that uses equirectangular mapping, when we can modify the basic Surface Shader template to do that like so:

1. Add `vertex:vert` to the surface shader declaration to make a custom pre-processor for our vertices.

`#pragma surface surf Standard fullforwardshadows vertex:vert`
2. Add a `float3 direction` field to our `Input` data structure:

```
struct Input
{
    float2 uv_MainTex;
    float3 direction;
};

```
3. Populate this direction with the object space normal of this vertex

```
void vert(inout appdata_full v, out Input o) {
    UNITY_INITIALIZE_OUTPUT(Input, o);
    o.direction = v.normal;
}

```
4. Compute our own per-pixel UV using a non-linear projection in the surface shader function:

```
void surf (Input IN, inout SurfaceOutputStandard o)
{
    const float PI = 3.14159265359;
    // Puff out the direction to compensate for interpolation.
    float3 direction = normalize(IN.direction);

    // Get a longitude wrapping eastward from x-, in the range 0-1.
    float longitude = 0.5 - atan2(direction.z, direction.x) / (2.0f * PI);
    // Get a latitude wrapping northward from y-, in the range 0-1.
    float latitude = 0.5 + asin(direction.y) / PI;

    // Combine these into our own sampling coordinate pair.
    float2 customUV = float2(longitude, latitude);

    // Use them to sample our texture(s), instead of the defaults.
    fixed4 c = tex2D (_MainTex, customUV) * _Color;

    // ...

```

And now we get a proper non-linear mapping, with no more distortion at the poles, or zig-zagging where lines cross triangle boundaries:

You can do this with a shader graph too - you'd just use math nodes to do the same operations as the code above.

You're not limited to equirectangular mapping of course. You can use any map projection you like, just by putting the matching projection function into your shader.

Another strategy that works well is to store your spherical texture as a cubemap, then use a cubemap sample in `direction` rather than a conventional 2D texture sample. This can help get more even texel coverage around the sphere, as equirectangular mapping devotes a bit too much space to tiny regions at the poles.
> 4 votes

---
Tags: unity, maps, sphere
---


# Question
Title: Why is OnTriggerEnter not called when my objects do not have Rigidbodies?
I am trying to get my enemy to take damage, however it is not working. I know the reason: the box colliders on not triggering the `OnTriggerEnter` message. I do not know why. Here is my code:

```
using UnityEngine;

public class EnemyBaseScript : MonoBehaviour
{
    public float health;
    private Weapon weaponGettingHitBy;

    private void OnTriggerEnter(Collider col)
    {
        Debug.Log("OnTriggerEnter was called");
        if (col.gameObject.CompareTag("Weapon"))
        {
            weaponGettingHitBy = new Weapon(
               col.gameObject,
               col.gameObject.GetComponent<WeaponBaseScript>().damageDealing
            );
            health -= weaponGettingHitBy.damageDealt;

            Debug.Log("Took damage from weapon.");
        }
    }
}

```

The code for weapons

```

using UnityEngine;

public class WeaponBaseScript : MonoBehaviour
{
    public float damageDealing;
}

```

Images of the box colliders:

(I know that some of the box colliders are off it is because I was testing around, assume all are enabled)

# Answer
As you can see from the Collision action matrix in the documentation:

**Trigger messages are sent upon collision**

|  | Static
Collider | Rigidbody
Collider | Kinematic
Rigidbody
Collider | Static
Trigger
Collider | Rigidbody
Trigger
Collider | Kinematic
Rigidbody
Trigger
Collider |
| --- | --- | --- | --- | --- | --- | --- |
| **Static Collider** |  |  |  |  | Y | Y |
| **Rigidbody Collider** |  |  |  | Y | Y | Y |
| **Kinematic Rigidbody Collider** |  |  |  | Y | Y | Y |
| **Static Trigger
Collider** |  | Y | Y |  | Y | Y |
| **Rigidbody Trigger
Collider** | Y | Y | Y | Y | Y | Y |
| **Kinematic Rigidbody
Trigger Collider** | Y | Y | Y | Y | Y | Y |

In order to generate an `OnTriggerEnter(Collider other)` message, at least one of the colliders involved has to have the `isTrigger` flag set, and at least one of the objects involved has to have a `Rigidbody` attached (either at the same level or in one of its parents).

Colliders with no `Rigidbody` are considered "static" - the engine expects they will not move, and so it does not check for collisions between them. You should always use a `Rigidbody` on physics colliders that you will be moving. If you don't want the physics engine to integrate their velocity automatically, use the kinematic mode so you can keep full control of their movement while still getting collision checking.
> 6 votes

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


# Question
Title: Technology behind retrogames.cc video games
What is the technology used in embedding the games on the retrogames.cc site?

I managed to see an HTML tag, but I don't know how they are inserted, are they simulators of real games?

# Answer
If you right-click on a game on this site, you get this pop-up menu:

Clicking on "EmulatorJS v.0.4.24" takes you to this site explaining the JavaScript video game console emulator they use.

So, it seems like the information about how this is done is at your fingertips. What is it that you need to know that's not explicitly described here?
> 1 votes

---
Tags: javascript, html
---


# Question
Title: Should you avoid memory allocation and deallocation while the game is running?
I recently read this answer on this site, which says the following:

> making sure no allocation/deallocation is being done while the game is running is a golden rule of thumb.

I interpret this as meaning that you should do all the necessary heap allocation while the game is booting up, and arrange it in object pools that you then manage when the game is running. Is this statement correct? The reason I'm struggling to understand it is because I thought that that goes against one of the main reasons we use dynamic heap allocation in games.

That I know of, there are three main uses for using dynamic allocation on the heap:

1. You have data whose size cannot be know at compile time and needs to be dynamically allocated at runtime.
2. You need to store objects that take up a large amount of space and won't fit on the stack
3. You have data whose lifetime outlives the current scope and thus must be stored on the heap.

I was under the impression that one of the main reasons for heap storage being used in games was reason 1, that you can't know the size of data collections beforehand and therefore need to work with dynamic memory. But if all the heap data should be allocated while the game is booting up, then that can't be true.

So does this mean that the reason we use heap storage in games is actually just reason 2 and 3?

# Answer
> 3 votes
> I interpret this as meaning that you should do all the necessary heap allocation while the game is booting up, and arrange it in object pools that you then manage when the game is running. Is this statement correct?

Whenever you read that there is a "golden rule" which should "always" be followed, you should raise an eyebrow. Software engineering is more of an art than a science. Even the most recommended best practice is only the best course of action *most* of the time.

Allocating and deallocating memory a lot while the game is running **can** have a performance cost due to reducing memory locality. That performance cost **could** result in a measureable effect on framerate. That framerate **could** get too low for the game to be playable for **some** people in your target demographic.

But none of that will happen all the time. Not every game will turn into a slideshow the moment it has a tiny `malloc` in the main loop.

Object pools are a performance optimization. But it is an optimization which comes with costs. They require work to implement. The code gets more convoluted. Startup time might get longer. And you either impose an artificial limitation on how many objects you want to allow or need additional logic to change the pool size at runtime, which can cause performance hickups itself.

Whenever you consider to take a performance optimization measure, ask yourself:

* Do I actually need the performance?
* Will it actually have a measurable benefit in my particular situation?
* What is the cost of that performance optimization, now and for the future?
* Is the benefit worth that cost?

So focus on creating a playable game first, then worry about the performance.

Experienced programmers are able to anticipate certain performance problems in advance and avoid them in the first place by implementing patterns which mitigate them from the beginning. But anticipating which parts of your software architecture will eat how much performance when implemented in what way requires a lot of experience. So when you are still a beginner (less than 10 years of programming experience) you should rather implement in the most straight-forward way first, measure performance and optimize afterwards.

---
Tags: performance, software-engineering, optimization, data, memory
---


# Question
Title: Applying friction separately to forward and side directions
I'm making a movement-based, first-person 3D game where the player should be able to gain a lot of horizontal speed over time with WASD, but also will stop due to friction very quickly the moment they release their movement key. The player's current horizontal movement is a velocity stored in a 2-dimensional vector.

Due to the requirement of needing to stop fast, I have a high amount of friction applied (the velocity is multiplied by `0.7`.) However, in order to allow gaining high amounts of horizontal speed, the friction is much, much lower when the player is moving, `0.99`.

I intend to separate the friction for forward/back from the friction for left/right, as this allows the player finer control over the current directions they're moving in.

Unfortunately, my code is broken, resulting in it working exactly as I intend only when you're facing in a cardinal direction — every other time, you have far too much friction. At this point, I realise that I'm not really sure what I'm doing, and my guesses aren't panning out. **How do I correctly apply friction separately to the forwards/backwards and side directions?**

I don't really want to include it in the question, but in case it's necessary, here's my current code — JavaScript, with a custom Vec2 class.
`powXY` is `v1.x **= v2.x; v1.y **= v2.y`. Everything else should be self-explanatory.

const direction = this.CAMERA.rotation.y;
const forwardBackVector = Vec2.fromDirection(direction).abs();
const leftRightVector = Vec2.fromDirection(direction + Math.PI / 2).abs();

let forwardBackInput = 0;
let leftRightInput = 0;

if (this.KEYBOARD.isDown("KeyE"))
    forwardBackInput++;
if (this.KEYBOARD.isDown("KeyD"))
    forwardBackInput--;

if (this.KEYBOARD.isDown("KeyS"))
    leftRightInput++;
if (this.KEYBOARD.isDown("KeyF"))
    leftRightInput--;

let forwardBackFriction = new Vec2(this.FRICTION).powXY(...forwardBackVector.xy);
let leftRightFriction = new Vec2(this.FRICTION).powXY(...leftRightVector.xy);

const acceleration = Vec2.ZERO;
if (forwardBackInput) {
    const normalisedVector = Vec2.fromDirection(direction + (forwardBackInput === 1 ? 0 : Math.PI));
    const dot = this.horizontalVelocity.dot(normalisedVector) * this.horizontalVelocity.length();
    acceleration.add(normalisedVector
        .multiply(dot < this.SPEED_HORIZONTAL_CAP ? this.SPEED_HORIZONTAL_FAST : this.SPEED_HORIZONTAL)
        .multiply(delta)
        .multiply(leftRightInput ? 0.5 : 1));

    forwardBackFriction = new Vec2(this.FRICTION_MOVE).powXY(...forwardBackVector.xy);
}

if (leftRightInput) {
    const normalisedVector = Vec2.fromDirection(direction + Math.PI / 2 * leftRightInput);
    const dot = this.horizontalVelocity.dot(normalisedVector) * this.horizontalVelocity.length();
    acceleration.add(normalisedVector.copy()
        .multiply(dot < this.SPEED_HORIZONTAL_CAP ? this.SPEED_HORIZONTAL_FAST : this.SPEED_HORIZONTAL)
        .multiply(delta)
        .multiply(forwardBackInput ? 0.5 : 1));

    leftRightFriction = new Vec2(this.FRICTION_MOVE).powXY(...leftRightVector.xy);
}

this.horizontalVelocity.add(acceleration);

this.CAMERA.position.x -= this.horizontalVelocity.y * delta;
this.CAMERA.position.z -= this.horizontalVelocity.x * delta;

for (const friction of [forwardBackFriction, leftRightFriction]) {
    this.horizontalVelocity.x *= friction.x ** delta;
    this.horizontalVelocity.y *= friction.y ** delta;
}
```
</code></pre>

# Answer
This is actually quite simple to do with a dot product to project the velocity onto a unit vector, to get the component of the velocity pointing in that direction:

```
function getComponentInDirection(vector, unitDirection) {
    // I'm not sure how your vector library works, so I'll be conservative
    // and assume we need an explicit copy when we want to avoid modifying the argument.
    const component = unitDirection.copy();

    // Scale this vector to the length of the projection of the input onto this direction.
    // (Incidentally, this dot product is your speed along the given direction)
    component.multiply(unitDirection.dot(vector));
    return component;
}

```

With that in hand, you can split your velocity into two parts, scale each one separately, then add them back together again.

```
function applyDirectionalFriction(velocity, forwardDirection,
                                  forwardFriction, sidewaysFriction, delta)
{
    // Get the component facing forward/backward (assuming forwardDirection has length 1)
    const forwardVelocity = getComponentInDirection(velocity, forwardDirection);

    // Whatever remains after subtracting the forward velocity must be sideways.
    const sidewaysVelocity = (velocity.clone()).subtract(forwardVelocity);

    // Apply the respective friction values to each.
    forwardVelocity.multiply(forwardFriction ** delta);
    sidewaysVelocity.multiply(sidewaysFriction ** delta);

    // Re-combine into a finished velocity.
    return fowardVelocity.add(sidewaysVelocity);
}

```
> 1 votes

# Answer
I knew that I could get it to work with velocity on the x or y axes, but I had no idea how to fix it when your direction wasn't on those axes. So I had the idea to just rotate the velocity to be on the x/y axes, apply the friction, then rotate back. It feels a little overcomplicated calculation-wise, but it works, and it's comprehensible, so it seems like the way to go.

Here's my updated code:

```
const direction = this.CAMERA.rotation.y;

let forwardBackInput = 0;
let leftRightInput = 0;

if (this.KEYBOARD.isDown("KeyE"))
    forwardBackInput++;
if (this.KEYBOARD.isDown("KeyD"))
    forwardBackInput--;

if (this.KEYBOARD.isDown("KeyS"))
    leftRightInput++;
if (this.KEYBOARD.isDown("KeyF"))
    leftRightInput--;

let forwardBackFriction = this.FRICTION;
let leftRightFriction = this.FRICTION;

const acceleration = Vec2.ZERO;
if (forwardBackInput) {
    const normalisedVector = Vec2.fromDirection(direction + (forwardBackInput === 1 ? 0 : Math.PI));
    const dot = this.horizontalVelocity.dot(normalisedVector) * this.horizontalVelocity.length();
    acceleration.add(normalisedVector
        .multiply(dot < this.SPEED_HORIZONTAL_CAP ? this.SPEED_HORIZONTAL_FAST : this.SPEED_HORIZONTAL)
        .multiply(delta)
        .multiply(leftRightInput ? 0.5 : 1));

    forwardBackFriction = this.FRICTION_MOVE;
}

if (leftRightInput) {
    const normalisedVector = Vec2.fromDirection(direction + Math.PI / 2 * leftRightInput);
    const dot = this.horizontalVelocity.dot(normalisedVector) * this.horizontalVelocity.length();
    acceleration.add(normalisedVector.copy()
        .multiply(dot < this.SPEED_HORIZONTAL_CAP ? this.SPEED_HORIZONTAL_FAST : this.SPEED_HORIZONTAL)
        .multiply(delta)
        .multiply(forwardBackInput ? 0.5 : 1));

    leftRightFriction = this.FRICTION_MOVE;
}

this.horizontalVelocity.add(acceleration);

this.CAMERA.position.x -= this.horizontalVelocity.y * delta;
this.CAMERA.position.z -= this.horizontalVelocity.x * delta;

this.horizontalVelocity.rotate(-direction);
this.horizontalVelocity.x *= forwardBackFriction ** delta;
this.horizontalVelocity.y *= leftRightFriction ** delta;
this.horizontalVelocity.rotate(direction);

```
> 1 votes

---
Tags: physics, 3d
---


# Question
Title: How to play audio in Unity when a mobile game runs in the background or the screen is locked?
I am trying to make a 3D audio player with a retro cassette-like interface. The first thing is to make audio playable smartphone-wise, even when the game is in the background or when the screen is locked. The second is to allow the game to process its logic. I have playlists that the user combines via 3D tapes, dropping them in the "play next" bin, which is then executed with colliders, etc. I also have some features with 3D audio, which requires the scene to run in the background and send audio outside (considering audio players and audio listeners for 3D audio).

Is it possible to do these things I want using Unity?

# Answer
The actual answer to your question is, **no** you can't implement all the above features. That is, you can't implement them using Unity *only*.

Potentially, you can implement all the above features, both for the Android and iOS platforms. However, this requires you don't build the project within Unity. Instead, you need to: Export the project to Android Studio/Xcode. Add the additional features. Finally, create an app build.

Android and iOS development follow different workflows, and their export processes differ as well.

## Android

#### Activities vs. Services

Android apps mainly consist of Activities. They are the main building blocks for most apps. They have a lifecycle and manage callbacks and high-level logic. Usually, Activities feature the app UI and invoke events on user input. By design, they are active as long as they have focus and stop when users close, minimise them or switch to a different app.

On the other hand, Services perform tasks and long-running operations in the background. Users never interact with Services. If a Service is there to provide a service (pun not intended) or expose some data, there's a delegated Activity to receive that data and display it to users. In the case of audio streaming, the Service is only playing the audio, while an Activity or a widget can call functions on it to stop and resume playback.

Unity apps are Activities. Then, implementing background music playback in your app requires you to add it yourself, for Unity doesn't provide these low-level features. But, Android Studio does.

In this discussion on the Unity Forums, user **diogo\_gc** seems to have implemented a working solution successfully. They exported their Unity project to Android Studio, implemented the discussed code, and built the app. The discussion end dates back to 2018, so it's likely not to be obsolete yet.

#### Exporting the Project

The Android export process is straightforward. You select Gradle as Build System, enable the Export Project checkbox, and click the Export button.

The official Unity documentation describes this process in the **Exporting the Project** section. Also, this Unity support article discusses the same argument in detail, including how to later migrate a project to Android Studio (thus, how to import an existing Gradle project).

### iOS

An iOS app structure and architecture are quite different from Android. There might be similarities and correspondences amongst components, but in the end, they follow diverse philosophies. If you want to read more about it, you can check this article on the overview of iOS apps.

#### But, can it be done?

**Yes**, iOS devs too found a solution to work this out. Of course, there's no reason not to allow background music playback on this platform as well. However, as said above, you'll need to create a different implementation only for iOS, since the features you want to add work on a lower level than what Unity has to offer.

This whole discussion on the Unity Forums involves different proposals and further fixes to implement background audio playback. The last messages date back to 2021, which is very promising.

#### Exporting the Project

Anytime you build an iOS app, Unity creates an Xcode project. Then, you just need to load it within Xcode itself and build the app. Before doing so, you can also tweak some settings or even add new features. You can find more information about the structure of a Unity Xcode project in the official documentation.

Finally, the `BackgroundModesOptions` exposes some flags to tell iOS what the behaviour of your app is going to be when it is running in the background. It's likely not intended to be used on its own, but combined with additional programming in Unity and/or Xcode.
> 1 votes

---
Tags: unity, android, ios, mobile
---


# Question
Title: 2D topdown generating stairs (access) to generated hill
I'm doing 2d topdown procedurally generated world. I'm generating perlin height values, and when certain value is crossed I'm generating one level higher, while edging biomes creates cliff of the mountain. Cliffs cannot be crossed so now I'm curious how would I do access to the generated mountain. I've got stairs tiles but I need help finding proper way of finding correct place on the mountain to actually generate them.
**This is what mountain could look like :**

Obviously stairs can be generated only on places where mountain is facing down(where the cliff is). I'm not sure when is ideal time to actually do this. During generating perlin or when rendering cliff(but then there is problem to find correct spot in the mountain to generate them. **Also** There should be only some stairs in the mountain not in every single cliff facing down.

# Answer
> 1 votes
There may be a way to do this more simply during the conversion from noise to tiles, but here's a sketch of a way that could work starting from the tiles:

If, for each ring of cliffs, we had an array containing the coordinates of the downward facing edge tiles of that that ring, then it would be easy to just pick a random one of those and replace it with stairs.

If, for each ring of cliffs, we had an array containing the coordinates of the all of the edge tiles, then it would be easy to filter to just the downward facing ones.

So, If we can get, for each ring of cliffs, an array containing the coordinates of the all of the edge tiles then we'd know what to do. That's the hard part.

A conceptually simple method to get those rings is to first scan over all the tiles and collect the coordinates for the downward facing tiles.

Then, for each of those tiles have a loop look starting from that tile and looking in all directions for tiles that are part of the ring, (that is, the tile is any of the edge tiles) collecting the results into an array. This is similar to a standard flood-fill algorithm, but instead of painting a tile, push it into the ring.

As described you'll end up with many duplicate rings, so you can sort the coordinates in order to make them exactly the same and then remove the duplicates.

You should now have one array for each ring, which you can then filter down to the downward edges, and then randomly choose a place from that filtered list, as described above.

There's several places this could be sped up if needed, by reducing duplicate work, but that could be a separate question. Plus, once a slow version is implemented, you can write a faster version and confirm the results are the same on an example.

# Answer
> 2 votes
We can simplify Ryan1729's method (getting rid of the rings and sorting) like so:

1. Choose any tile that is not a downward-facing cliff as the start of a flood fill. Mark it visited and add it to an "open set".
2. While the open set is non-empty, remove a tile from the open set. For each of its neighbouring tiles not yet marked as visited...

* If the neighbour is a downward-facing cliff, mark it visited and add it to a "cliff list".
    * If the neighbour is at a different elevation, skip it.
    * Otherwise, mark it visited and add it to the open set.
3. Once you empty the open set, you've visited every tile that can be reached without crossing a cliff. Now it's time to punch some holes. Iterate over your cliff list in a random order...

* If the cliff has no unvisited neighbour above or below (ie. either both already visited, or it borders the edge of the map), remove it from the list and keep going - it's not needed to expand our reachable area.
    * When you find a cliff with an unvisited neighbour above or below, convert it to stairs, and add the unvisited tile it borders into your open set.
    * Doing this just once will give you a single entrance leading up each hill / down into each valley. Instead, you could randomly select some fraction of the cliff tiles with this property to convert to stairs (possibly checking that they're not already next to another stairway if you want to avoid clumps)
4. Once you've converted at least one cliff to stairs, loop back to 2, since our open set is non-empty again.
5. Once the open set and the cliff list are both empty, we've visited every cell in the map and punched holes in cliffs so that every hill or valley is connected.

---
Tags: 2d, procedural-generation, perlin-noise, pixel-art, top-down
---


title: Websockets Server for Unity3d

text:
# Question
Title: Websockets Server for Unity3d
Is there any way to implement websocket server, which I can run inside Unity3d standalone linux instance? I gonna connect to it directly from webpage (pure javascript, not Unity3d WebGL). I've tried to look for existing websockets libraries for C#, but the reason they does not fit because Unity3d can execute only Mono libraries with .NET 3.5 (.NET 4.6 in newest Unity3d 2017.1 release).

I have HttpListener server running fine, however for Websockets it needs lots of specific logic. Who knows any solution for this?

# Answer
Websocket sharp: https://github.com/sta/websocket-sharp

It has a unity version which I've used as part of a cross-platform library and on a couple of local multiplayer games, and worked well. I have not tried using the server part of it though - only the client.

That said are you sure you want to have a unity app be the server? It might be more trouble than it's worth to make it discoverable on anything but a local network.
> 3 votes

# Answer
`System.Net.WebSockets` seems to be completely built-in to .Net and freely available in Unity.

Here's a **full Websockets client for Unity** for example:

```
using System;
using System.Text;
using System.Threading;
using System.Net.WebSockets;
using UnityEngine;

public class Comms: MonoBehaviour {
    Uri u = new Uri("ws://blah blah.us-west-1.compute.amazonaws.com:3333");
    ClientWebSocket cws = null;
    ArraySegment<byte> buf = new ArraySegment<byte>(new byte[1024]);

    void Start() { Connect(); }

    async void Connect() {
        cws = new ClientWebSocket();
        try {
            await cws.ConnectAsync(u, CancellationToken.None);
            if (cws.State == WebSocketState.Open) Debug.Log("connected");
            SayHello();
            GetStuff();
        }
        catch (Exception e) { Debug.Log("woe " + e.Message); }
    }

    async void SayHello() {
        ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes("hello"));
        await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
    }

    async void GetStuff() {
        WebSocketReceiveResult r = await cws.ReceiveAsync(buf, CancellationToken.None);
        Debug.Log("Got: " + Encoding.UTF8.GetString(buf.Array, 0, r.Count));
        GetStuff();
    }
}

```

.

One side issue ...

# (Note - For anyone using that sample code, don't forget Unity has no threading. Using Debug.Log is just a trick for that demo.)

*The three "async" calls in the example happen on some other thread. Just as in Unity whenever you (say) start some calculation thread or use a plugin. When you get information "back" on those other threads, of course, you absolutely cannot access Unity again. (IE, you can't access any of the actual game objects, their component scripts, or the frame loop in any way in Unity). What you do is just "leave the information somewhere" for Unity to find. This is a basic of threading in Unity. (As explained at great length HERE for example.) Please note that in the example code above, I cheaply use "Debug.Log" (which you can use from any thread) as pseudocode.*

# Even more important, don't use my code above! :O

While my code is not wrong, ***it is not really complete. And there is a huge amount of work to do to really use WS from scratch.***

The only current library is: https://github.com/Marfusios/websocket-client

We changed a very large project from "my" raw .Net code, to that library. (Alternately I would have had to basically .. rewrite that whole library!)

# And here's what you have to do in Unity! You must use a ConcurrentQueue.

It is completely meaningless to process messages "instantly" in Unity: it is frame based!

Every arriving message: put it in a queue, and process them once each frame:

{Note that *threading* is irrelevant here. It makes no difference, at all, whether your processing that is getting the messages is on the "main" thread, another thread, many threads, or it is being handled by a quantum computer! Each message has to be queued in the frame system.}

```
someLibrary_aMessageHasArrived
    {
        incoming_messages.Enqueue( the message text );
    };

```

and ... this must of course be in a MonoBehavior ...

```
ConcurrentQueue<string> incoming_messages = new ConcurrentQueue<string>();
void Update()
{
    if (incoming_messages.TryDequeue(out var message))
    {
        Handle(message); .. your code for handling a message
    }
}

```

So that's what you do with real time messages to a Unity app. (Or any frame-based engine.)
> 10 votes

# Answer
2021 Answer: Another library which is also built on `System.Net.Websockets` like Fattie's linked Marfusios library, but is made for Unity is the following:

https://github.com/endel/NativeWebSocket

Contains a whole example which is quite simple to get up and running.
> 1 votes

---
Tags: unity, server, websocket
---


# Question
Title: Conway's game of life algorithm does not work
the `getNeighbors` and `isOutOfBounds` function works fine as far as my tests go but for some reason the game never works as intended and i did the rules according to this:

* Any live cell with two or three live neighbours survives.
* Any dead cell with three live neighbours becomes a live cell.
* All other live cells die in the next generation. Similarly, all other dead cells stay dead.

this is the `advance()` function of my game of life attempt:

```
var grid : MutableList<MutableList<Boolean>> // initialised in the constructor
    fun advance()
    {
        var iter = grid.iterator()
        var toSet = MutableList(grid.size)  { i-> iter.next()}
        var dieAmount = 0
        var reviveAmount = 0
        for( col in 0 until grid.size)
        {
            for( row in 0 until grid[0].size )
            {
                var neighbors = getNeighborCount(grid, col, row)

                if(!(neighbors == 2 || neighbors == 3))
                {
                    toSet[col][row] = false
                    dieAmount++
                }
                 if(neighbors == 3 && !grid[col][row])
                {
                    toSet[col][row] = true
                    reviveAmount++
                }
                else
                    toSet[col][row] = false

            }

        }
        //println("dieAmount: $dieAmount surviveAmount: $reviveAmount")
        grid = toSet
    }

```

and my functions:

```
    fun getNeighborCount(grid: MutableList<MutableList<Boolean>>, column:Int, row:Int) : Int
    {
        var toReturn = 0
        for(minorColumn in -1..1)
            for(minorRow in -1..1)
                if(!isOverBounds(grid,column + minorColumn, row +minorRow) &&  !(minorColumn == 0 && minorRow == 0))
                {
                    if(grid[column+minorColumn][row + minorRow])
                    {
                        toReturn++
                    }
                }
        return toReturn
    }

    fun <T> isOverBounds(args: MutableList<MutableList<T>>, colCheck: Int, rowCheck: Int) : Boolean
    {
        if(args.size < colCheck+1 ||colCheck < 0) return true
        if(args[0].size<rowCheck+1||rowCheck < 0) return true
        return false
    }

```

the game is initially at this state:

advancement 1:

and the sole cell disappears in the second

another example:

advancement 1:

advancement 2:

# Answer
> 2 votes
Your if statements are not correct.

Lets assume `neightbors = 2` (2 neightbors) and `grid[col][row] = true` (the cell is alive)

The rules states that "Any live cell with two or three live neighbours survives."

Lets check the if statements

* `if(!(neighbors == 2 || neighbors == 3))`: `if(!(true || false))`: `if(!true)`: `if(false)`: We don't take this branch
* `if(neighbors == 3 && !grid[col][row])`: `if(false && !true)`: `if(false && false)`: `if(false)`: We don't take this branch
* `else`: We take this branch, and set the new value to `false`. *This is incorrect.*

We need to implement these if statements following the rules, like

```
            if(grid[col][row] && (neighbors == 2 || neighbors == 3))
            {
                // Any live cell with two or three live neighbours survives.
                toSet[col][row] = true
            }
            else if(!grid[col][row] && neighbors == 3)
            {
                // Any dead cell with three live neighbours becomes a live cell.
                toSet[col][row] = true
                reviveAmount++
            }
            else if(grid[col][row])
            {
                // All other live cells die in the next generation.
                toSet[col][row] = false
                dieAmount++
            }
            else
            {
                // Similarly, all other dead cells stay dead.
                toSet[col][row] = false;
            }

```

---
Tags: kotlin
---