# Question
Title: How to fix cutting corner problem in A-star pathfinding
So this is a problem when doing diagonal jumps (checking diagonal neighbor nodes). In 2d it can be prevented by doing some checks, like if up and right is blocked, don't take up-right neighbor for calculations. But in 3d thous check become a bit to much and to tedious.. so if I still want diagonal paths, what could be a good solution?

# Answer
You have to solve this by fixing your logic for determining the possible edges between two nodes. This means that if you want to check a diagonal transition in 3d you need to check up to 6 different voxels for being passable.

If doing all the checks for every single diagonal edge transition becomes a performance bottleneck, then it can be a good idea to pre-compute all edges of your map once. Add a list of neighbors to each node. Do one pass where you determine all the neighbor nodes which can be reached from each node and put those in their lists. Your route finding algorithm then just needs to iterate that list of neighbors.

Another nice side-effect of this architecture is that it also becomes trivial to have your route finding algorithm account for unconventional movement methods like teleporters, jumps or one-way connections. You just need to add another edge to the list and the algorithm will handle it without you having to do anything. You don't even need to check anymore if the neighbor is out-of-bounds.
> 4 votes

# Answer
If a diagonal move is only valid when the orthogonal path is clear, then a simple way to avoid invalid diagonals is to never take a diagonal at all. Consider only orthogonal moves.

You don't exclude any valid solution paths that way: if an unobstructed diagonal is indeed the shortest path to your destination, then taking it as two (or three) orthogonal steps is also a valid solution path, and will be selected as the shortest out of the available orthogonal-only paths.

This also has the side benefit of reducing the branching factor of your search from 25 in 3D (26 cells to go to from here, at least one of them explored by the path we took to get here), down to 5.

Now, the obvious objection here is that this introduces unsightly stair-step kinks into the resulting path. But unnecessary kinked paths is a problem you already have with grid-based pathfinding, even when diagonals are allowed.

(Imagine your target is 30 tiles over and 10 tiles up in open space: we'd expect to go over 2, then diagonally 1, repeating to approximate the straight diagonal line to the target. But a pathfinder will typically return a kinked path that goes 20 over, then turns a corner to do the last 10 tiles diagonally. This is equivalently short, but doesn't look like the path a human would take)

So we usually apply a string pulling algorithm as a post process after the pathfinding has been done, to flatten out unnecessary corners and dead-reckon across spaces where we have line of sight to the next step of the path. In addition to flattening out deep corners like the 20-10 example above, this will also collapse our orthogonal pathing around a diagonal into a direct diagonal jump.

You still have to do equivalent neighbour-checking in the string-pulling algorithm to verify when it's valid to pull this little snag out of the path, but the savings is that you deal with this complexity only a linear number of times, where there are corners in your solution path, not a quadratic number of times for every cell you visit during your pathfinding search.

You can even do this string-pulling incrementally, as the agent follows the path: have it scan forward through the waypoints until it reaches one that's out of sight, then just dead-reckon to the point where it lost sight of the path. This spreads the cost and complexity over multiple frames. :)
> 3 votes

# Answer
From the comments you want to avoid a tangle of ifs in your neighbour generation and avoid the corner squeeze.

You can do that by keeping track of all possible neighbours and only generate neighbours using orthogonal movement but then generate extra neighbours based on the new neighbours but only keep those that are 1 set away:

```
generateNeighbours(node){
    neighbours = [];

    for(dim in {X,Y,Z}){
        newNode = node.move(dim, 1)
        if(newNode.isWalkable && !neighbours.contains(newNode)){
            neighbours.add(newNode);
        }
        newNode = node.move(dim, -1)
        if(newNode.isWalkable && !neighbours.contains(newNode)){
            neighbours.add(newNode);
        }
    }
    for(i in {1,2}) { //repeat dim-1 times.
        for(n in neighbours){
            for(dim in {X,Y,Z}){
                if(node.dist(dim) !=0) break; //already moved on this axis
                newNode = n.move(dim, 1)
                if(newNode.isWalkable && !neighbours.contains(newNode) && node.kingsDistance(n)==1){
                    neighbours.add(newNode);
                }
                newNode = node.move(dim, -1)
                if(newNode.isWalkable && !neighbours.contains(newNode) && node.kingsDistance(n)==1){
                    neighbours.add(newNode);
                }
            }
        }
    }
}

```

`kingsDistance` is the max of the difference on each axis.
> 0 votes

---
Tags: path-finding
---


# Question
Title: GLSL variables as main function params vs on their own line?
I am learning OpenGL and GLSL. I was taught that the in/out variables should be formatted like this:

```
in vec3 something;
out vec3 somethingElse;

int main()
{
    // etc...
}

```

However, I ran across code like this online (ShaderToy):

```
int main(in vec3 something, out vec3 somethingElse)
{
    Is there a difference?
}

```

Is there any difference?

# Answer
> 2 votes
Shadertoy code is used as part of a GLSL program for WebGL. There is additional code to make the GLSL program work that is not part of the Shadertoy code we write.

In Shadertoy, you will use:

```
void mainImage( out vec4 fragColor, in vec2 fragCoord );

```

To output the image. Please notice it is `mainImage` not `main`. You can write a fragment shader in GLSL that has a `main` that simply calls into `mainImage` copied from Shadertoy passing the correct values.

For the code to work you will also need to define some `uniform`s to match whatever Shadertoy inputs you are using (`iResolution`, `iTime`, etc...), and actually passing them to the shade program.

To replicate the output of shadertoy you will also need a simple vertex shader, and in fact pass geometry that cover the whole view. *There is also the chance you do not want to replicate the output, but use the code in some other way.*

---

If you read the Shadertoy documentation, you will find there is also `mainSound` and `mainVR`. Of couse, simply adding to a fragment shader won't work. They will need their own additional setup to be useful.

---
Tags: opengl, glsl
---


# Question
Title: Can't interact with anything in UI canvas, although it was working previously
I'm working on a menu with several buttons and input fields. For a while everything was working fine, but suddenly every button and input field is not reacting to being clicked on, as if everything's been disabled.

This problem is only occurring in one of my scenes. My canvas has a graphic raycaster and my buttons have methods attached to them.

# Answer
you need an active **EVENT SYSTEM** in your scene to be sure your UI works properly. adding a new canvas first checks that there is a **Event System**.if there is not, add a new one.

its possible that you have made a panel with checked **Raycast Target** that obscured that back panels. so you cant interact with them.
> 1 votes

# Answer
Switching my UI assets to a new canvas fixed the issue, but I'm still not sure why that was necessary. The new canvas is identical to the old in the inspector.
> 0 votes

---
Tags: unity, gui
---


# Question
Title: How can I change the hardness and blast resistance of Minecraft blocks?
I want to make the strength of the iron block and obsidian switch places, along with other changes to block strength and blast resistance. I am not allowed to swap the textures or anything like that. I need to actually change the values of each block.

To do this, I need to know where Minecraft stores the blast resistance and hardness.

Is decompilation required? If so, which class file do I need to look into?

# Answer
> *Info: You gave no information how you are making your mod so I assume you are using forge.*

All Blocks can be accessed via the `Block` class.

The attributes you want to change are called:

* Hardness: This defines how often you have to mine the block for it to break
* Resistance: This defines the Blast resistance

To set these you can use the provided setter functions, e.g.:

`Block.obsidian.setHardness(2.5);`

or

`Block.obsidian.setResistance (25);`

See the documentation for full explanation.
> 0 votes

---
Tags: java, minecraft-modding
---


# Question
Title: Is Unreal engine or Unity better for high graphics low file size mobile games?
My objective of learning game development is to make a 3d relatively high graphics mobile game but that should be in 150 mb. I don't know should I start with unity or unreal engine. I found that people say unreal engine is better for 3d games and unity is better for mobile game development. As I have no experience, can anyone suggest me an engine with some reasons?

# Answer
> 0 votes
If your making a mobile game that has to fit into 150 MB you probably won't be able to show the full graphics capabilities of any of those engines. As your objective is learning I would suggest you go with Unity as its much easier to get started and to find proper resources you will need for your game. Besides better\* resources, Unity will be easier to learn.

---
Tags: unity, 3d, unreal-4, mobile
---


title: Quadtree for AABB collision boxes

text:
# Question
Title: Quadtree for AABB collision boxes
I have a whole bunch of entities constantly being processed and testing for collisions. I've tried to optimize this by stopping certain entity types from checking each other, dead entities not being processed and entities not checking themselves, but with the more entities I had, the slower the processing goes.

What I need is a good, clean way of implementing AABB (axis aligned bounding box) quadtree support. A way to insert an AABB of any length, width and position into the quadtree, and queering an area.

Right now I have a very basic quadtree that only takes singular points but it's buggy and can only store points. If I have a wall entity, with an AABB that extends across the whole window, then the quadtree will only store it's X and Y value in one corner of the window so collisions on the other side of the window don't occur.

Right now, my quadtree is as follows:

Creation:

```
//--------------Quad Tree-----------------------
quadTree = new QuadTree(screenBoundry->X() + screenBoundry->W() / 2, //X
                        screenBoundry->Y() + screenBoundry->H() / 2, //Y
                        screenBoundry->W() / 2,                      //W
                        screenBoundry->H() / 2,                      //H
                        4);                                          //Capacity

//----------------------------

QuadTree::QuadTree(double x, double y, double w, double h, int capacity)
    : mo_boundry(0)
    , mo_i_capacity(0)
    , mo_v_points()
    , mo_b_divided(false)
    , mo_i_arrayCounter(0)
    , northEast()
    , northWest()
    , southEast()
    , southWest()
{
    mo_boundry = new Rectangle(x, y, w, h);
    mo_i_capacity = capacity;
    mo_b_divided = false;
}
QuadTree::~QuadTree()
{
    delete mo_boundry;
    mo_boundry = 0;
}

```

Insertion:

```
void QuadTree::ParseEntityList(std::vector<Entity*> entityList)
{
    for (int i = 0; i < static_cast<signed int>(entityList.size()); ++i) {
        Insert(entityList.at(i), entityList.at(i)->GetPos());
    }
}

void
QuadTree::Insert(Entity* entityToReference, Vector2* entityPoint) {

    //Check if point exists in boundry
    if (!mo_boundry->Contains(entityPoint)) {
        return;
    }

    //If points are under the limit then push
    if (mo_i_arrayCounter < mo_i_capacity) {
        mo_v_points[entityToReference] = entityPoint; //Add to map
        mo_i_arrayCounter++;
    }
    else {
        //If not divided then divide
        if (!mo_b_divided) {
            SubDivide();
        }

        northEast->Insert(entityToReference, entityPoint);
        northWest->Insert(entityToReference, entityPoint);
        southEast->Insert(entityToReference, entityPoint);
        southWest->Insert(entityToReference, entityPoint);
    }
}

```

Subdivision:

```
void
QuadTree::SubDivide() {
    double x = mo_boundry->X();
    double y = mo_boundry->Y();
    double w = mo_boundry->W() / 2;
    double h = mo_boundry->H() / 2;

    //Northwest boundry (x + w, y - h, w, h)
    //Northeast boundry (x - w, y - h, w, h)
    //Southwest boundry (x + w, y + h, w, h)
    //Southeast boundry (x - w, y + h, w, h)

    northEast = new QuadTree(x + w, y - h, w, h, mo_i_capacity);
    northWest = new QuadTree(x - w, y - h, w, h, mo_i_capacity);
    southEast = new QuadTree(x + w, y + h, w, h, mo_i_capacity);
    southWest = new QuadTree(x - w, y + h, w, h, mo_i_capacity);

    mo_b_divided = true;
}

```

Querying:

```
std::vector<Entity*>
QuadTree::Query(Rectangle* range, std::vector<Entity*> found)
{
    //The current range doesn't overlap this boundry
    if (!range->Overlaps(this->mo_boundry)) {
        return found;
    }

    //For each point in this current quad
    for (std::map<Entity*, Vector2*>::iterator it = mo_v_points.begin(); it != mo_v_points.end(); ++it) {
        if (range->Contains(it->second)) {
            found.push_back(it->first);
        }
    }

    if (mo_b_divided) {
        this->northEast->Query(range, found);
        this->northWest->Query(range, found);
        this->southEast->Query(range, found);
        this->southWest->Query(range, found);
    }

    return found;
}

```

Clearing per frame:

```
void
QuadTree::ClearTree()
{
    mo_v_points.clear();

    if (mo_b_divided) {
        this->northEast->ClearTree();
        delete northEast;
        northEast = 0;

        this->northWest->ClearTree();
        delete northWest;
        northWest = 0;

        this->southEast->ClearTree();
        delete southEast;
        southEast = 0;

        this->southWest->ClearTree();
        delete southWest;
        southWest = 0;
    }

    mo_i_arrayCounter = 0;
    mo_b_divided = false;
}

```

My Current solutions has a bunch of issue though.

1. Memory leaks like crazy.
2. For some reason, only stores points on the right side of the screen.
3. Doesn't support, or store AABB information for collision detection.

If anyone can give some direct answers, or some links to exactly this issue, then that would be great. I've searched around for a while now, and haven't found a solution for my exact problem or the ones I have found are usually extremely unreadable or very difficult to implement into my current solution.

Thanks heaps for any answers/help I can get

# Answer
> 2 votes
There are 2 ways to deal with boxes straddling a boundary. One is to keep the box in the vector of the node where it straddles the boundary and don't push it down. The other is to add the box to all subtrees it overlaps with.

For the second option all you need to do is change first if in `insert` to:

```
//Check if box overlaps boundary
if (!mo_boundry.Overlaps(entityAABB)) {
    return;
}

```

As an optimization when a large box gets inserted the overlaps the boundary you can try to move one of the smaller boxes in the local vector to the subtrees. Especially when the smaller box it's already fully contained within one of the subtrees. This does not need to happen during subdivision but can be done as you insert more Entities.

For the first you need to additionally check if the rectangle would overlap the boundary and if so don't push to the subtree. Here that previous optimization is mandatory.

---

A few more remarks:

you don't use the Mapness of your `mo_v_points`. Change it to a `std::vector<std::pair<Entity*, Rectangle>>` (You could even remove the Rectangle and get it from Entity in the loop). It's much more performant than the cache thrashing that `std::map` forces on you. Even if you need it as a map doing a quick linear search (`std::find_if`) on the vector is going to be faster than `std::map::find` for this use case.

Rectangle doesn't need to be held by pointer. Store it by value instead. (I suspect it's the same for the position in Entity).

I also see a lot of passing by pointer, for the pointer to Entity that is logical, for the position and range it isn't. Replace it with passing by const ref or by value for the small trivial structs.

Also you pass the result vector by value, this causes quite a few issues. For one it means that the subtrees don't actually add their results to the result vector but instead to a private copy. Instead pass the result vector by pointer. Or move the vector in to avoid the deep copy and capture the result:

```
found = this->northEast->Query(range, std::move(found));
found = this->northWest->Query(range, std::move(found));
found = this->southEast->Query(range, std::move(found));
found = this->southWest->Query(range, std::move(found));

```

To fix your leaks replace the raw pointer member fields with `std::unique_ptr` where you need the owning pointer semantics and by value where you don't need pointer semantics. Non-owning pointer can remain raw pointers (like the per-node vector holding pointers to Entities).

---
Tags: c++, collision-detection, optimization, sdl2, quadtree
---


# Question
Title: How to automatically test a game's mechanics without duplicating work?
I've heard and read enough programmers firmly advocating automatic tests. According to many, tests are themselves part of a code's functionality, untested code is broken and/or legacy by definition, long-term manual testing is more time-consuming and provides far weaker guarantees against failures than automatic testing... etc.

I'm trying to hobbystically develop a turn-based Pokemon-like game. While talking to a far more experienced developer I said that when I add a new attack I run my game, go into 1v1 combat, use this move and see if it does what its supposed to do. His answer was: *Why won't you instead write a test that goes into a 1v1 combat, uses this move and checks if it does what it's supposed to do? Doing what you're doing manually may be faster than writing tests if you do it once, twice, thrice. But after 10 times? One hundred times?*

I'm thinking about what he said. I'm thinking and I still don't feel convinced. About any other kind of project, perhaps. But a game?

Assume I'm adding lifesteal to a monster's attack. Problem is I'll have to **anyway** boot my game and play it! To see if it feels right, if it plays right, if not for anything else.

Tests on the other hand add maintenance cost: for example, once I (for balancement reasons) change the lifesteal coefficient, I'll have to reflect that change in tests. (Or I won't have to reflect this change in tests if I copy&paste the formula, parametrized by attack strength, lifesteal coefficient, etc, but doesn't this defeat the purpose of testing?)

Automatic tests are supposed to replace manual tests; but given I have to manually play my game anyway, isn't this duplication of work?

Or is my thinking wrong? What am I missing?

# Answer
> 4 votes
Testing is an investment in your future. While an individual test might duplicate some aspect of manual testing you are about to do in any given run of the game, a robust suite of tests can in the long run cover far more scenarios than that small bit of overlapping work (manual testing can also more effectively test more complex scenarios where writing automatic tests might be too difficult).

Writing tests is an overhead, yes. So is maintaining them when the things you are testing change. It's also much harder to retrofit tests onto a big project not built from scratch with that goal in mind, as there are some technical design choices that are less compatible with easy, isolated testing than others.

Whether or not that overhead is worth the benefit depends on you and the scale and scope of your project.

The payoff is that automated tests can be run automatically and require far, far less work on your part that equivalent manual testing coverage would. In your example, sure, you manually run the game and ad-hoc test your change.

But do you do it on every platform you are shipping on? On every build configuration? Automated tests can do so easily, which means you can catch errors that only manifest on one or two platforms/configurations that you don't regularly test more quickly.

Similarly, while you may ad-hoc test that one ability change, do you manually go back and ad-hoc test *every other ability*? Probably not, because you're operating under the assumption that you didn't make a change that could impact those other abilities. But you are a programmer, and therefore, you make mistakes ("bugs") and therefor you *could have* accidentally made your change in a such a way as to have unintentionally broke something you were not expecting. An automated test suite could catch that.

Granted, the value of the test suite is dependent on what you test and how, and there is a point of diminishing returns in the investment (100% test coverage is often impractical, for example).

For example, it's probably worthwhile to write a test to validate the results of a math function that presumes a left- or right-handed convention, as change in that function to prefer the other convention will probably destabilize a lot and should be flagged. But a test for the outcome of some damage calculation may not be a good candidate for a test, at least not early on when you are iterating rapidly on game balance. That sort of test is perhaps best added later, once balance has hardened a little, to alert you that you may have made a change that has balance implications.

# Answer
> 1 votes
First off, 100% test coverage is not a realistic goal, and games especially tend to incorporate elements that are difficult to test reliably, for example when aspects like timing, physics or (nontrivial) AI become involved. In addition, automated tests are neither infallible nor by definition superior to manual testing, so your friends' stance appears a little... overzealous to me.

Howver, that does not mean that games can't massively benefit from automated tests. A common approach in test automation is to prioritize areas that would benefit the most and work your way down the list until you reach a point where the efforts outweigh the advantages. Typical criteria are:

* How often does this code **change** / how likely is it to introduce a bug here?
* How **severe** are the consequences if it breaks?
* How **easy** is it to test?
* How **obvious** (or not) would a bug be during manual tests?

I'd recommend the following starting points:

### Sanity checks

If game stats and actions depend on complicated and/or frequently tweaked formulae or functions, it's rarely necessary to check for minor deviations (unless your game is really balanced on a knife's edge), and updating the test cases every time can take a lot of work. What you **do** want to guard against, however, are **gamebreaking** numbers and unexpected interactions. Say, an ability that does 20 times the expected damage on a critical hit, but only against a specific enemy type.

Instead of setting up a test case that checks the exact damage output and secondary effects of every attack, I would write a test that goes through all attacks and checks if the numbers are **within a specific range** that's appropriate for their power level. Tweaking an ability by 10% for balance reasons shouldn't cause any tests to fail, but extreme outliers (which are probably unintended) should.

### Core rules and algorithms

There will probably be pieces of code (say, the save/load mechanism, network code, pathfinding, core game rules...) that are critical to your game working as intended. They are also likely to interact with a lot of different modules, and thus be easily affected by changes to those. You might, for example, introduce a new enemy type, forget to serialize one of their stats and mess up the savegame format, which only becomes apparent during a longer playthrough, which you can't do after every little change.

For these central elements, automated tests are usually worth the effort because you absolutely don't want them to break.

### Rapid iteration

Few finished games look anything like their early versions. You will probably make some sweeping changes that affect most of the existing content in one way or another, for example by adding a new stat or game mechanic. This, essentially, resets the "tested and mature" status of all your code and assets and the amount of extra testing required will grow with the size of your game.

You can't just skip manual tests, of course. There's no replacement for actually playing your game (and having others play it as well). But having a battery of tests ready to go, even if they're imperfect and incomplete, can allow you to vet and tweak these sweeping changes *much* faster, and find many inconsistencies the second they are introduced.

You're not limited to testing for correctness, by the way. If you're worried about balance, a scipt that runs a battery of different combinations, items, matchups or whatever can yield a lot more valuable (and reliable) data points than a handful of manual tests.

# Answer
> 1 votes
> Problem is I'll have to anyway boot my game and play it! To see if it feels right, if it plays right, if not for anything else.

Yes, you need to do that while you are iterating on that specific situation you are implementing right now. But think ahead a couple years in the future. You might be working on a completely different aspect of the game and accidentally break this situation you though you had done. Are you going to test every single thing in your game after every change? Certainly not manually all by yourself. So how long will it take you to notice the bug? Will you then be able to easily connect it to that specific change you made? But if you have an automated test suit, you *can* easily test your entire codebase after every change.

> Tests on the other hand add maintenance cost: for example, once I (for balancement reasons) change the lifesteal coefficient, I'll have to reflect that change in tests.

Yes, and that's a good thing, because now you have to be aware of every ramification of your balance change.

Does the tutorial still play out the way you intended? Is that one boss fight still winnable with the intended strategy? Is that other boss still immune to life steal? In order to detect those problems you might have to play through your whole game from start to finish. But an automated test can tell you within seconds to minutes.

So an automated test allows you to go through every situation where the outcome is affected and confirm one by one that this is still the outcome you intended.

> Automatic tests are supposed to replace manual tests; but given I have to manually play my game anyway, isn't this duplication of work?

Automatic tests are not supposed to replace manual tests. They are supposed to augment them. While it can not replace the "how does it feel?" playtesting, it can save you a ton of work in regression testing (testing again and again if the things which used to work still work).

---
Tags: testing
---


# Question
Title: After creating the Build of my Game, part of the UI isnt interactable anymore
This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem.  When I start my game normally through the Unity Editor (is this the right name?), everything works fine. Everything is interactable and the functions behind the buttons, dropdowns etc work as well. Since I can't test resolutions, fullscreen inside the Unity Editor, I decided to build my game and test it there. Everything still works fine, but the Options A Dropdown (this shows the resolutions), the Fullscreen Button and Graphics Dropdown arent interactable anymore.

After some testing myself, I found out, that the functions still work. If I click on the volume slider and go up through the WASD Keys, then I can still use the UI Elements and functions behind them still work.

What I tried:

* I got the help to put my Event System to "Always enabled", which didnt helped.

Side Information:

* The dropdowns are from Textmesh Pro, dont know if this is important or not.

# Answer
Based on the comment I gave earlier, I'll write a more detailed answer here.

The description you gave often means that 'something' is in front of the buttons you are trying to interact with. If this only hapens in build, this could be because the build runs at another resolution or aspect ratio. When creating your UI, you should make sure that you support all resolutions that you want to support.

This problem is easy to spot when an Image is overlapping a Button, as you can see that on screen. But when a Tex Rect (not the actual text) is overlapping a Button, you can't see that in build (or game view), making it harder to spot whats going on while (by default) Text components do consume pointer input.

If this is indeed the problem, then there are 2 ways to fix this.

1. Make sure that the 'something' that is consuming the input doesn't consume input if it doesn't need to. For any graphic component, including Text components, this can be done by unchecking the 'Raycast target' checkbox. (For textmesh pro, this checkbox is under 'Extra Settings')
2. Make sure that the 'something' doesn't overlap the button. This involves changing values of a RectTransform, but which RectTransform and which values depends on your exact setup. This usually happens when you give something a fixed pixel size, which can unintentionally start to overlap other items when your screen gets smaller.

Option 2 would be the best fix for the actual problem in my opinion, that being said, option 1 is a simple quick fix and is something you could opt to do for performance reasons anyway.
> 0 votes

---
Tags: unity, gui
---


# Question
Title: Problem with the Layer System/Tilemap Layer from Unity
This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem.   My character overlaps with the upper wall, but doesnt with the lower wall. This is the right behaviour given the layers (seen in the picture). But I want him to be behind the lower wall AND in front of the upper wall.

Side Information:
\- The Wall Tile is one piece, which covers two tiles.
\- Movement is depended on the existents of a ground tile. The reason behind this is, that I wanted the character to always move one tile at a time. And since this is my first time with unity, that was the easiest way of doing it. So there is no actual interaction with the wall. No collsions or anything.
\- There are three Layers (Ground, Creature, Wall) and two tilemap layers (Ground and Wall) (see picture) and the character doesnt interact with the tilemaps at all, he just gets drawn above the ground tilemap layer.

What I see as answers:
\- Split the wall tile into two tiles and let the wall part be on another layer, then the roof part.
\- Split the character into two parts and do the same thing.
Both seem like a good way of solving it, but I dont even know where do start there. I think I can split the walls into two tiles, but I dont know if this is a good way to solve this issue. The other option, to split my character, there I really dont know where to start.

What I tried:
\- Trying around with layers and order in layers.
\- Trying around with the tile atlas (adding the sprite, removing tiles)

# Answer
You essentially have 3 options:

1.: Since your walls are 2 tiles high, you can simply set the top tile to render in front of the player and the bottom tile to render behind the player. If the player is less than 2 tiles tall, then this will work pretty well.

2.: Create 2 layers for the wall, one of them should render behind the player, the other in front. Then you can dynamically move the tiles from one layer to the other based on their relative y position from the player.

3.: Instead of using 2d tiles for the wall, make them 3d. A lot of games do this, e.g. Enter the gungeon:

This has the added benefit, that it makes lighting a lot easier
> 1 votes

# Answer
After following the help on this side https://forum.unity.com/threads/isometric-tilemap-sorting-issues.554914/#post-3692299 (thanks again DMGregory).
I changed the following things:  First of all the camera settings to Custom Axis and changed the Sort Axis. (try to change the Z Value, because many other had different values there.) After that I changed every layer to the same layer "Default" and put my player and walls on Order "1" (the ground on "0".) Then the Cell Size of your grid needs to have a Z Value of at least 1. Last Thing is that you need to change the sprit Pivot to custom and the sprite sort point to "pivot" for your player character.

After that it works fine.
> 0 votes

---
Tags: unity
---


# Question
Title: Array of script class references in inspector
I'm trying to remove the Reflection part of one of my scripts so it works in WebGL, however I am having some trouble.

Basically I need a way to store references to classes in an Inspector array so that I can then use AddComponent() to add them to an object I spawn.

The code I'm using uses arrays to hold different types of AI modules and then chooses a random set of modules and add them to an base enemy prefab. Previously I was using Reflection to create the array and add the modules but that doesn't seem to work in WebGL. Currently the modules are Monobehaviours but it is possible for me to make them normal classes.

# Answer
My best guess as to how to do this would be to use the `MonoScript` type to expose a list of script references in the Inspector. This type is in the `UnityEditor` namespace, so we need to smuggle the type information out of those objects to use at runtime:

```
[SerializeField]
System.Type[] _types;

#if UNITY_EDITOR
public UnityEditor.MonoScript[] _scripts;

private void OnValidate() {
    _types = new System.Type[_scripts.Length];

    for (int i = 0; i < _scripts.Length; i++)
        if(_scripts[i] != null)
            _types[i] = _scripts[i].GetClass();
}
#endif

public void AddComponentByIndex(GameObject host, int index) {
    host.AddComponent(_types[index]);
}

```

If serializing `System.Type` references, or the `System.Type` overload of `AddComponent` isn't working for you, we could instead store the names of the component types to use the `string` overload.

If neither works, then we might need to do something more drastic, like mapping our component types to enum values and using a switch statement to jump to the appropriate hard-coded `AddComponent<Foo>()`;
> 0 votes

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


# Question
Title: Taking cube from camera space to clip space, error in my math?
watching Ken Joy's Computer Graphics lectures on youtube. One thing I'm confused about is after he gets the cube from the camera space to clip space, from my calculations the cube doesn't look like that. I expected the cube to look like that pink parallelogram in my picture, if we assume the Z of the front-face of the cube to be -4/3 and the back-face to be -2 then the Ws come out to be 4/3 and 2 respectively. So can someone explain how after multiplying by the viewing matrix, the cube comes out to look like how Ken has it.

Ken's view matrix:

After view matrix has been applied:

What I think the side of the cube should look like(the pink parallelogram) after view matrix has been applied:

my reasoning is, after the perspective divide by W, the blue and green vectors should get truncated to create that pink parallelogram. So I'm struggling to understand this. Thanks in advance.

# Answer
> 0 votes
So I found that it was because of where I have the cube relative to my camera. So my picture would emphasize the bottom of the cube, as the cube is above the camera. But in his picture the cube is dead center to the camera so he'll see a square. If the cube was below the camera then the top would be emphasized. Same thing with the sides. I found 2 pictures that perfectly illustrate this transformation.

Before view transformation:

After view transformation:

---
Tags: opengl, camera, coordinates, perspective, clipping
---


# Question
Title: How to get consecutive voice clips to sound natural
In the game I'm working on I have to play several short consecutive voice-clips to form a complete sentence. Example (each \[\] bracket is a different voice clip):

\[Bob here,\] \[we're at\] \[some town\] \[and are on our way to\] \[some city\].

Stitching together different voice-clips like this makes it sound stilted and disconnected. This is because there are unnatural pauses when switching clips, and the pitch and tone of the speaker changes.

My current efforts include two methods for removing the unnatural pauses:

1. starting the next clip early if a silence is detected at the end of the preceding clip
2. skipping the first few milliseconds of the new clip up to the first detected 'sound'.

These work OK at removing the unnatural pausimh, but detecting what 'silence' is is difficult, especially when dealing with multiple voice-actors and microphones.

How could I make stitching together voice-clips sound more natural? Any advice would be appreciated. This has to be done in real-time inside the game (I'm using Unity), and can't be pre-processed or done ahead of time.

# Answer
you can assign multiple audio sources to one object. for exxample maximum 10 phrases in a sentence. so you have:

```
AudioSource[] Phrases;

void Awake()
{
  phrases[0] = GetComponents<AudioSource>()[0];
}

```

then you can get length of clip that check what is best place to start new phrase audio source. like this:

```
  phrases[1].Play(phrases[0].clip.length +or- someuLongValue);// for better syncing

```
> -1 votes

---
Tags: unity, audio, voice
---


# Question
Title: What does this Yellow Outline represent in Unity Text Mesh Pro?
What does this Yellow Outline Represent around Text Mesh Pro Text objects in Unity? I don't see any regarding them in the inspector making it so that I have eye-ball it in the scene view to make it smaller. But it's caused me nothing but trouble such as causing overlap issues with other Text Mesh Pro Text objects making only the most recently rendered button usable. What is it? And how do I modify it's values and/or make it go away?

# Answer
> 5 votes
These are 'margins'. In the inspector, you can find them under the 'extra settings' section. This is what the documentation says about them:

> The Margins values can be used to add some space between the text and the content bounds. You can also use negative margins, in which case the text can extend beyond the bounds of the container. You can also adjust the margins by dragging the handles of the yellow rectangle in the scene view.

You can find the settings here in the inspector: (visually, the 'Extra Settings' dropdown changed in a recent version of Unity. In older versions of textmesh pro, the 'Extra Settings' looked more like a button as in the linked documentation)

As for where you can use it for... Well, for most cases I think nesting them inside other RectTransforms and handling margins using RectTransforms works just as good and is more intuitive.

So far the only real use I found is when used in layout groups, where the layout groups control the text RectTransform size (Based on that text layout properties, and sinse the margins affect the preferred width/height layout properties, you can then easier apply margins for individual text components). But there might be many more use-cases that I don't know about.

If you really wan't to disable these gizmo's, you can. Note however that this will disable all gizmos of Textmesh pro (I'm not sure whether there are any others, but I'll add this warning in case I missed some), so I'd advise to simply leave the margins at 0 and ignore them. To disable, above the shene view, click the 'gizmos' drowpdown arrow. The under Scrips, uncheck 'TextMeshProUGUI' or 'TextMeshPro' depending on which one you use (You can re-check it later if you want them back).

# Answer
> 2 votes
It's like a bounding box for the text.

If you narrow it the text will overflow,

And here in the settings you can change what happens (like text going into a new line or creating dots ex ...)

---
Tags: unity, gui, unity-ui
---


title: Make character following another

text:
# Question
Title: Make character following another
What's a solid way to have a character stuck to another one?

I have a moving character (say *followed*) and I want a second one (say *follower*) to follow the first without chance of getting stuck into obstacles.

I thought that I could save every delta velocity vector of the *followed* and having the *follower* consuming one each frame after it reached its target's starting position.

More to say, dynamic obstacles could be an issue.

Since this sounds to me like a common topic (despite the fact that I'm having difficulties in finding answers), is there anyone who could enlighten me on a proper way of facing the issue?

**Edit**:

Since I'd like to describe something more like to an edge case of a pathfinding algorithm, consider the following:

* *follower* should always be at a fixed position related to *followed*
* *follower* must not necessarily interact with the environment the way *followed* does

# Answer
It sounds like you want one object to be "towed" behind the other, as though it were tethered to it by a free-swinging, rigid bar of a fixed length, and ignoring any obstacles along the way.

Instead of pathfinding around obstacles, or copying the leader's path exactly, this object will dead-reckon toward the leader, cutting corners when the leader turns, to follow the shortest path that maintains its fixed following distance. If the leader starts moving toward the follower, the follower will back up as though pushed by this tow rod, until the bar is nudged far enough to the left or right that it can swing around the leader again and resume the chase from the other side.

If that description matches your desired behaviour, then we can do this with a very simple trick:

```
// Get the vector pointing from the leader to the follower.
Vector offset = follower.position - leader.position;

// Scale this vector so that it's exactly as long as our desired distance.
offset = offset * followDistance / Length(offset);

// Snap the follower to the leader's position, shifted by this offset.
follower.position = leader.position + offset;

```

If you want to apply physics-based movement, then instead of setting the position directly on the last step here, you can use the desired change in position to compute a velocity that will bring the object there in the next time step. This will play nicer with collisions, if the follower is meant to push objects or be pushed.
> 3 votes

# Answer
It's pathfinding to a dynamic target. Every few frames you repath to find the new best path to the player.

doing frequent repaths to a close by target means that dynamic obstacles aren't that much of an issue.

Of course there is always the old cheat: teleport the character when it's offscreen instead of making it walk.
> 0 votes

---
Tags: algorithm
---


# Question
Title: How to get android permission call back in unity
I am using unity run time permission system and when i ask for specific permission at run time using this:

> Permission.RequestUserPermission("android.permission.WRITE\_EXTERNAL\_STORAGE");

then permission show up.

But now i want get permission callback that has user give the permission or not. I know that i can check for it using this:

> Permission.HasUserAuthorizedPermission("android.permission.WRITE\_EXTERNAL\_STORAGE")

But i want some thing more convenient then this.

# Answer
I would love if unity permission has call backs but unfortunately there is not. So i found a way around it.

When i ask for permission using:

> Permission.HasUserAuthorizedPermission("android.permission.WRITE\_EXTERNAL\_STORAGE");

Then android native popup come up which is asking for permission at that time unity application is out of focus. and when user allow or deny permission unity application come back to focus and you can detect when application go out or come int to focus using this:

> OnApplicationFocus(bool){}

So when my application come back to focus then i check for permission if application is allowed or not doing some thing like this:

```
OnApplicationFocus(bool)
{
     if (Permission.HasUserAuthorizedPermission("Your permission string"))
     {
         Debug.log("Permission Allowed");
     }else
     {
         Debug.log("Permission Denied");
      }
}

```

I hope this will help some in the future. and i am also hoping that unity will implements call backs to android permission.

Spacial Thanks to @DMGregory♦ for helping me out.
> 4 votes

# Answer
Hope this will work.

```
AndroidRuntimePermissions.Permission result = AndroidRuntimePermissions.RequestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    if (result == AndroidRuntimePermissions.Permission.Granted)
    {
        Debug.Log("We have permission to access external storage!");
        //Do whatever you want to do if permission granted
    }
    else
    {
        Debug.Log("Permission state: " + result);
        //Permission.RequestUserPermission(Permission.WRITE_EXTERNAL_STORAGE);
    }

```

It will shows request permission automatically and frame will stop until the execution of the request pop up. Then it will check for the permission status. You need to call this lines whenever you need permission.
> -1 votes

---
Tags: unity, c#, android, permission
---


title: Disabling RigidBody component

text:
# Question
Title: Disabling RigidBody component
I'm trying to create a mechanic in my puzzle game in which if the player clicks on one of the flying game objects, the object's gravity would be enabled and world physics would be applied to it. Initially, I thought I could use the 'enabled' feature to create such a mechanic but I noticed that the RigidBody class does not contain 'enabled'.

Could there be any other way that would allow me to disable the GameObject's gravity or RigidBody component when it is instantiated?

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

[RequireComponent(typeof(Rigidbody))]
public class Plane : MonoBehaviour
{
    private bool clicked = false;
    [SerializeField] private Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.enabled = false;
    }

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

    }
}

```

# Answer
You could do this by enabling and disabling the "isKinematic" property of the rigid body: For more information about "isKinematic" is here:

> rb.isKinematic = false;

or to enable it do it like this:

> rb.isKinematic = true;

here is your script:

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

[RequireComponent(typeof(Rigidbody))]
public class Plane : MonoBehaviour
{
    private bool clicked = false;
    [SerializeField] private Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.isKinematic = false;
    }

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

    }
}

```

I hope this will help.
> 0 votes

# Answer
Why you are not simply using useGravity to control the gravity of the GameObject?

> rb.useGravity = false;

or

> rb.useGravity = true;

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

[RequireComponent(typeof(Rigidbody))]
public class Plane : MonoBehaviour
{
    private bool clicked = false;
    [SerializeField] private Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.useGravity = false;
    }

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

    }
}

```
> 0 votes

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


title: Space game scene boundaries

text:
# Question
Title: Space game scene boundaries
I've been trying to add boundaries to my space game.

I've been following this tutorial with a sphere instead of a cube, but every time I start the game and move or rotate my ship it appears outside the sphere, as shown in the image:

The ship has a collider and a characterController.

Could anybody tell me what I'm doing wrong here? Thanks!

# Answer
> 1 votes
sphere restriction all means a distance from center point.

```
Vector3 center = new Vector3(0, 0, 0);
float thresholdDistance = 200;
private void Update()
{
    if (Vector3.Distance(transform.position, center) > thresholdDistance)
    {
        transform.LookAt(center);
    }
}

```

this code make the player to return to sphere zone when is further than a distance from center.

---
Tags: unity, collision-detection, collider
---


# Question
Title: MoveTowards giving two different results for same input - Unity
I have prefab and its hierarchy is as follows:

bird

-Outline

--mask

--filler

Now I am using this in `Update` to move the filler:

```
filler.gameObject.transform.position = Vector3.MoveTowards(
            filler.gameObject.transform.position,
            new Vector3(feedBar.gameObject.transform.position.x, -1.1f, filler.gameObject.transform.position.z),
            (1f / PlayerPrefs.GetFloat("timetofeedbird", 5)) * Time.deltaTime);

```

All the instantiated birds have movement in correct direction. But the last one has a movement in reverse direction.

Here is the GIF to explain the issue:

Any idea what the issue here?

# Answer
> 0 votes
So I solved this issue. I don't quite understand it but what did the trick for me was I changed the value of `maxDistanceDelta` to negative. And now its working as expected.

`filler.gameObject.transform.position = Vector3.MoveTowards(
 filler.gameObject.transform.position,
 new Vector3(feedBar.gameObject.transform.position.x, -1.1f,
 filler.gameObject.transform.position.z),
 -(1f / PlayerPrefs.GetFloat("timetofeedbird", 5)) * Time.deltaTime);`

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


# Question
Title: How to create a turn-based system with an unknown number of enemies?
This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem.

I want to create a turn-based system for my 2D Top/Down Roguelike. After the generation of the dungeon, there will be x enemies spawned based on chosen difficulty and chosen quest.

How should each turn look like?
Player for example is an Orc, so he gets 7 movement (meaning he can move 7 tiles). In his turn he can move for example 3 tiles, then attack, 2 tiles, use a potion and then uses his last 2 tiles of movement. And then he presses "End Turn" and then the enemies go through their turns (based on which type of creature they are). The player can skip his turn completely, attack and don't move or only move. But he always needs to press the "End Turn" button.

What I would do, to solve this issue:
I would create a boolean for every single enemy and the player, then turn them true or false. And whenever boolean is true, that person can do his turn. But to check this, I would need to put it in the "Update" method. So on every frame there would be x+1 checks (all enemies plus player), who can move or not.

A second idea would be to put the player and the enemy in an array, sort by speed variable (so who goes first, and who goes last) and then I would have my turn order without any boolean. But this still leaves the question, how I would prevent the player of moving or doing stuff while it is not his turn.

I don't think any of them would be a good idea. Since I use now Unity, I hope there is a better option for this. And just a heads up, English isn't my first language, but I hope you can understand me. I will happily answer any question.

# Answer
> 0 votes
### You'll need two subsystems -

the one chooses who'll be acting next, and the other handles his(her, its) turn until it is over. Since it is a turn-based game, no more than one entity can be active at once. This will simplify things for you.

---

### The choosing system

There are many ways to make it:

* A queue (the simplest). Just make it based on a queue. Its not necessary to use the `Queue` class (but you may). A list with a counter will do.
* A sorted queue. Based on entities' initiative. You'll need to carefully update the order when the initiative changes somewhere.
* A deck. It's the same as a queue, but shuffled after each full iteration. You may use Fisher-Yates shuffle or invent your own custom algorithm (not recomended).
* A priority queue. The key is the moment when an entity will become active, and the value is that entity itself. Take the entity with the eariest turn time, make a move, put it again with updated time, repeat. It time exceeds current time then wait, render and increment time. If the initiative changes, you remove that entity and insert it with new priority. This method is more flexible, but also more bug-prone.

---

### The updating system

The simplest way is to store the active entity there and call its update method repeatedly (if it derives from `MonoBehaviour` then use a different name for its update method).

If it's player controlled entity, check input here. If it's a bot, write its logic here.

Make it return a value: is the turn completed or not? If yes, put the entity back into queue and take the next. If no, just wait - it's what the world does here in turn-based games.

If your game has reactions, you will have to implement the concept of suspended turns. In that case you need a stack of active entities. If a reaction triggers, new entity is pushed to the stack. When its work is done, the suspended turn continues (or ends, depending on the code).

---

### Be careful

When an entity spawns, despawns or changes initiative, the choosing system should handle it (add, remove etc.). Incorrect code may update dead entities, skip entities or handle them twice like here:

```
entities: ABCD
active:    ^
it's B's turn!
during B's turn A was removed
entities: BCD
active:    ^
turn has ended, the counter is incremented as usual
entities: BCD
active:     ^
it's D's turn!

```

We skipped the entity C.

---
Tags: unity, turn-based
---


title: Writing Hull shader in directx

text:
# Question
Title: Writing Hull shader in directx
hey i am studying different types of shaders in directx. and it comes to hull shader. so i write hlsl codes for both constant hull shader and control point hull shader in same file in visual studio 2019 .

i compile this file and this is showing these errors

the shader type is hull shader and 5.0 model.

```
struct VS_OUT
{
    float3 pos : TEXCOORD0;
};

struct Patch
{
    float edgeTessFactor[3] : SV_TessFactor;
    float inTessFactor : SV_InsideTessFactor;
};

struct HS_OUTPUT
{
    float3 pos : TEXCOORD0;
};

Patch ConstantHS(InputPatch<VS_OUT,3> patch, uint pI:SV_PrimitiveID)
{
    Patch p;
    p.edgeTessFactor[0] = 3.0f;
    p.edgeTessFactor[1] = 3.0f;
    p.edgeTessFactor[2] = 3.0f;
    p.inTessFactor = 3.0f;

    return p;
}

[domain("tri")]
[partitioning("fractional_even")]
[outputtopology("triangle_cw")]
[outputcontrolpoints(3)]
[patchconstantfunc("ConstantHS")]
[maxtessfactor(16.0f)]
HS_OUTPUT ControlPointHS(InputPatch<VS_OUT, 3> patch, uint i : SV_OutputControlPointID, uint pI : SV_PrimitiveID)
{
    HS_OUTPUT output;
    output.pos = patch[i].pos;

    return output;
}

```

any advice would be really helpful.

# Answer
> 1 votes
You might need to set up the compiler to look for "ControlPointHS" as shader entry point function. By default, it's going to look for a function named "main".

---
Tags: directx, hlsl, tessellation, hull-shaders
---


# Question
Title: Erase save file when the game gets force closed Unity C#
Im making an old school arcade for android where you have to get the highest score between levels. At each level you can save the progress. If you die and have 0 lives left your save file gets deleted. However to prevent cheating I want the game to erase the save file when the player quits the game mid level instead of going back to the last save. What is the code for checking if the player force closed the game?

# Answer
**Only allow saving on quit and delete the save on load.**

A somewhat common approach to this sort of problem is to quit the game when you save. So for your case, when they player try to save the game they could be presented with two options:

1. Save and quit
2. Cancel

Then when the player returns to the game to load their save you can pop up a warning to the effect of "loading this save will delete it, are you sure you want to continue?"

**Note:** It should be noted that games with this sort of save system will typically have communities that share how to backup and restore your save in order to bypass this limitation. So while casual players may abide by your save restrictions, people who are actually fans of your game will likely try to circumvent it. As other answers have mentioned, often times it's not worth it to go through fancy hoops to protect offline single player games.
> 1 votes

# Answer
you cant prevent cheating in a offline game in any system of storage.

if you store it in ram, a hacker can read it and change it. look for trainers that are built.

even if you encrypt the saved or any important data, its possible to read it when its decrypted or before encryption.

if you see that online games cant be cheated because all logic and data is on server and user client only can send inputs.

even if your goal is not cheating, deleting a file and making a new one is not a good practice. you should manipulate contents in the file.

conclusion: for a game that is not still big enough to be valuable for cheating, dont worry about cheating. just make it, you can make it safe when its needed.
> 0 votes

---
Tags: unity, android
---


# Question
Title: How to set the runtime of an animation based on attack speed?
**Based on an answer I received on this question:**

How to make an action perform only after an animation has run?

I am using notifications in animations to perform certain commands/actions.

**See in the documentation:**

https://docs.unrealengine.com/en-US/Engine/Animation/Sequences/Notifies/index.html

**Before resorting to this site, I researched elsewhere for something about modifying the animation speed and the closest question I found was this:**

https://answers.unrealengine.com/questions/509654/how-do-you-change-the-ratespeed-of-animation.html

Simply changing the speed of the animation, I know how to do it, but I want to control its runtime. Sort of determining how much time the animation has to play.

**In the image below I show more or less the scenario I have:**

Note that the notification happens at the end of the animation (where I apply the damage).

So based on the speed I set for animation to perform, every time it's finished the notification happens, applying the damage.

**It turns out that the animation doesn't necessarily have the exact duration of an attack starting when the other one ends (the image below will make it easier to understand):**

There is one more scenario I imagined.

**In the latter case, assuming the animation is (usually) 1 second long, and the character has the maximum attack speed (I set the maximum to 2 attacks per second). So the animation would be running 2 times faster:**

But the attack speed will not always be a "simple" number, I would like to know how to calculate/set it time so I have no problems when the attack speed is any number.

**I want to know how to set the animation runtime and a time interval between the animation running.**

# Answer
**To find out the duration of the animation, just open it and look at this part of the screen:**

Another way to find out the duration is to divide the total number of frames by the framerate.

**In my case:**

180/24 =\> 7.5

**In the player animation blueprint on the state machine you will see an option called *Play Rate* (click on the pink circled location in the picture below):**

**This way you will be able to change the animation speed using the variable and constant values (State Machine):**
> 0 votes

---
Tags: animation, unreal-4
---


# Question
Title: How to access random material in a renderer besides first without cloning any materials except accessed one?
Clones only first material:

```
renderer.material

```

Clones all materials in the same renderer:

```
renderer.materials[0]

```

# Answer
It is by design. The solution is to clone a material manually and assign to sharedMaterial array. It doesn't affect other materials.

The next code will clone only second material, do you note you can't assign a new material directly, you must modify array:

```
Material[] materials = line.sharedMaterials;
materials[1] = Instantiate(materials[1]);
line.sharedMaterials = materials;

```
> 1 votes

---
Tags: unity, shaders, rendering, materials
---


# Question
Title: How to find perpendicular line given a line?
I have two points that form 1 line. I want to find a point that creates a perpendicular line.

Here is an image showing what I am looking for:

How do I find the red point to form a perpendicular line?

# Answer
when a given line with certain equation is give. it has slope of **m**. so the line that is perpendicular to it has slope of **-1/m**

check this link: https://www.mathsisfun.com/algebra/line-parallel-perpendicular.html

you have one point and find out the wanted slope so you can build equation of new line
> 1 votes

# Answer
There is not a specific answer to this question as stated. (Assuming that this is in 3d space, as the coordinates list three values.) Technically, there are infinite perpendicular lines rotated around the black line.

If you have a third point, you can use the Cross Product to get a perpendicular vector, like:

```
i = B - A;
j = C - A;
p = (i.y * j.z - i.z * j.y, i.z * j.x - i.x * j.y, i.x * j.y - i.y * j.x);
N = A + p;

```

Where *A*, *B*, and *C* are the points, and *i* and *j* are vectors representing their relationship. The vector *p* will point in the direction perpendicular to the three points and *N* will be the point relative to the original, as in the picture.

Given that in your question the *y* coordinate is 0 for both points, it seems you may be interested in an answer in 2d space. In 2d space, there are two possible answers. Given two points *A* and *B*:

```
v = B - A;
p0 = (v.y, -v.x);
p1 = (-v.y, v.x);

```

You can find more info in this answer

For the coordinates you specified, this would work if you ignore the *y* coordinate and use *z* in its place.
> 1 votes

# Answer
There is one LINE that solves this problem if this is a 2D question (supported because the known points in the image have '0's for y-coordinates, so your line will be entirely in XZ-plane). However, as a line is a set of infinitely many points, any point that is on the solution line will be a solution point.

You need a line through (-1.75, 0, -2.32), perpendicular to a line through (-1.75, 0, -2.32) and (0,0,0).

Considering only X and Z coordinates, slope of known line is the difference in Z-coordinates divided by difference in X-coordinates: m = (0-(-2.32))/(0-(-1.75)) = 232/175.

The perpendocular slope is

m\_perp = -1/m = -175/232.

To get the slope of the line ne in the XZ-plane perpendicular to this one, through (-1.75, 0, -2.32), use the perpendicular slope and the XZ coordinates of that point in the point-slope equation:

Z-Z0 = m\_perp(X-X0) Z - (-2.32) = (-175/232)\*(X - (-1.75)).

Solve for Z:

Z = -175X/232 - (175^2)/232 + 2.32

(I'm on a phone and don't want to break that down rn)

Now, ANY X coordinate you plug into this will return a valid Z coordinate, giving you a point (X,Z) on the line.
> 1 votes

---
Tags: mathematics, geometry
---


title: Codify user progress

text:
# Question
Title: Codify user progress
I want to generate a string-code for the user that represents his progress in the game (so he can load this state somewhere else). I don't want him to be able to guess the system and thus load a state which he hasn't yet achieved.

The following variables are involved:

* A number X between 1-30 representing the highest level he unlocked.
* For each level lower than X a boolean representing whether he made the level on hard or not.
* For each secret object he could have found (also roughly 30) another boolean.

My idea was to just build a binary number from all these but that's just way too easy for the user to hack. If he beats level 1 and then saves, he will see his code being something like 0x1, while having bet level 10 will be something like 0x200.

# Answer
If you want to prevent casual passcode guessing, add a couple checksum bits somewhere into the passcode. Calculate the value of these bits from the values of those bits which contain actual data. When you parse a passcode, check if the values of the checksum bits matches, and if not, reject the passcode.

You can do that with a stock hash algorithm or by making up your own. Inventing your own crypto algorithms is generally a bad idea for any serious security use-case, but in this case it doesn't matter, because this solution can not be hacker-proof anyway. Any determined hacker with too much time on their hands can figure out your checksum algorithm by decompiling the game executable and finding out how it verifies the checksum. You can not get a fully hacker-proof solution using only client-side means. So you can at least turn it into a fun cryptoanalysis challenge by inventing your own (weak) hash algorithm.
> 1 votes

---
Tags: algorithm, savegame, encryption
---


# Question
Title: Use floats or doubles when writing mobile games
I know for shaders, floats should be used because they are the optimal choice for performance. Doubles are slow and use more memory which isn't ideal for shaders. While floats are less accurate and are prone to float overlflows, the tradeoff for speed is ideal on mobile hardware.

But what about everywhere else in the code base not related to the shader pipeline? I'm writing an engine and use doubles for the delta update tick and try to keep all units relative to that data type so there's lots of places using doubles. Should I be using floats on mobile in the engine as well?

The engine is written in C++ language

# Answer
You'd be hard pressed to find a mobile GPU that could use doubles even if you wanted to, so that part of the choice is pretty much made for you.

There are only a few places where you might benefit from switching from single-precision floats in your game:

These would be the two most common examples of things you shouldn't try to store in a single-precision float, because they lose significant precision over the range you need to cover (in the first second of your game, you can represent the elapsed time to within \\$2^{-24}\\$ seconds, or tens of nanoseconds, but after 2.5 hours, you start to lose millisecond accuracy)

But that doesn't mean you need to use doubles necessarily. Integer types can handle these values just fine. (A 32-bit int can give you millisecond accuracy for 12 days of continuous play. 64-bit ints will last millions of years)

A ***delta* time value** will usually be on the order of 16 milliseconds, so storing it in a single precision float gives you precision to about \\$2^{-29}\\$s, which is still down to the level of nanoseconds — ie. probably well beyond the precision with which you can reliably time your code, signal your threads, or coordiante your graphics refresh anyway. Adding more precision here with a double is unlikely to improve your game in any measurable way.

So you can store your total elapsed time at high precision or using an integer type, compute your delta and convert to single-precision float once per frame, then use floats happily from there on.

Similarly for positions. Even with a huge world, if you break it up into chunks several km across or less, then single precision floats can locate a position relative to its parent chunk to a precision of less than a millimetre.

Relative offsets between objects (for computing headings and the like) are generally just fine to store in a float even out to immense distances. Your relative error, as compared to the total length of the vector, stays in a controlled range.

So, there's not much reason to turn to doubles as a default. I'd consider that only if you have a very particular need, where you've computed the precision of floats won't cut it, and keep your use of doubles contained to only the part of your game that actively needs it.
> 15 votes

---
Tags: architecture, memory-efficiency
---


title: Godot and getting files via HTTP

text:
# Question
Title: Godot and getting files via HTTP
So, I am wanting to use Godot to get a (binary) file using HTTP and then either save it or, even better, turn it into a Resource in memory that I can use. It'll be WAV files that I'm getting in return (trying to implement MaryTTS, which is running as a server on localhost). I had a look at the docs for HTTPRequest, but can't seem to get a working solution.

I do `$HTTPRequest.request("http://...")` when a keypress is made, and I have the `_on_HTTPRequest_request_completed()` function, but this never seems to be called. I tried with the function in the same Node as the request (as per the docs' example), and I also tried putting it as part of a script for the HTTPRequest Node. If I hit the triggering key fast enough, it gives an error ("HTTPRequest is processing a request"), but if I do it slower, it doesn't give that error, so it appears it is finishing. It just doesn't do anything when it finishes. HTTPRequest gives a return value of 0, which I assume means no error? (Or should this give me HTTP status codes?)

Any idea what I'm doing wrong? Can HTTPRequest handle binary files? How do I get this working?

(Any suggestions on a better way to implement MaryTTS are also welcome).

# Answer
Eventually managed to get this working, using HTTPClient instead of HTTPRequest.

I also implemented threading so it doesn't freeze the main thread.

Full code is here: https://pastebin.com/P1GYkvAX

---

Edit: As requested, some code samples. Basically it's a mix of the threading stuff here (https://docs.godotengine.org/en/3.1/tutorials/threads/using\_multiple\_threads.html) with HTTPClient from here (https://docs.godotengine.org/en/3.1/tutorials/networking/http\_client\_class.html)

```
func _ready():
    mutex = Mutex.new()
    semaphore = Semaphore.new()
    exit_thread = false

    thread = Thread.new()
    thread.start(self, "_thread_function", "")

func _thread_function(userdata):
    while true:
        semaphore.wait()

        mutex.lock()
        var should_exit = exit_thread
        mutex.unlock()

        if should_exit:
            break

        mutex.lock()
        _http_get_worker()
        mutex.unlock()

func http_get(url_passed = ""):
    url_path = url_passed
    semaphore.post()

func _exit_tree():
    mutex.lock()
    exit_thread = true
    mutex.unlock()

    semaphore.post()

    thread.wait_to_finish()

func _http_get_worker():

```

Followed by the HTTPClient code, followed by:

```
        var player = AudioStreamPlayer.new()
        self.add_child(player)
        var sound = AudioStreamSample.new()
        sound.data = rb # "rb" is the received HTTP data
        sound.format = AudioStreamSample.FORMAT_16_BITS
        sound.loop_mode = AudioStreamSample.LOOP_DISABLED
        sound.stereo = false
        sound.mix_rate = 16000
        player.stream = sound
        player.play()

```
> 1 votes

---
Tags: godot, http
---


# Question
Title: How to intentionally make an RPG maker game crash?
I'm currently working on a game project that involves tricking the user into thinking the game experienced a bug/glitch and crashed. The reason that I want to code this is that I want to hide the file size of the main game, thus separating it into two files. So I want the first file which has x amount of game to crash at a certain point. Then manually give the second half of the game to the user and they can continue on. It may seem a little pointless, but I think stylistically this is a neat concept to try.

# Answer
Intentionally causing a crash is a somewhat irresponsible way to develop software. Instead of actually making the game crash, simulate a crash. Use messed up graphics, fake BSOD, etc. Then simply close the application.

This approach allows you to have far more control over the style of the crash. Further, it doesn't introduce potential consequences of forcing an application crash on the end user's computer.
> 13 votes

# Answer
I would suggest you try this simple thing:

> Divide by zero.
> 4 votes

# Answer
It is indeed a irresponsible practice in game development. It's been done before- the fake crashes that is. And splitting the executable into 2 pieces then calling on another to open is just time wasted. You can make a intentional error, cause it to crash and proceed from there. But a better way is to just past a BSOD gif or animation over their screen. Have it throw it's self into full screen right before it happens and then just toss the photo on.
> 0 votes

# Answer
If you do want to make RPG Maker crash, it is not simple, as RPG Maker cannot usually crash through any kind of script call, or such. You can make a fake Error, and close the game, however, making the game crash, is basically impossible, unless it somehow occurs naturally.

The reason why, is when RPG Maker experiences a coding error, or bug, unlike most engines, will always throw a Code Error, then close itself, without any problems, besides that.
> 0 votes

# Answer
You can use a script call in an event:

`window.close()`
> 0 votes

---
Tags: rpg-maker
---


# Question
Title: Authenticating users without a username or password
I'm curious about what the process is for anonymously authenticating users when it comes to mobile games. There are quite a few examples out there, but the ones that immediately come to mind are Lords Mobile, Family Guy: Quest for Stuff, and Clash of Clans. When you first open the game, you're assigned an account id and that id is tied to your device until you choose to register an account with a password or sign in through some SSO service.

In that initial step where you're not creating a password or using SSO, how are these games making sure the requests are from both the user/device that they come from? Or is it that they actually don't?

I can imagine a simple setup where you're providing a key that needs to be refreshed every now and then just like you would with something like OAuth, but other than that you don't care that the user is who they say they are. After all, you're dealing with a request that already has to be validated for legality within the game rules.

# Answer
I cannot speak to how those games in particular work, but I have worked on other games that behave similarly. Quite simply, the client generates an anonymous id and password for you, similar to any normal profile creation, just without user input. That info is stored on the device. On iOS, it is possible for that data to be saved in the Keychain, where it will even survive the app being deleted and reinstalled. I don’t know if there is something similar on Android, but my guess is that there is.

Your profile can be associated with any number of identities. When you sign in with an SSO or similar, it simply adds your new identity to your existing profile.
> 3 votes

---
Tags: multiplayer, mobile, authentication
---


# Question
Title: Inheritance - accessing child class values
I want to use the same variable for five different child classes. It is basically a boolean that is true when a player purchases an item(represented by a child class) and false when the player is yet to purchase that item. Then save the bool status.

Can someone tell me how to do just that?

Do I create five different bool variables each on their respective classes(the child classes), then access them individually when a player wants to buy the item? If I change the bool value of a parent class, it'll change it across all of it's child class.

# Answer
If you have a member variable in a base class you want to be visible to the subclasses but not to any unrelated classes, then declare that variable as `protected`.

Example:

```
public abstract class Item {

     protected bool isBought;

     public abstract void Buy();
}

/*-------------------------------*/

public class Sword : Item {

     public void Buy() {
          if (isBought) {
               Console.log("You can only use one sword, there is no point in buying another one");
          } else {
               Console.log("You purchased a sword!");
               isBought = true;
          }
     }
}

/*-------------------------------*/

public class Shield : Item {

     public void Buy() {
          if (isBought) {
               Console.log("Shields are heavy. You can't carry more than one.");
          } else {
               Console.log("You purchased a shield!");
               isBought = true;
          }
     }
}

```

Note that each *instance* of Item has a separate value for `isBought`. So the code above assumes that each of those child-classes only has one instance. If you have multiple instances of `Sword`, the `isBought` status is traced for each of those separately.

If your architecture assumes that there can be multiple instances of Sword, but you only ever want the player to own one of them, then it gets a bit more complicated. In that case I would implement a separate class `Inventory` which keeps track of what the player owns and which has some public methods which can be used to check if the player does or does not have an item matching some criteria.
> 0 votes

# Answer
if you want to share a variable you should define it in parent or base class. if you define it protected or public, its accessible by all children children. its like you copy the variable in all of them.

basically in OOP low level components should depend on high level components with no inversion. so defining a variable in child class and access it in parent class breaks the rules(i didnt test it but it should be impossible)basically you instantiate concrete or low level classes.

if you think that way, your design is wrong. just read about (OOP, solid, Uncle Bob)
> 0 votes

# Answer
## Encapsulation

Another option is to use *encapsulation*. The base class decides whether an item can be bought, depending on whether the item has an owner. We do assert here that an item can have at most 1 owner.

```
public abstract class Item
{
    public Person Owner { get; private set; }
    public bool IsBought => Owner != null;

    protected abstract bool OnBuy(Person buyer);

    public bool Buy(Person buyer)
    {
        if (IsBought)
        {
            Console.WriteLine("The item already has an owner");
            return false;
        }
        var wasBought = OnBuy(buyer);
        if (wasBought)
        {
            Owner = buyer;
        }
        return wasBought;
    }
}

```

Derived classes are not allowed to bypass the policy that an item which has already been bought can be bought again, but they can add additional checks whether the item could be bought. For instance, a child cannot buy a sword.

```
public class Sword : Item
{
    protected override bool OnBuy(Person buyer)
    {
        if (buyer.IsChild)
        {
            Console.WriteLine("A child cannot buy a sword");
            return false;
        }

        Console.WriteLine($"{buyer.Name} bought a sword");
        return true;
    }
}

```

The `Person` class used in this example:

```
public class Person
{
    public string Name;
    public bool IsChild;
}

```
> 0 votes

---
Tags: unity, c#, unityscript, inheritance
---


# Question
Title: Is it bad to store other memory in a system, alongside the components buffer using an Entity-Component-System architecture (ECS)?
I'm currently writing a simple ECS architecture for an engine and I have the fundamentals in place but after reading up on this architecture, it is designed in such a way that the memory is contiguous for all of the components and systems.

My understanding is that the components should be stored right after each other so they are not somewhat fragmented in memory? So that way when I update all of the components, the cache prefetcher can help out performance by fetching the next lot of components (limited understanding) without jumping around.

```
class system1 final
{
public:
        //...

private:
    std::vector<component1>         m_components;
};

class system2 final
{
public:
        //...

private:
    std::vector<component2>         m_components;
};

```

Then in some manager, you would initialize the systems so that they are as close as possible in memory.

But what if I wanted to allocate additional memory in the systems? Like a few extra buffers for dealing with system-specific information. That would then separate the component buffers so they are no longer next to each other.

```
class system1 final
{
public:
        //...

private:
    std::vector<component1>         m_components;
    std::vector<int>                m_somebuffer;
    std::vector<int>                m_someOtherBuffer;
};

class system2 final
{
public:
        //...

private:
    std::vector<component2>         m_components;
};

```
* Would this cause any problems and does this break the whole ECS principle?
* What should I be considering here for maximum performance without stumbling on issues later?

I don't want to optimize prematurely but knowing what makes an architecture fast and somewhat optimal during development is an interesting topic for me. Any input is greatly appreciated.

# Answer
One goal of the ECS pattern is that *each system* has all its data closely together so that it doesn't get many cache misses when it iterates over the components it manages. So there is nothing wrong with systems having their own memory buffers for data only required by that system.

However, there is one thing in your architecture which is usually not what you do in an ECS-by-the-book architecture, and that's that each system owns the components it manages. You usually don't have a 1:1 relationship between systems and components. There are often components shared by multiple systems and systems which operate on multiple components. For example, you might have a system `MovementSystem` which uses the components `Position` and `Velocity` and a separate `CollisionSystem` system which uses the components `Position` and `BoundingBox`.

For that reason you usually manage the components by a separate class and then inject the component-arrays into the systems.
> 2 votes

---
Tags: c++, architecture
---


# Question
Title: Calling data from a java script object with a variable and dot format
I have a const object, player, and inside that, I have several things one of which is playerResources.

```
const player ={
    // other things
        playerResources:{
            tree1:{
                unlocked: true,
                level: 0,
                type: "Magic Tree",
                hp: 100,
                id: "#playerTree1Prog",
                did:"playerTree1",
                cid:"treeContainer1",
                yeild: 110,
                respawnRate: 1,
                resourceText: "Hits Remaining"
            }
       // more resources
      }
    }

```

Now I am trying to find a way to call these different resources values using a variable. Like this.

```
var LVL = player.playerResources.VAR.level;

```

I have tried it with how it is above, I have looked into Object.keys and several other things that looked like it might be a solution, but I'm 3 hours and a few hundred pages deep in Google. So I figured it was time to come to the experts.

here is my question: Is this even possible, and if it is what is it called and if you have the time how does one implement it.

# Answer
You can use the bracket format:

```
player.playerResources[VAR].level

```

E.g. if VAR is `"tree1"` it will return the level of the tree1 object inside playerResources
> 1 votes

---
Tags: javascript
---


# Question
Title: Get Closest point between a Box 3D and a Point
I have a point A (x, y, z), and a Box: Center (x, y, z), Size (Width, Height)

How to get the closest point in the box from the point A ?

In Unity I can create a bound, and I can find the non-rotated position like that:

```
Bounds bounds = _mesh.bounds;
Vector3 closestPoint = bounds.ClosestPoint(pointA);

```

But then If the bound is rotated, the result is not correct. So I have 2 options:

Find the way to rotate my closestPoint from the pivot. Find the math formula myleft.

If someone can help ! thanks.

EDIT: here a video: the red point is the one find with bound.ClosestPoint the yellow point is the one find with:

```
Vector3 closestPointInverse = _currentTarget.InverseTransformPoint(closestPoint);

```

https://youtu.be/RMRRtSaJv8w

I have also tryed to do my own rotateFromPivot function:

```
public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles)
    {
        return Quaternion.Euler(angles) * (point - pivot) + pivot;
    }

```

When I use it, I get the same result with the InverseTransformPoint method.

# Answer
> 1 votes
Note that I said "first" not "after" - you're using the transform method backwards.

```
Vector3 ClosestPointOnMeshOBB(MeshFilter meshFilter, Vector3 worldPoint) {
     // First, we transform the point into the local coordinate space of the mesh.
     var localPoint = meshFilter.transform.InverseTransformPoint(worldPoint);

     // Next, we compare it against the mesh's axis-aligned bounds in its local space.
     var localClosest = meshFilter.sharedMesh.bounds.ClosestPoint(localPoint);

     // Finally, we transform the local point back into world space.
     return meshFilter.transform.TransformPoint(localClosest);
}

```

# Answer
> 0 votes
you should use **colliders** and **raycast**. tray to make a box collider for you box mesh. then cast a ray from point to center of box.

```
  void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
               print(hit.point);

            }
        }
    }

```

`hit.point` is nearest point t you empty object or point.

---
Tags: unity, collision-detection, mathematics
---


# Question
Title: Unity3D: Mathf Lerp too fast when timescale increases
I have an image with a fill amount component controlled by a Mathf Lerp. The problem is, the time for completion of the Mathf Lerp function decreases more than expected when the timescale increases.

When the timescale is equal to 2 the function should take half the time to complete but it takes less than that. Any idea why?

```
public static float demolishTime = 6.0f

public void OnClickDemolish()
{
    InvokeRepeating("demolishProgress", 0f, 0.1f);
}

void demolishProgress()
{
    progress += (Time.deltaTime / demolishTime);
    demolishProgressBar[DemolishManager.demolishState].fillAmount = (float)Mathf.Lerp(0, 1, progress);
    if (progress >= 1) demolishCompleted();
}

```

# Answer
When you have a coroutine scheduled with `InvokeRepeating`, then the repetition frequency is affected by the current timescale. That means the delta-time adjustment in a InvokeRepeating routine is not necessary.
> 1 votes

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


title: Calculate normal angle in screen space

text:
# Question
Title: Calculate normal angle in screen space
I'm working on adding billboarded sprites to a game engine, but the engine allows for walking on curved terrain, like spheres. In order to look like the player is walking on the terrain, I want to start with the billboard, then rotate it around its origin (bottom centre) so that its up vector matches the *screenspace* normal of the terrain.

Here's a diagram of the general idea:

The billboarding works fine - passed the camera's rotation matrix to the sprite, and the poly quad's 0,0,0 is at the bottom centre of the canvas.

How can I get the angle between the normal and screenspace up?

I think it's a matter of projecting the normal with the MVP matrix, to get it as a 2D screenspace vector to calculate the angle from. But I'm not having much luck attempting to implement it.

The sprites take their positioning from the centre of the tiles, along with the normal. I'd also like to move the sprites down in the rotated axis, so that they cover the tile they're standing on.

Any other methods are welcome too.

# Answer
> 1 votes
```
worldNormal = modelMatrix * vertexNormal;

x = Dot(camera.right, worldNormal);
y = Dot(camera.up, worldNormal);

angleaRadians = Atan2(-x, y);

```

---
Tags: opengl, python, billboarding
---


# Question
Title: implementing magnet like system in unity
I'm implementing magnet like behavior in unity3d.
the red object have a script that add force to it toward a blue object.
to do that i use this code:

```
void FixedUpdate()
{
    float distance = Vector2.Distance(blue.transform.position, transform.position);
    speed = MAX_DISTANCE - distance;
    body2d.AddForce((blue.transform.position - transform.position).normalized * speed);
}

```

`MAX_DISTANCE` is maximum distance that red and blue object can have.

with this code i got this behavior :

but i don't want red object gets this far after reaching blue object i want red object to **decrease** it's speed and after maybe some shaking around blue object and eventually stop on blue object, how can i implement this?

**UPDATE**
red and blue objects can't collide with each other they just know their location.

# Answer
> 1 votes
You really shouldn't redefine physics, you already have Physics2D. What you need is a PointEffector2D on the blue object and a Rigidbody2D on the red object. Your red object also needs to have its drag and angularDrag set to something other than zero for a realistic effect. You can skip the angularDrag and leave it at zero but you might need it later on.

Since the object will get to a point where the distance is almost zero, you'll have (almost) infinite force at that point. In the following gif, the "blue" object has a `PointEffector2D` with the force -30 and a `CircleCollider2D` for the effector to use. The "red" ball on the outside has a `Rigidbody2D` with a mass of 1 and a drag of 0.25.

Here are the details of the objects (as I already had them at hand, I'm just putting them here for future reference). Be aware that you might or might not need a Collider2D on the "red" object, I'm not entirely sure.

So, when the object gets near enough to the point you want it to be (and when it's slow enough to stop), remove its Rigidbody2D, or just disable it, and set its position. You can also increase the drag your object has to a point where it'll stand still. This way you're ensuring that the object won't wobble. For example:

```
if(distanceBetweenObjects <= 0.1 && redObject.velocity < 1) {
redObject.Rigidbody2D.enabled = false;
redObject.transform.position = blueObject.transform.position;
}

```

You'll have to tweak the values and maybe the code but this is close enough.

# Answer
> 3 votes
I think what you're looking for is "damping." This is where you drain a little energy out of the system with each update step so that it settles into an equilibrium, rather than oscillating/vibrating forever.

You can do this by multiplying the velocity each frame by a value close to but less than one (the lower the value, the more sharply your object decelerates), or equivalently, by applying a force or acceleration that's a small negative multiple of the velocity.

# Answer
> 0 votes
In real world physics, the formula for magnetic force is roughly some constant divided by the *square* of the distance.
This means that the force starts low, but quickly starts to increases when the distance reaches 1. It becomes infinite when the distance is zero.
If you implement your formula this way, there will be no going back and forth, and it will be more realistic.

---
Tags: unity, physics, rigidbody
---


title: Backface culling in Unity

text:
# Question
Title: Backface culling in Unity
I am a Unity noob trying to recreate something I did a long time ago in raw OpenGL.

I draw a scene normally `glCullFace(GL_BACK)`, and then draw the walls a second time with face culling flipped `glCullFace(GL_BACK)` and a semi-transparent alpha to everything.

So my question is how to achieve this in Unity?

Can I basically set up Unity to draw the scene twice, the second time with the new culling mode, a global alpha and perhaps only drawing meshes that are children of node with a particular tag?

Or is there some better or other way to achieve this affect?

# Answer
You can create two materials for your walls. One normal, and one with a shader in the Transparent queue, with alpha blending, and front-face culling enabled, like so:

```
Tags {"Queue"="Transparent"}
Blend SrcAlpha OneMinusSrcAlpha
Cull Front

```

Attach both materials to your walls' renderer components (most renderers in Unity will accept an array of materials).

Unity will generate a pass for each material, drawing your walls with your opaque material in the Geometry queue, then later sorting & redrawing them with the translucent material in the Transparent queue, after all the opaque materials in the scene have been drawn.
> 2 votes

---
Tags: unity
---


title: Instancing with Directx11

text:
# Question
Title: Instancing with Directx11
I'm a total beginner with Directx/3D programming. I need help with implementing hardware instancing on Directx 11. I'm trying to render multiple cubes on the screen, to create some sort of Minecraft-esque voxel engine. The problem is, I don't know where to start to achieve this. This is how my "render frame" function looks:

```
void RenderFrame(void)
{
    D3DXMATRIX matView, matProjection;
    D3DXMATRIX matFinal;

    // create a view matrix
    D3DXMatrixLookAtLH(&matView,
    &D3DXVECTOR3(0.0f, 9.0f, 24.0f),   // the camera position
    &D3DXVECTOR3(0.0f, 0.0f, 0.0f),    // the look-at position
    &D3DXVECTOR3(0.0f, 1.0f, 0.0f));   // the up direction

    // create a projection matrix
    D3DXMatrixPerspectiveFovLH(&matProjection,
    (FLOAT)D3DXToRadian(45),                    // field of view
    (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio
    1.0f,                                       // near view-plane
    100.0f);                                    // far view-plane

    // create the final transform
    matFinal = matView * matProjection;

    devcon->ClearRenderTargetView(backbuffer, D3DXCOLOR(0.0f, 0.2f, 0.4f, 1.0f));

    devcon->ClearDepthStencilView(zbuffer, D3D11_CLEAR_DEPTH, 1.0f, 0);

    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    devcon->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
    devcon->IASetIndexBuffer(pIBuffer, DXGI_FORMAT_R32_UINT, 0);
    devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    devcon->UpdateSubresource(pCBuffer, 0, 0, &matFinal, 0, 0);
    devcon->DrawIndexed(24, 0, 0);

    swapchain->Present(0, 0);
}

```

Notice that there's a single vertex buffer containing the verteces of a cube, and index buffer containing its indeces. I want to render many (5000+) cubes on the screen at once on a single draw call, without performance issues, so I know instancing is the way to go, but I don't know how to implement it in my code. What changes do I need to do to my code in order to display multiple instances of the cube?

Thanks in advance!

# Answer
> 2 votes
Instancing is basically a technology that allows you to draw many instances using only GPU. You basically tell the GPU "draw this many instances of this buffer" and it does this by adding an additional shader input value called Instance ID (it's just an instance index). You do this by adding an additional element to your input layout:

```
static const D3D12_INPUT_ELEMENT_DESC s_inputElementDesc[] =
{
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
        { "NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
        { "SV_InstanceID",   0, DXGI_FORMAT_R32_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};

```

Note the `SV_` (system value) prefix before the semantic name. It basically means that this value can be added to the input layout of any shader except PS but only once in a draw call (I don't recommend adding it to anything else than a VS, instead just pass the value between pipeline stages).

After that modify the `VS_INPUT` structure in your shader:

```
struct VS_INPUT
{
    float4 Pos : POSITION;
    float3 Normal : NORMAL;
    uint Instance: SV_InstanceID;
};

```

Make sure to add your own logic that does something depending on the Instance ID or else all your instances will have the same vertices.

The last step is the draw call itself:

```
// The last argument is the vertex buffer increment; it is zero if you do all the processing on the GPU
pImmCtx->DrawIndexedInstanced(24, YOUR_INSTANCE_COUNT, 0, 0, 0);

```

Don't hesitate to ask questions in the comments if you don't fully understand my explanation.

---
Tags: c++, directx11
---