# Question
Title: Convert global 3d coordinate system to a local one with specific direction
Imagine a (x,y,z) coordinate system within a solar system, with (0,0,0) beeing the center of sun where Z axis goes thru both solar poles.

I'm standing on a planet inside a house within that solar system.

Now from my perspective Z axis is skewed in unknown direction depending on where exactly the planet is at this moment.

What would be the steps I should take to create a local coordinate system with (0,0,0) being the house and where Z axis is perpendicular to the ground/house, so that I would be able to convert coordinates from local to global.

I have the global coordinate of my house and directional vectors for where is up/forward/right for my house.

I have some limited knowledge of vector math and projecting vectors on other surfaces, but there is a gap in my understanding that keeps me from solving this.

```
local housePos = vec(getHouseWorldPosition())        -- (x,y,z) position of house in global cooridnates (housePos.x,housePos.y,housePos.z)

local vRight = vec(getHouseWorldOrientationRight())  -- X directional normalized vector
local vForw = vec(getHouseWorldOrientationForward()) -- Y directional normalized vector
local vUp = vec(getHouseWorldOrientationUp())        -- Z directional normalized vector

local playerPos = vec(getPlayerWorldPosition())      -- players position in global coordinates

--Now how to get players position in coordinate system relative to housePos, with Z axis going along vUp vector

```

# Answer
> 3 votes
Construct a matrix like so, where each vector is one column of the matrix:

\[ House's X+ direction | House's Y+ direction | House's Z+ direction | House's position\]

The fourth row should be \[0, 0, 0, 1\]

Since you're in Unreal with its right-handed coordinate system

* x -\> right
* y -\> back
* z -\> up

we can write this as:

$$M = \begin{bmatrix} houseRight.x & -houseForward.x & houseUp.x & housePosition.x\\ houseRight.y & -houseForward.y & houseUp.y & housePosition.y\\ houseRight.z & -houseForward.z & houseUp.z & housePosition.z\\ 0 & 0 & 0 & 1 \end{bmatrix}$$

Multiplying a vector \\$v\\$ like this:

$$v = \begin{bmatrix}v.x\\v.y\\v.z\\1\end{bmatrix}$$

by this matrix gives us...

$$M v = \begin{bmatrix} houseRight \cdot v.xyz &+& housePosition.x \\ -houseForward \cdot v.xyz &+& housePosition.y \\ houseUp \cdot v.xyz &+& housePosition.z \\ &1& \end{bmatrix}^T$$

...which takes a coordinate `v.xyz` from house-local coordinates to global coordinates. You can verify that...

* When `v = [0, 0, 0, 1]` (the origin), this matrix maps it to the center of the house - the `v.w = 1` coordinate gets multiplied by the house position column in the matrix, and the rest get zero'd-out
* As we increase `v.x`, the result `v'` moves along the house's X+ (right) direction, and so on for the Y (back) & Z (up)

To convert back from world coordinates to house-local coordinates, take the inverse of this matrix.

---
Tags: coordinates, unreal, linear-algebra
---


# Question
Title: why My canvas buttons are behind the object?
I don't want this to happen. Screen space overlay no problem, but when screen space camera does this.

# Answer
# ScreenSpace-Overlay

Rendering process:

```
Render GameObject1
Render GameObject2
Render GameObject3
...
Render Canvas

```

When using Screen Space overlay, first all GameObjects in the scene are rendered.The canvas is rendered last.

# ScreenSpace-Camera

When using Screen Space Camera, that means the camera treats the canvas like Gameobjects. U can treat it like a plane in 3D world except it is always perpendicular to the camera view direction.

Rendering process:

```
Render GameObject1
Render GameObject2
Render Canvas
Render GameObject3

```

The rendering order is from far to near to the camera.

In your case, you can just `Plane Distance` of your canvas settings. Make it smaller, so it is nearer to your camera. Thus make it in front of other GameObjects.
> 0 votes

---
Tags: unity
---


# Question
Title: Finding Closest of 8 Possible Angles to Theta Value
I'm working on creating a gesture recognition system, and I saw one simple implementation that isn't as accurate, but is really easy to implement. The idea is that you have a unit circle with the 8 significant angles (0, 45, 90, 135, 180, etc) and you map those angles to a value of 1-8. So 45 would be 2, 180 would be 5, etc. Then you just use the Levenshtein distance algorithm to find the closest matching gesture.

I have a prototype that is "almost" working, but I'm having some trouble getting the math functions to play nicely with my algorithm. Right now, I have a list of points representing segments of a defined size that make up the gesture. I iterate over these points and get the theta value of the segment like so:

```
start = points[i]
end = points[i + 1]
theta = math.atan2((p2[1] - p1[1]), (p2[0] - p1[0]))
theta = ((theta + (math.pi * 2)) % (math.pi * 2))

```

The math.pi correction is so that I'll have all positive radian values. Makes it a lot easier to compare them. I also have a list containing the radian equivalent values of \[0, 45, 90, 135, 180, 225, 270, 315, 360\]. I iterate over the segments and compare the theta value to each of those 8 directions (360 is a redundancy so that I can compare values greater than 315 to 0). I use the index of the direction + 1 to get my mapped value.

So if I have a drawing of a box like so:

Then according to the algorithm, I should get the values "1357" to indicate the directions being 0, 90, 180, and 270 degrees in change.

However, something seems to be off about the way I calculate my theta values, or the way I compare them, because for that drawing, I get "1753" indicating that it's flipping the theta values for the second and third lines (the vertical ones). Here is how I'm comparing the points:

```
for i in range(len(points) - 1):
    p1 = points[i]
    p2 = points[i + 1]
    theta = math.atan2((p2[1] - p1[1]), (p2[0] - p1[0]))
    theta = ((theta + TWO_PI) % TWO_PI)
    closest = 0
    cDiff = TWO_PI
    for i in range(len(DIRECTIONS)):
        direction = DIRECTIONS[i]
        diff = abs(direction - theta)
        if diff < cDiff:
            cDiff = diff
            closest = I
    if closest == (len(DIRECTIONS) - 1):
        dir.append(1)
    else:
        dir.append(closest + 1)

```

So my theta values seem to be increasing clockwise, rather than counter-clockwise, so for the following angle:

...I would expect the theta value to be (pi / 4), but instead, it seems to be (7pi / 4).

Can anyone spot a flaw in my logic? This same math works in my game written in Java. Are Python's math functions different somehow?

**Edit:** Added a diagram to explain the encoded gesture movement values.

# Answer
> 0 votes
Uh...

```
for i in...
    for i in...

```

You have two loop variables with the same name. This is probably playing havoc with your execution.

Then this:

```
closest = I

```

That `I` isn't declared anywhere. It isn't either of the two loop iterators.

---
Tags: python, pygame, trigonometry
---


# Question
Title: What is the most efficient method to load 2D dynamic chunks?
# Information/context

I'm writing a 2D sandbox game - similar to Terraria. The world is made up of many chunks, in a variable like this:

```
vector<Chunk> chunks;

```

There's no need to go *too* in depth about the `Chunk` class, but each chunk has these members:

```
int x, y;
Block blocks[256];

```

When a chunk is initialized, the blocks are all set (with a Perlin noise based algorithm.) There are 256 blocks per every chunk because **a chunk is a 16x16 area filled with blocks.** To the loading of the chunks, the members of the `Block` class are irrelevant.

# Question

As the player walks around the world, I obviously need new chunks to load for them to explore. I don't think it needs saying but I shouldn't load every chunk in the world at once because:

* It would be *incredibly* inefficient to render (even with **my current system of block culling,**) and
* I don't know how many chunks will be in the world - there can be a huge amount, basically as many as the player wants to load.

I've tried a few different (but similar) ways to load and unload the chunks, but none of them worked very well. The main problem with both was that they sometimes gave segmentation faults.

**What's the best way to dynamically load and unload chunks in a world?**

By "best", I mean the most performance-efficient method.

Keep in mind I can easily load a chunk at any position - this isn't the problem. I just want a way of deciding *which* chunks to load.

# Answer
You are best off loading the chunks around the player. You are already on the right track with your system, and you don't need to make any significant additions.

What you're currently already doing is storing each chunk's world coordinate. All you have to do is to get the player's chunk coordinate and load chunks that are nearby.

There are two ways of doing this, either you need to track chunk coordinates in every object that uses them (that means the player, the objects on the map like monsters and items), or simply extend your position type to include chunk coordinates and just use that for every position in the game (don't forget to override all the operators you use, the bare minimum you'll need is addition/subtraction, scalar multiplication and division, as well as a method to correct any values out of bounds).

After you have that, you simply run a method every now and then that checks what chunks should be visible, loads the missing ones and unloads the invisible ones.

Depending on your game, putting all of that on the same thread that runs your update loop might be not the best idea so you might want to separate some of that into an extra thread.

I have achieved decent results with a n array (vector in C++ parlance I suppose?) that contains currently loaded blocks, which is consulted and the blocks rendered and updated as needed by the game. There's also a method that runs every time the player crosses a chunk border, which checks player's location and fills a queue with the coordinates of chunks that must be loaded, and removes any chunks that aren't used anymore. I also have a separate thread which checks the queue and loads chunks based on those coordinates.
> 1 votes

---
Tags: c++, 2d, loading, open-world
---


# Question
Title: What do game developers do when they have to port their DirectX games to PS4/Switch?
I'm not a game developer (hope to be one day though!) and was wondering how devs handle porting their games that use DirectX to PS4/Switch? From what I know neither supports DirectX, only OpenGL, and Vulkan. Do the devs just have to recreate their game with OpenGL or Vulkan? That seems like a lot of work. I'd imagine it would probably be a fairly common scenario, especially with AAA games so I'd assume that there would be something somebody has made to make it easier?

# Answer
Yes, porting games between platforms is a lot of work.

Typically it involves writing an abstraction layer, so game-specific code never references a DirectX or other platform-specific code directly. Instead it will direct its request to this intermediate layer. When done right, the vast majority of the game code will have no idea if it's running on DirectX or something else.

The old DirectX-specific code will become one version of the implementation of this layer, and the devs will create another version for the new platform - serving the same interface to the rest of the game, with different internals to match the new system.

At compile time, either version of these intermediate layers can be swapped-in, to compile a binary for one platform or another.

Now of course it's not a simple task, since different platforms and APIs work in different ways or make different assumptions. So there's a lot of work in establishing a common set of operations that the abstraction layer can efficiently map to one platform's implementation or the other.

DirectX shader code might need to be re-written for the new platform, or the team might use a transpiler to produce modified shader code automatically for most cases, and only hand-fix the problem cases.

Assets like textures might also need to be re-baked to suit the compression formats or memory size characteristics needed by the new platform. When porting to mobile, assets might also need to be exported at different resolutions to suit different screens. Sometimes an artist or other asset creator will need to make custom versions to support the new platform, like simpler meshes for weaker graphics hardware.

The amount of work involved in all this is one reason why established, cross-platform engines are so attractive. They've already done *most of* this hard work, so you have fewer steps required to port your game to a new platform (though usually there are still at least a few issues to sort out, since platforms don't just differ in rendering, but also input devices, vibration, player account management, online/store systems, achievements, console settings, certification requirements, etc...)
> 12 votes

# Answer
Having done so several times, I can say that porting the graphics part from PC to (modern) consoles, depending on how the PC code was written, could be relatively straightforward, or very hard.

Just like the differences between modern DirectX and OpenGL are not -that- big (from an API point of view), the several APIs for consoles also use similar architectures, and in general, porting a game from PC to consoles will mostly consist of changing the API calls, changing some of the platform-specific code, and fixing unusual things that might have worked on PC, but no longer work on your console. DMGregory's answer covers what you need to do pretty well.

That said, in my experience, the majority of effort in porting an (indie) game to consoles comes from porting the non-graphics stuff, where the underlying assumptions about how the platform works can be very different between platforms.

This is aggravated with the fact that consoles often have a long and very strict list of technical requirements that your game will be checked against, and has to pass, before it is allowed on the game store (PlayStation Store/Nintendo eShop). Some of these requirements will come and bite you where you least expect it.

For example, saved game data is stored in files in PC, and you might want to show a file open/file save dialog to let the user choose where to save their game. In some consoles, saved game data is not stored with the file IO API (`fopen`, `fread`, `fwrite`, etc.), but uses a special API, with a different GUI, and different concepts altogether.

Furthermore, you might have been able to save data on PC with simple synchronous calls; on consoles, on consoles you might be required to correctly save data asynchronously, and handle all errors appropriately. Depending on how you did saved games before, this might require you to re-engineer the parts where you are saving data in your game.

Another example is achievements/trophies. You can make a game for PC without the concept of achievements/trophies. When you move to consoles, you might be required to do so, and therefore you have to start from even planning what the achievements/trophies will be, where they will be unlocked, and add the code to do so.

Just like these examples, there are many, many, many requirements that have different assumptions on PCs and consoles, and in my experience these take much more effort to resolve, compared to the graphics API differences, which are comparatively straightforward.

If you're porting a game from PC to consoles, I do recommend you budget enough time to do all of this, especially if this is the first time you're working for a specific platform.
> 2 votes

---
Tags: rendering, porting, playstation4
---


# Question
Title: Touching screen not working for move object or print message
It's simple, i want to move an object when i touch the screen, but code's not working, i tried to just put a console printing on it, but nothing happens:

```
void Update()
{
   if (Input.touchCount > 0)
   {
     Debug.Log("Touch");
   }
}

```

What am i doing wrong ?, thanks in advance !!

# Answer
> 1 votes
Use this standard touch code for mobile devices. You have to test it on a real device. If you use **print** or **debug.log** you have to use logcat on windows cmd to see logs on your computer, but you can simply make a UI text to display your test result.

```
void Update ()
{
    int activeTouches = Input.touchCount;

    if (activeTouches > 0) {
        print (activeTouches + " touch(es) detected");

        for (int i = 0; i < activeTouches; i++) {
            Touch touch = Input.GetTouch (i);

            print ("Touch index " + touch.fingerId + " detected at position " + touch.position);

            switch (touch.phase) {
            case TouchPhase.Began:
                print ("User did touch the screen");
                break;
            case TouchPhase.Moved:
                print ("User dragging or moving his finger");
                break;
            case TouchPhase.Ended:
                print ("User did lift up his finger");
                break;
            }
        }
    }
}

```

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


# Question
Title: How do developers get their money with Steam Direct?
**Here's what I know:**
Steam is a digital distribution platform developed and owned by the Valve corporation. Steam is mostly known for its video games, XR software, and game development programs. Earlier, the products that were to be published to Steam were decided by the method of voting. This system was called Steam Greenlight. Now, a developer can just *pay* a sum of IN₹ 7,000 (US$ 100) and publish his/her product to Steam directly. This new system is called 'Steam Direct'.

**Here's what I need to know:**

* In the new system of Steam Direct, do developers get *any* money off every copy of their product(s) sold on Steam?
* If they do, what percentage of money is kept by Steam (or taken away for taxes and/or other purposes) and what percentage is given to the developers of the product?
* If developers do get money by selling their products on Steam, what is the most common means by which they receive payments?

# Answer
I'd definitely recommend reading the Steamworks documentation, it's mostly open, and there's a whole section on the financial side of things.

> In the new system of Steam Direct, do developers get any money off every copy of their product(s) sold on Steam?
>
> If they do, what percentage of money is kept by Steam (or taken away for taxes and/or other purposes) and what percentage is given to the developers of the product?

I cannot find this information from the docs, so I believe this falls under the NDA.

> If developers do get money by selling their products on Steam, what is the most common means by which they receive payments?

From the FAQ:

> Q. What method of payment do you use?
>
> A. We will make your payments by Electronic Funds Transfer which is a bank-to-bank transfer. We do not currently offer any other payment methods – please ensure that you are able to receive payments in this manner. Valve is unable to provide additional documentation to help you receive your funds.

There's also this helpful FAQ for new Steamworks developers which might be helpful for you.

I'd also suggest just Googling around, most of the stuff hasn't changed since Greenlight, so if you manage to find information from people that feel more comfortable disclosing it, I'd say that it should still be valid.
> 3 votes

# Answer
As Typpi has mentioned before, there is a FAQ where you can get some answers but there is an important point that I read when Steam direct was launched (if they didn't change it):

You have to pay $100 to put your game on Steam but you do not necessarily lose that money. It is a fee that you can get back if your game makes $1000. As of 2/01/2018, here's their official statement regarding recouping the steam app fee:

> **Overview** Whether you are completing the Steam Direct signup process or are already an established Steamworks developer, you can now simply pay a $100 USD (or equivalent) fee for each new app you wish to distribute on Steam. Read below for details on how it works.
>
> ...
>
> **Recouping The App** Fee The Steam App Fee is not refundable, but will be recoupable in the payment made after your product has at least $1,000.00 Adjusted Gross Revenue for Steam Store and in-app purchases. Payment of revenue from sales and repayment of fee may be withheld if deposit payment is charged-back, refunded, or otherwise identified as fraudulent.

So if your game is worth $1, when you sell 1000 copies you will be able to recover your initial $100 spent publishing to their platform.

I found more info on that Steam Blog: Link To Blog
> 3 votes

# Answer
Also dont forget that if you sell 1$\*1000 you have to figure out what is "gross Revenue" as you will maybe have 15% refunds, 20% VAT and 20 - 30 % steam collected part so from 1000$ you goes to 450$ ... need then another year / turn.
> 0 votes

---
Tags: steam
---


# Question
Title: Lightweight NON-dynamic particles in Unity
I know Unity has an advanced system for managing complex dynamic particle systems with a few thousand elements (Shuriken).

Does Unity have a more lightweight way to create a very, very large (several million in scene) particle system that's basically a vast point cloud of camera-facing billboards that gets created, then just sits in the scene (recalculating normals as necessary in a non-blocking manner as the camera moves around, but otherwise doing nothing) until it gets destroyed and replaced in its entirety a minute later?

The specific application I have in mind is displaying weather radar. Weather radar consists of multiple 360-degree sweeps, each at different inclinations. The collection of sweeps taken in a single round is called a Volume Scan. What I'm trying to do is render the volume scan for a radar site in its entirety, in a way that allows someone to move the camera around and look at it from different vantage points, seeing the storm structure in 3D.

The important thing to remember is that the scene rendered by the camera needs to be able to change with an acceptable framerate as the user looks around and moves the camera, but the underlying point cloud being rendered by the particles changes at most once every 60 seconds. The only thing that could really be considered "dynamic" might be recalculating the normals for each point as the camera moves around.

Likewise, assuming normal-recalculation for a 4 million+ particle system wouldn't be instantaneous, I'd at least hope it could be done in a non-blocking manner (I'd rather get 60fps with most of the particles facing in the wrong direction at any instant, then have them gradually snap to face the camera once it stops moving, than have the world completely grind to a halt while Unity recalculates the normals).

I'm pretty sure that raw OpenGL and OpenGL ES can do this with acceptable performance, but I'm trying to stick to Unity for the sake of keeping my app somewhat portable (initially targeting "normal Android" for the sake of having something I can actually make money with immediately, but eventually extending it to support Android VR, Oculus, Magic Leap, HoloLens, etc... if only for the sake of having portfolio projects to show off).

So... does Unity have anything like this? At this moment, I don't necessarily need step-by-step directions... more like some suggestions about what to even SEARCH for, or where to look for documentation about it, since pretty much EVERYTHING particle-related I've found for Unity so far seems to be totally 100% Shuriken-focused.

# Answer
Rather than using particles, you probably want point sprites. Create a mesh of points using MeshTopology.Points, and to render the particles you could use a geometry shader to create quads or just use the GPU point primitive (which has a point size input in the vertex shader).

Example: https://forum.unity.com/threads/unity4-point-sprite-texture-coordinates.158891/

If you need alpha blending on the sprites, sorting will be a problem.
> 0 votes

---
Tags: unity, particles
---


title: Infinite plane with Unity Navmesh agent

text:
# Question
Title: Infinite plane with Unity Navmesh agent
guys!

I would like to create a map where the player can never reach the end while using the awesome navmesh agent from unity.

Is it achievable? I'm thinking of making a treadmill kind of logic with navmesh but since the environment have to be static, I don't think it's workable is it?

# Answer
From my understanding the Unity NavMesh has to be baked so it's not something you can do in real-time. My advice would be to go and build your own path finding solution using the A\* algorithm or something similar. Sebastian Lague has a fantastic tutorial on YouTube.
> 3 votes

# Answer
I know it's quite old one, but you should be able to achieve this with NavMesh Surface

It's official created by Unity, but it's not part of Unity though as of now - check that link for how to install it.

NavMesh Surface can be prefabed along with NavMesh itself and connected such e.g. planes are automatically connected together, so you should be able to instantiate such prefab with script as needed, while keeping NavMesh functionality and to add another benefit of this - it actually can be in 2D game as well (e.g. top-down shooter) since there is no angle restriction for baking.
> 2 votes

---
Tags: unity, navmesh
---


# Question
Title: Physics engine and squishing of stacked objects
I have a general question that seems to apply to most physics Engines (Box2D, Unity, Matter.js, …). I'm trying to make a tower of rectangular objects that are stacked on the \[static/mass=infinity\] ground, and the more blocks I have, the more they "squish".

I put together a test case in CodePen, which is reproduced here:

```
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;

//physics vars:
var phys = Matter;
var bod = Matter.Body;
var bodies = Matter.Bodies;
var engine;
var render;
var world;
var optionsForBodies = { // Florian
  restitution: 1,
};

var boxNumber = 0;

// --- TEMP ---
const keyState = {};
window.onkeydown = function (event) {
  keyState[event.code] = true;
};
window.onkeyup = function (event) {
  delete keyState[event.code];
};
// --- /TEMP ---

// Add bodies to matter
function loadMatter(){
  var floor = phys.Bodies.rectangle(100, 225, 200, 50, {isStatic: true});
  var blist = [floor];
  for (var i = 0; i < 13; i++) {
  // for (var i = 0; i < 2; i++) {
    var box = bodies.rectangle(100, 200 - i * 20, 56.8, 20, optionsForBodies);
    blist.push(box);
    boxNumber += 1;
  }
  phys.World.add(world, blist);
}

function drawMatter(name){
  var bodies = phys.Composite.allBodies(world);
  for(var i = 0; i < bodies.length; i++)
  {
    if(!bodies[i].render.visible)
      continue;
    var verts = bodies[i].vertices;
    if(verts.length <= 0)
      continue;
    context.fillStyle = "#aaa";
    context.strokeStyle = "#000";
    context.lineWidth = 2;

    var ofsx = 0, ofsy = 0;
    context.beginPath();
    context.moveTo(verts[0].x + ofsx, verts[0].y + ofsy);
    for(var j = 1; j < verts.length; j ++)
      context.lineTo(verts[j].x + ofsx, verts[j].y + ofsy);
    context.lineTo(verts[0].x + ofsx, verts[0].y + ofsy);
    context.fill();
    context.stroke();
  }
}

function updateMatter(ms){
  phys.Engine.update(engine, ms);
}

function clrCanvas(){
  context.fillStyle = "#fff";
  context.fillRect(0, 0, width, height);
}

var inter;

function init(){
  initMatter();
  clrCanvas();
  requestAnimationFrame(step);
}

function initMatter(){
  engine = Matter.Engine.create();

  world = engine.world;
  world.gravity.y = 3.0;
  render = Matter.Render.create({
    canvas: canvas,
    engine: engine,
    options: {
      width: 400,
      height: 300
    }
  });
  loadMatter();
}

var frameNo = 0;
function step() {
  var SCALER = keyState.KeyA ? 3 : 1;
  var SPEED = 16 * SCALER;
  if (frameNo++ % SCALER === 0) {
    updateMatter(SPEED);
    clrCanvas();
    drawMatter();
  }
  requestAnimationFrame(step);
}

init();
```

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.11.0/matter.min.js"></script>
<body>
<canvas id="canvas" width="400px" height="400px"></canvas>
</body>
```

To me what's happening is not obvious and I'd love an explanation in human words, since in real life if you stacked crates they would not squish inside each other, but it's a constant with EVERY physics engine, despite playing with restitution, slop, damping, density and many parameters.

Ideally I'd like those crates to be dense enough to absorb a big part of the shock (=not bounce much) of each other and never penetrate each other.

What concepts am I missing?

In the codepen above, try to select the canvas and then press the 'A' key, which reduces the framerate (increasing the dt from 16ms to 50ms) which increases the forces computed for the objects at each iteration and therefore penetrating even more each other.

Thanks!!

# Answer
> 2 votes
Sorry, I didn't know how to mark your comment as helpful. Turned out to be, I watched the GDC talk with great interest and along with my research, I could grasp why what I'm looking to do is just gonna happen with collisions done in pairs.

Basically, think about crates who are squished one in each other, each having the same weight and mass; the crate on top has as much the right to say to the crate below it that it should move down (to not collide with it) as the crate below it will move the crate above it to not collide anymore. This "dance" could continue almost forever, and it's the core reason of why I experienced the issue.

We can apparently not solve it unless we have an infinite number of iterations (mathematically). In practice, it is solved partially by raising the number of iterations of the solver significantly. Or by avoiding this design. For iterations, something around double the number of crates is giving a much better result, but you will never have anything perfect and you've gotta make a compromise.

I played with the friction and restitution too, but expect nothing miraculous. It was enough for my game, even if that crate design unfortunately drains on the CPU way more than one'd initially think.

# Answer
> 2 votes
I’m surprised that this question has such few views and votes. Stacking is a fundamental pathological use case of physics engines that implement a simple contact solver model. It showcases how the principle behind simulating the dynamics on an individual per-contact basis breaks down when long chains or complex interactions of contact are at play.

In the typical situation of a general purpose engine and a stack of boxes, I’d analogize the situation with a chain of nodes that are connected. In both situations the forces computed between them are integrated one at a time only at their contact boundaries.

E.g. as far as the solver is concerned, the top box isn’t interacting with any other box than the second-to-top box. Therefore, in the course of one timestep, only the penetration resolution impulse (or positional correction, as necessary) from the second-to-top box can affect the top box.

So let’s imagine 5 nodes connected with constraints

```
T=0: * - * - * - * - *

```

They must be 1 unit of space between them (because for example the blocks are one unit thick). Represented here by the distance of 3 monospace characters.

A force (such as gravity, but let’s assume for the sake of easy analysis this stack is static in a weightless environment and we experience a single impulse) is experienced on the top of the stack pushing it down.

```
T=1: * * - * - * - *

T=2: * - * * - * - *

T=3: *  * - *  * - *

T=4: * - * - *  *  *

```

...Etc. Interactions become more diffused.

The point here is that the way the “speed of sound” has to travel through the material shows how it is limited by your timestep and number of iterations. This is where the realism breaks down. Indeed if you double the number of blocks stacked together (and halve their height), you have something that is more or less twice as unstable in the simulation,

In the real world, there is no such thing as a timestep or iterations, and yielding to a squishing force should not depend in any significant amount on the number of discrete structures involved (we do not see that books with a higher count of pages are proportionately more squishy, for example. Nor that books are the squishiest of all things.)

We understand that the correct interaction is that no squishing of the stack happens (provided we are modeling an incompressible block material, of course):

```
T=1: * - * - * - * - *

```

In order for it to be possible to have this “correct” computation, the engine has to realize that all of the blocks are connected to each other based on their geometric contact state, and perform a global constraint resolution on that connectivity. In our simplified node representation, node 0 and node 4 are connected through a chain of 3-character spacing constraints, so upon node 0’s receipt of an impulse, the solver must somehow determine that since node 4 will not “give” in that direction, the normal force impulse shall be delivered immediately, canceling out the squish motion.

I think that this is all quite possible to resolve in theory, and the TOI solver for the computation of the time of impact by sweeping in the box2d engine is an example of an engine taking some steps forward (though that one does not do much in the way of directly addressing massive contact interactions such as large stacks: it simply allows for detecting and adding “in-between” iterations at the time of impact, so that bullet-like fast moving objects will not freely warp through objects without interacting with them).

So this has been my approach to explaining the situation around poor stacking performance in typical rigid body simulations and how to start thinking about improving the situation.

The trouble with putting it into practice... Well, simple solvers that only resolve local contact constraints are very beneficial as they give you straightforward implementations that have nice computational scaling. You resolve your contact constraints for all of the points of contact that your collision detector computed, and you get on with the next frame or timestep.

I have not done much exhaustive brainstorming around this, though I have pondered this on and off over the years.

Consider that if you want to actually compute the correct result of resolving forces imposed on stacks or jumbles or piles of objects, it stands to reason that the entire connectivity graph based on contact for that pile of objects must be resolved each frame. This is not in and of itself prohibitive, given that the collision detection would already be required anyway for the basic contact solver, so you just additionally compute the connectivity graph based on the contacting objects.

Then, this graph (one for each group of contacting objects) must be used each step of the simulation to implement and solve a global constraint system (one for each group of contacting objects) to resolve the interacting forces.

It’s clear that the computational complexity scales rather dramatically with the dimension (given that the cardinality of this graph will likely scale with the size of the pile squared or cubed depending on if you’re doing 2D or 3D physics) and further modulated by whatever solver you are using to solve the contact constraint model that you have to have to keep things behaving as they should. Even though the runtime of such models might be subquadratic, remember that the model is based on the contact connectivity, which would be subject to almost arbitrary change each timestep, meaning that the time complexity of setting up the model in order to run it is also very much implicated here. Likely quadratic or worse, with worse yet constants.

In almost all game-type simulations, it is difficult to make a case for the importance of having a high fidelity model of just how a jumble or pile or stack of objects (which would themselves exhibit idealized material properties, e.g. that objects are totally rigid to begin with, reducing the resultant realism anyway) reacts to arbitrary disruption. The result is always highly chaotic, and the computation involved to evaluate the most correct response is always going to be rather prohibitive: A massive constraint system must be modeled out of the connectivity graph for that particular physics state, and then every force impulse that is applied to any object on that group of objects is accumulated for input to that model and evaluated. The good news is that the model can be evaluated one time per timestep, but the overhead of having to initialize the model for every single timestep (as the scene evolves) is most likely to be the performance killer.

So in conclusion, although I referred to the pairwise contact solver model as "basic", it is usually the best fit for the problem. You're really opening up a can of worms trying to move beyond it. But I do believe that under special circumstances given a particular type of scene, a more sophisticated and flexible solver can make great strides on something like stack stability.

But you'd be about as well served pursuing heuristical solutions (such as putting simulated objects to sleep etc) or design changes to address the issue.

---
Tags: physics, collision-resolution, physics-engine, simulations
---


# Question
Title: How do i properly make a skybox in Unity?
I have some trouble creating a sky box from a panoramic texture. Everything appears to be working. However there are some artifacts in one place. How do i get rid of them?

# Answer
> 2 votes
My approach is to generate an Inverted Sphere and put an Equirectangular texture (2:1 ratio) on it, it will work by default.

here is an editor script that will generate an inverted sphere for you:

```
using UnityEngine;
using UnityEditor;

public class InvertedSphere : EditorWindow
{
    private string st = "1.0";

[MenuItem ("GameObject/Create Other/Inverted Sphere...")]
public static void ShowWindow ()
{
    EditorWindow.GetWindow (typeof(InvertedSphere));
}

public void OnGUI ()
{
    GUILayout.Label ("Enter sphere size:");
    st = GUILayout.TextField (st);

    float f;
    if (!float.TryParse (st, out f))
        f = 1.0f;
    if (GUILayout.Button ("Create Inverted Sphere")) {
        CreateInvertedSphere (f);
    }
}

private void CreateInvertedSphere (float size)
{
    GameObject go = GameObject.CreatePrimitive (PrimitiveType.Sphere);
    MeshFilter mf = go.GetComponent<MeshFilter> ();
    Mesh mesh = mf.sharedMesh;

    GameObject goNew = new GameObject ();
    goNew.name = "Inverted Sphere";
    MeshFilter mfNew = goNew.AddComponent<MeshFilter> ();
    mfNew.sharedMesh = new Mesh ();

    //Scale the vertices;
    Vector3[] vertices = mesh.vertices;
    for (int i = 0; i < vertices.Length; i++)
        vertices [i] = vertices [i] * size;
    mfNew.sharedMesh.vertices = vertices;

    // Reverse the triangles
    int[] triangles = mesh.triangles;
    for (int i = 0; i < triangles.Length; i += 3) {
        int t = triangles [i];
        triangles [i] = triangles [i + 2];
        triangles [i + 2] = t;
    }
    mfNew.sharedMesh.triangles = triangles;

    // Reverse the normals;
    Vector3[] normals = mesh.normals;
    for (int i = 0; i < normals.Length; i++)
        normals [i] = -normals [i];
    mfNew.sharedMesh.normals = normals;

    mfNew.sharedMesh.uv = mesh.uv;
    mfNew.sharedMesh.uv2 = mesh.uv2;
    mfNew.sharedMesh.RecalculateBounds ();

    // Add the same material that the original sphere used
    MeshRenderer mr = goNew.AddComponent<MeshRenderer> ();
    mr.sharedMaterial = go.GetComponent<Renderer>().sharedMaterial;

    DestroyImmediate (go);
}
}

```

---
Tags: unity, textures
---


# Question
Title: Is it NOT feasible to create a web-based game which provides cash prizes due to bots?
Say you want to build an online web-based game of (say) Hangman where the person who continues to win eventually wins a cash prize. The more players that enter the game the more the eventual winner wins.

However, it is clear these days, that any game which has cash prizes will attract the bot-writers. I would assume that even a game like Hangman would be a trivial matter for an experienced bot-writer to create a bot which would provide a significant edge over a human player.

Based on this fact; that any online game could provide a bot-writer with a advantage over human players, my question is: is it possible to create a online game which provides cash prizes which a bot-writer would have no significant advantage over human players? Or is it simply that bots are too powerful and pervasive now in gaming and a real-money-transaction game is not feasible?

# Answer
There are four kinds of games I could imagine where human players wouldn't get outpaced by bots.

1. Embrace the bots. Make a game about bot programming. Let the best bot-writer win. It's not cheating when it's the point of the game :) (Ok, this is kind of a cop-out)
2. Create a very complex strategy game with large numbers of units to control, a large number of interlocking mechanics and many, many decisions to make (like Civilization). The standard MiniMax algorithm which beats human players at games like chess can't be used here because the decision tree is just too wide. I have yet to see a 4X game where the AI can pose a challenge to a moderately experienced human player without having to resort to some form of cheating. Turn-based games might be better for this than real-time games, because in real-time games AI opponents can benefit from their superhuman speed and perception when it comes to micro-management.
3. Make a social deduction game like Town of Salem where players need to communicate with each other and win the game through psychology, diplomacy and deception. Bots will fail the Turing test and get ganged on by the human players. Most social deduction games I know have some design flaws which prevent them from being really e-sport compatible, like imbalanced roles or bad players having it too easy to screw up the game for good players. But I am curious how a social deduction game specifically designed for competitive play could work.
4. Make the game a popularity contest. Give the players a creative task and then have humans rate them based on aesthetics and originality. There are some pitfalls here, of course. When you design the voting system badly, it might be vulnerable to brigading, tactical voting or bot voting.
> 6 votes

# Answer
Your game has to have some form of income to make it work - it has to make money so you can give money away.

Assuming your goal is to make YOU some money...

Base your game concept around the idea that even if a bot is playing, it's still making you money. More money than the bots are being paid. Done right, you only care about bots upsetting other human players, because they aren't costing you anything (beyond maybe human players).
> 2 votes

# Answer
Come up with a game that is too hard to write a bot for. For the vast majority of games out there, the investment of writing a bot is vastly higher than the prize you could get for winning it. For most professional e-sports, bots simply aren't good enough to compete with capable humans. (We're getting there, though. Then, this question will become relevant again)

People will only resort to using bots if the game is a pointless grind and the price goes to the best grinder. You're not going to avoid bots on a game like that.
> 1 votes

# Answer
It's not easy, and its feasibility depends on your technical ability and funds. It also depends on the game itself. e.g. if it's a game of pure chance, writing a bot won't help at all. But if it's a game of speed, then obviously a bot will trump any human.

It's perfectly possible though, there are hundreds of online casinos and poker sites, all of these host online games which give cash prizes, and plenty more online non-cash games which implement successful bot prevention strategies.

They have sophisticated anti-cheat technology tuned to the game in question to prevent both automatic and 'manual' cheating (e.g. Poker needs collaboration detection as well as basic web application security measures etc. etc.)

You can also integrate some form of CAPTCHA into your game play; detect human-like mouse movements and non-linear timings etc.
> 1 votes

---
Tags: game-design, web, anti-cheat, bot, real-money-transactions
---


title: Adding text to gameobject

text:
# Question
Title: Adding text to gameobject
I'm trying to create a falling word game like z-type (code here). I have created 3 game objects and I want the words to be added as text to these game objects something like a health bar is added to enemies etc. This is the word spawner script that spawns the word on screen.

```
public GameObject wordPrefab;
public Transform wordCanvas;

public WordDisplay SpawnWord()
{
    Vector3 randomPosition = new Vector3(Random.Range(-2.0f, 2.0f), 7.0f, 0);
    GameObject wordObj = Instantiate(wordPrefab,randomPosition, Quaternion.identity, wordCanvas);
    WordDisplay wordDisplay = wordObj.GetComponent<WordDisplay>();
    return wordDisplay;
}

```

Right now the words are spawned at a random x position and y position of 7.0. Instead of this how can I assign the words to the gameobjects that I have created.

**Edit**

I have created a spawner that spawns 3 enemies at the top of the screen and they start falling down to the bottom. Here is the script attached to the enemy game objects:

```
public float fallSpeed = 1.0f;
public GameObject wordPrefab;
private Transform parent;

public WordDisplay SpawnWord()
{
    Vector3 randomPosition = new Vector3(Random.Range(-2.0f, 2.0f), 7.0f, 0);
    GameObject wordObj = Instantiate(wordPrefab, randomPosition, Quaternion.identity, parent);
    WordDisplay wordDisplay = wordObj.GetComponent<WordDisplay>();
    return wordDisplay;
}

// Update is called once per frame
void Update () {
    transform.Translate(0, -fallSpeed * Time.deltaTime, 0);
}

```

I have also removed the SpawnWord() method from the wordspawner script. However the words don't spawn along with the enemy gameobjects. There is one more script called the WordTimer. Not sure where to add this code. This is from the original code that's on github.

```
public WordManager wordManager;
public float delay = 1.5f;
private float nextWord = 0f;

void Update()
{
    if (Time.time >= nextWord)
    {
        wordManager.AddWord();
        nextWord = Time.time + delay;
        delay *= 0.95f;
    }
}

```

# Answer
> 1 votes
instead of `randomPosition` just use `wordCanvas.transform.position`

As you set the wordCanvas as the parent it will be parented to the wordCanvas and follow it around.

If wordCanvas isn't the object you're supposed to be following, substitute wordCanvas with that object.

---
Tags: unity
---


# Question
Title: How to get the position of individual characters in TextMeshPro (Unity)?
I am making a typing game. There are words falling down what the user have to type, before they can call the ***OnBecameInvisible()*** event.

When the user types a character I want to apply a force and a torque to it and make it fall down. But to do this I have to instantiate a TextMeshPro GameObject at the position where that letter was located inside that word. But how can I get that position?

> Just to make things clear:

# Answer
> 1 votes
It's late but for some peoples who dig a bit with google :

The best solution here is to create a GameObject and a Textmesh for all letters with one parent GameObject, then your register in a KeyManager all letter you spawn and everytime you press a key you look into this KeyManager to get the letter GameObject to SetParent(null) and shoot the letter away

You can spawn easily this hierarchy with a script where you give a string as a parameter

```
public class KeyManager : MonoBehaviour
{
    List<GameObject> ListOfSpawnWord = new List<GameObject>();

    public void EjectLetterIfExist(string a_letter) {
        foreach (GameObject currentGameObject in ListOfSpawnWord) {
            GameObject letterToKickAway =  currentGameObject.transform.Find(a_letter+"_GO").gameObject;//get the GameObject you want kick away
            if (letterToKickAway != null)
            {
                letterToKickAway.transform.SetParent(null);
                letterToKickAway.GetComponent<Rigidbody2D>().AddForce(new Vector2(-1, 0) * 100);
            }
        }
    }
    public void AddSpawnedWord(GameObject a_gameobject)
    {
        ListOfSpawnWord.Add(a_gameobject);
    }
}

```

---
Tags: unity, text
---


title: Quaternion angle calculation

text:
# Question
Title: Quaternion angle calculation
I'm working on a programming project, in this project I'm receiving an angle as a quaternion value, I partially understand how they work but I don't find any math to get the values I need.
What I would need is the angle between a fictional line/vector going to the the quaternion point from the origin (yes I know what you are thinking, but I couldn't think of a better explanation) and the "earth" a plane that is perpendicular to the gravitational vector, in this case one of your planes of reference.
Also I would need to get the rotation of the line/vector, this time the rotation should be according to the plane perpendicular to itself.
If possible all angles should be described as an angle between -180° and 180° (that's were my troubles are from.

In this picture γ complementary angle of the first questing and R is the secondary angle.
Angles

PS: This is the last formula I tried to use.

# Answer
> 1 votes
Calculate the "shadow" on i,j plane $$A\alpha= \sqrt{(Ax)^2+(Ay)^2}$$

Get the γ angle $$\gamma = tan({A\alpha \over Az})$$

Middle solution : $$\alpha'=tan({Ay \over Ax})$$ $$\beta'=tan({Ax \over Ay})$$

You maybe draw α and β wrong if not I cannot help you more :(

# Answer
> 0 votes
> You should **always** use atan2(y,x) instead of atan(y/x). It is a common mistake. – Somos

He wrote this on a math form were I asked this too, and that was my stupid mistake -\_-

My new version is:

```
float gx = 2 * (x*z - w*y);
float gy = 2 * (w*x + y*z);
float gz = w*w - x*x - y*y + z*z;
float yaw = atan2(2*x*y - 2*w*z, 2*w*w + 2*x*x - 1); // about Z axis
float pitch = atan2(gx, sqrt(gy*gy + gz*gz)); // about Y axis
float roll = atan2(gy, gz); // about X axis

/*Serial.print("  yaw ");
Serial.print(yaw * 180/M_PI,0);*/
Serial.print("  pitch ");
Serial.print(pitch * 180/M_PI,2);
Serial.print("  sideways ");
// Please don't pay  attention to the extra function I made for the project but it doesn't have to do with the problem
if(pitch > 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,((pitch * 180/M_PI)-51.57)))), 2);
else if(pitch == 0) Serial.println(roll * 180/M_PI, 2);
else if(pitch < 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,(((pitch) * (-180)/M_PI)-51.57)))), 2);

```

---
Tags: quaternion, angles
---


# Question
Title: Unwanted left-right rotation in run animation imported from Mixamo
A humanoid run animation I downloaded from Mixamo is working fine on their site and in Blender.

When I import it into Unity it shows a strange movement: the full body is rotating left & right in a strange way when animation is running.

Here are my import settings for the animation:

# Answer
I read about this before and I think you need to fix the rotation manually. Root Motion - how it works

> Bake into Pose: The orientation will stay on the body transform (or Pose). The Root Orientation will be constant and delta Orientation will be identity. This means that the Game Object will not be rotated at all by that AnimationClip.
>
> Only AnimationClips that have similar start and stop Root Orientation should use this option. You will have a Green Light in the UI telling you that an AnimationClip is a good candidate. A suitable candidate would be a straight walk or a run.
>
> Based Upon: This lets you set the orientation of the clip. Using Body Orientation, the clip will be oriented to follow the forward vector of body. This default setting works well for most Motion Capture (Mocap) data like walks, runs, and jumps, but it will fail with motion like strafing where the motion is perpendicular to the body’s forward vector. In those cases you can manually adjust the orientation using the Offset setting. Finally you have Original that will automatically add the authored offset found in the imported clip. It is usually used with Keyframed data to respect orientation that was set by the artist.
>
> Offset: used to enter the offset when that option is chosen for Based Upon.

So, I think you have to deal with "Root Transform Rotation" only. Bake into Pose,Checked. Change Based Upon to "Body Orientation". for Offset, put a value that makes your doll facing the small blue arrow direction. Plus, try to Unchecked "Apply Root Motion" option in your Animator.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: the countdown timer inside while loop not working
i am instantiating prefab cars ... the clones had a random countdown timer with each one off them and its working very well but the its not decreasing its not counting down the timer is inside the spawn method the spawn method is inside the WHILE loop and the while loop is inside the UpDate() ... i tried to move the countdown to Update() but didnn't worked ... any ideas ...Thank You!

```
void Update()
{
    p -= Time.deltaTime;

        while (carNumber < cars && p <= 0 )
        {
            SpawnCars();
            print(carNumber);
            p = 5;
    }

}

```

and this is the spawn method:

```
 public void SpawnCars()
{
    if (spawnAllowed)
    {
        // choose a random strat point 1/6
        randomSpawnPoint = Random.Range(0, spawnPoints.Length);
        // choose a random car 1/6
        randomSpawnCars = Random.Range(0, Cars.Length);
        // clone randomly a car(1/6) from a random pre_set-points(1/6)
        GameObject obj = Instantiate(Cars[randomSpawnCars], spawnPoints[randomSpawnPoint].position, Quaternion.Euler(-90, 180, 0)) as GameObject;
        // carNumber will count how many cloned car
        carNumber++;
        // destroy the  cloned car after N sec
       // Destroy(obj, 8);
        // every cloned car will take a tag with it
        obj.gameObject.tag = "select" + k;
        k++;
        rcf = obj.GetComponent<RayCastForward>();
        //textCDT
        time = Random.Range(4f, time);
        TextMesh txt = FindObjectOfType<TextMesh>();

//the Timer:
        time -= Time.deltaTime;
        coolDown = time.ToString("0");
        txt.text = ""+coolDown;

    }
}

```

edit: i forgot to tell that the timer is inside SpawnCars().

# Answer
> 1 votes
Finally! After 3 days, I found the solution:

1. I created a new script
2. attached it to the 3d Text
3. Add code to change the text:

```
time-= Time.deltatime; // CountingDown
GetComponent<TextMesh>().text = time.ToString("0"); // Show the countdown in the 3d text

```

# Answer
> 0 votes
You could use a Coroutine. You can run `SpawnCars();` there and use `yield return new WaitForSeconds(5f);` to make it run every 5 seconds. You have to put `StartCoroutine("YourCoroutine");` in `Start();` and when you don't need anymore cars you will have to call `StopCoroutine("YourCoroutine");`.

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


# Question
Title: UI/Menu that works with and without VR (Unity, WMR)
I'm working on an app that I want to be useable without and with VR (with a Windows Mixed Reality HMD like the Samsung Odyssey).

For non-VR I'm simply using a canvas in "Screen Space - Camera" and a second camera, which is a child of the Main Camera and can only see the UI (the Main Camera can see everything but the UI). This way the menus are displayed as transparent overlays that are always visible to the player (with the game scene in the background).

For VR you have to use World Space. This makes sense because I want to be able to look around without having the menu move too.

How do you now make an e.g. pause menu work in VR AND non-VR - depending on if the player plugs in his headset before starting the app or not?

* Do you change the Screen Space to World Space in code at runtime if there's an HMD?
* Do I have to move the whole canvas at runtime to where the player is? You'd want the menu to be in front of the player, no matter where he is but it also has to be in front of the other objects in the scene, so you can interact with it.

I'm using Unity 2017.3 with OpenVR/SteamVR.

# Answer
> 1 votes
This is a question of platform management. Using one Unity project, you can create an application that runs in Desktop (Windows/Mac), VR (Vive/WMR), MR (HoloLens/Magic Leap) and Mobile devices (Android/iOS).

A simple solution would be to do as you say, change a UI canvas from screen space to world space.

However, there are other considerations that you may run into as your UIs get more advanced, that simply changing the space of the canvas can't account for. You may wish to have a UI follow the user in VR/MR, or display different options to mobile users than VR users. All of this gets very complex to manage in a single canvas.

I'd suggest a platform manager. It will know the platform it's running on, and enable/disable scripts and objects accordingly.

You'd arrange things so that you have a parent object that holds a canvas. That parent object will get enabled or disabled by whatever turns on or off your UI. Under the parent object, you have one or more canvas objects for your platforms. For UIs that are common among all platforms, you'd just have one canvas. For UIs that are more complex, you'd have multiple canvases that are turned on or off by your platform manager.

As an example, your menu UI would be turned on at the parent level. In this case, when running in VR, the only canvas under that parent is the VR canvas. This VR canvas is in world space and also has scripts that lerp its position to be in front of the user, 2 meters away. The desktop canvas (that's disabled in this case) would just have a screen space canvas, without the need for movement scripts. In this case, the content of the two UIs might be very similar, but you may have options available only to desktop users (like a display options menu where they can change the resolution).

This will likely result in some duplication of UI elements. Typically this is pretty easy to handle. If you're willing to bump up your Unity version, you can take advantage of the prefab improvements to use nested prefabs, so any duplicated elements are automatically updated across multiple canvases.

Additionally, this platform manager can also handle other things you need to enable/disable when switching between platforms. Like scripts that do spatial mapping on a MR device, or different camera objects for each platform you support.

---
Tags: unity, gui, virtual-reality, menu
---


# Question
Title: Is Frustum Culling and Occlusion Culling used together, or separately?
I am taking a 3D game programming course and my professor provided the class with already-implemented graphics code with **OpenGL**. The graphics uses **frustum culling** to remove primitives outside the view of the camera. I did some stress testing by spawning 1000s of boxes and when all boxes are in the view of camera, the FPS drops significantly (from 60FPS to 10FPS).

I have several questions about graphics clipping:

* Is **Frustum Culling** (FC) always implemented in every graphics engine?
* I've read about **Occlusion Culling** (OC), where objects occluded behind other objects aren't rendered. Does this replace **FC** or are they used together?
* Is **OC** more difficult to implement and therefore **FC** is the default clipping technique? I'm assuming implementing **OC** would increase the performance of my "game" since not all 1000s boxes would be rendered.

Any information is appreciated. Thanks!

# Answer
> 3 votes
In short yes. Both can be used. FC deals only what can be removed outside the camera view. What's inside the view or to be occluded is a more difficult proposition. There are few techniques for occlusion and i don't go into too much detail but you will find a couple of simple methods may improve your performance.

Dynamic occlusion, that is within each frame is challenging performance wise. Unless the objects you are testing are geometrically or complex shader wise you won't see as much of a benefit using some of the more advanced shader techniques. What you can do though to improve performance through occlusion is to get the hardware to work for you.

What i mean is to order your objects in your visible set from front to back. What this gives you is the ability to remove over draw by leveraging the z buffer. The z buffer itself in modern hardware is very fast. This effectively eliminates unnecessary draw actions to your back buffer. And in some cases it's faster as occlusion has edge cases where you end drawing the whole object even if only 1 pixel is exposed.

For static scenes, where criticality of frame time is not an issue, you can get into possible viewable sets (PVS) and this can test whether parts of your static scene can be seen from other parts. This where you can leverage bsp or quad yes to break your world up then test parts against other parts.

It's just a start. There are a number of books on the market talking about occlusion and how to achieve it. Gl

Edit: just to add. No, specifically implemented occlusion may not be in every graphics engine but some form most likely used and in some of the more defunct gpus designs such as tile renderer based would have a form of occlussion built in. To also dd. Using FC before OC makes the process of occlusion faster by only testing to the PVS possible viewable set.

Link to powervr which has an engineer talking about powervr vs radeon and nvidia https://www.imgtec.com/blog/a-look-at-the-powervr-graphics-architecture-tile-based-rendering/

---
Tags: opengl, graphics-programming, frustum-culling
---


# Question
Title: How to apply outer glow to a UI game object? Shader? Particle?
What's the best or easiest approach to apply an outer glow effect to a UI game object -- let's say, a popup dialog, so it's a rectangular shape -- in Unity 2018.3?

Is this something that should be done with a shader, or is it a particle effect?

Ideally I should be able to specify and perhaps even dynamically adjust the color and size of the glow.

Edit: image below shows a blue rectangle, which has this subtle, grey glow around it. I'm hoping to generate this glow effect somehow in Unity.

# Answer
> 1 votes
You can create a .png that has alpha with a gradient, that will create the shadow. You can then use the 9-slice to be able to seamlessly scale it to any size you want and keep the same resolution. You can then set it as a parent to the object so it will be rendered under it.

---
Tags: unity
---


title: DX12 Passing an Instance Buffer

text:
# Question
Title: DX12 Passing an Instance Buffer
I'm trying to take the DX12 Cube Demo that comes with VS2017 Community and draw three cubes instead of one. Unfortunately, the VertexShader doesn't seem to be getting my instance data.

In my InputLayout of CreateDeviceDependentResources, I'm trying to put my InstanceBuffer in Slot 1 per https://www.braynzarsoft.net/viewtutorial/q16390-33-instancing-with-indexed-primitives
(Yes, I know the Braynzarsoft Example is D3D11) :

```
    ...
    static const D3D12_INPUT_ELEMENT_DESC inputLayout[] =
    {
        // Vertex Buffer Data
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
        /* { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, Old Microsoft stuff */
        { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
        // Instance Buffer Data
        { "INSTANCE_STUFF", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
    };
    ...

```

Then later in CreateDeviceDependentResources, I try to upload my InstanceBuffer data between the areas where the sample uploads the VertexBuffer and IndexBuffer:

```
    ...
    // Instance positions
    VertexPosition instancePositions[] =
    {
        XMFLOAT3(3.0f, 0.0f, 0.0f),
        XMFLOAT3(3.0f, 0.0f, 0.0f),
        XMFLOAT3(-3.0f, 0.0f, 0.0f)
    };

    const UINT instanceBufferSize = sizeof(instancePositions);

    // Create the instance buffer resource in the GPU's default heap and copy instance data into it using the upload heap.
    // The upload resource must not be released until after the GPU has finished using it.
    Microsoft::WRL::ComPtr<ID3D12Resource> instanceBufferUpload;

    CD3DX12_RESOURCE_DESC instanceBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(instanceBufferSize);
    DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(
        &defaultHeapProperties,
        D3D12_HEAP_FLAG_NONE,
        &instanceBufferDesc,
        D3D12_RESOURCE_STATE_COPY_DEST,
        nullptr,
        IID_PPV_ARGS(&m_instanceBuffer)));

    DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(
        &uploadHeapProperties,
        D3D12_HEAP_FLAG_NONE,
        &instanceBufferDesc,
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(&instanceBufferUpload)));

    NAME_D3D12_OBJECT(m_instanceBuffer);

    // Upload the instance buffer to the GPU.
    {
        D3D12_SUBRESOURCE_DATA instanceData = {};
        instanceData.pData = reinterpret_cast<BYTE*>(instancePositions);
        instanceData.RowPitch = instanceBufferSize;
        instanceData.SlicePitch = instanceData.RowPitch;

        UpdateSubresources(m_commandList.Get(), m_instanceBuffer.Get(), instanceBufferUpload.Get(), 0, 0, 1, &instanceData);

        CD3DX12_RESOURCE_BARRIER instanceBufferResourceBarrier =
            CD3DX12_RESOURCE_BARRIER::Transition(m_instanceBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
        m_commandList->ResourceBarrier(1, &instanceBufferResourceBarrier);
    }
    ...

```

While uploading my InstanceBuffer above, I'm trying to mimic the same pattern that Microsoft used when they uploaded the VertexBuffer. The *main* difference I can see is that for my InstanceBuffer, I'm using a VertexPostion that I defined in ShaderStructures.h *instead* of the VertexPostionColor that Microsoft used for the VertexBuffer. The VertexPosition is the same as the VertexPositionColor except that the "DirectX::XMFLOAT3 color;" definition was removed from the end.

My *mangling* of the SampleVertexShader.hlsl file then looks like this:

```
// A constant buffer that stores the three basic column-major matrices for composing geometry.
cbuffer ModelViewProjectionConstantBuffer : register(b0)
{
    matrix model;
    matrix view;
    matrix projection;
};

// Per-vertex data used as input to the vertex shader.
struct VertexShaderInput
{
    float3 pos : POSITION;
    float3 color : COLOR0;
    float3 instancePos : INSTANCE_STUFF;
};

// Per-pixel color data passed through the pixel shader.
struct PixelShaderInput
{
    float4 pos : SV_POSITION;
    float3 color : COLOR0;
};

// Simple shader to do vertex processing on the GPU.
PixelShaderInput main(VertexShaderInput input)
{
    PixelShaderInput output;
    float4 pos = float4(input.pos, 1.0f);
    float4 instPos = float4(input.instancePos, 1.0f);

    pos.x += instPos.x;
    pos.y += instPos.y;
    pos.z += instPos.z;

    // Transform the vertex position into projected space.
    pos = mul(pos, model);
    pos = mul(pos, view);
    pos = mul(pos, projection);
    output.pos = pos;

    // Pass the color through without modification.
    output.color = input.color;

    return output;
}

```

Unfortunately, when the GPU gets to the main routine of the VertexShader, instPos.x, instPos.y and instPos.z all *seem* to be zero.

Will you all please kindly show me what I am doing wrong?

EDIT: I finally found the Graphics Debugger... and it its doesn't say anything about my m\_instanceBuffer. I don't know what I'm doing but I would have expected m\_instanceBuffer to show up as a Vertex Buffer in Slot 1 (See Picture):

# Answer
> 1 votes
I eventually got this working. As I said, my *biggest* mistake was apparently the fact that I wasn't handling the m\_vertexBufferView properly per Tubby94's Reddit post that I mentioned in the comments.

The primary missing code to handle that appears at the end of Sample3DSceneRenderer.cpp:CreateDeviceDependentResources. So my CreateDeviceDependentResources function should have looked more like this
(notice the m\_instanceBufferView code near the end):

```
...
static const D3D12_INPUT_ELEMENT_DESC inputLayout[] =
{
    // Vertex Buffer Data
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
    /* { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, Old Microsoft stuff */
    { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
    // Instance Buffer Data
    { "INSTANCE_STUFF", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
};
...
// Instance positions
VertexPosition instancePositions[] =
{
    XMFLOAT3(3.0f, 0.0f, 0.0f),
    XMFLOAT3(3.0f, 0.0f, 0.0f),
    XMFLOAT3(-3.0f, 0.0f, 0.0f)
};

const UINT instanceBufferSize = sizeof(instancePositions);

// Create the instance buffer resource in the GPU's default heap and copy instance data into it using the upload heap.
// The upload resource must not be released until after the GPU has finished using it.
Microsoft::WRL::ComPtr<ID3D12Resource> instanceBufferUpload;

CD3DX12_RESOURCE_DESC instanceBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(instanceBufferSize);
DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(
    &defaultHeapProperties,
    D3D12_HEAP_FLAG_NONE,
    &instanceBufferDesc,
    D3D12_RESOURCE_STATE_COPY_DEST,
    nullptr,
    IID_PPV_ARGS(&m_instanceBuffer)));

DX::ThrowIfFailed(d3dDevice->CreateCommittedResource(
    &uploadHeapProperties,
    D3D12_HEAP_FLAG_NONE,
    &instanceBufferDesc,
    D3D12_RESOURCE_STATE_GENERIC_READ,
    nullptr,
    IID_PPV_ARGS(&instanceBufferUpload)));

NAME_D3D12_OBJECT(m_instanceBuffer);

// Upload the instance buffer to the GPU.
{
    D3D12_SUBRESOURCE_DATA instanceData = {};
    instanceData.pData = reinterpret_cast<BYTE*>(instancePositions);
    instanceData.RowPitch = instanceBufferSize;
    instanceData.SlicePitch = instanceData.RowPitch;

    UpdateSubresources(m_commandList.Get(), m_instanceBuffer.Get(), instanceBufferUpload.Get(), 0, 0, 1, &instanceData);

    CD3DX12_RESOURCE_BARRIER instanceBufferResourceBarrier =
        CD3DX12_RESOURCE_BARRIER::Transition(m_instanceBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
    m_commandList->ResourceBarrier(1, &instanceBufferResourceBarrier);
}

...
// Create vertex/index buffer views.
m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress();
m_vertexBufferView.StrideInBytes = sizeof(VertexPositionColor);
m_vertexBufferView.SizeInBytes = sizeof(cubeVertices);

m_instanceBufferView.BufferLocation = m_instanceBuffer->GetGPUVirtualAddress();
m_instanceBufferView.StrideInBytes = sizeof(VertexPosition);
m_instanceBufferView.SizeInBytes = sizeof(someInstanceData);

m_indexBufferView.BufferLocation = m_indexBuffer->GetGPUVirtualAddress();
m_indexBufferView.SizeInBytes = sizeof(cubeIndices);
m_indexBufferView.Format = DXGI_FORMAT_R16_UINT;
...

```

Then, in Sample3DSceneRenderer.cpp:Render I should have called IASetVertexBuffers on m\_instanceBufferView as Tubby94 said:

```
...
PIXBeginEvent(m_commandList.Get(), 0, L"Draw the cube");
{
    ...
    m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
    m_commandList->IASetVertexBuffers(0, 1, &m_vertexBufferView);
    m_commandList->IASetVertexBuffers(1, 1, &m_instanceBufferView);
    m_commandList->IASetIndexBuffer(&m_indexBufferView);
    m_commandList->DrawIndexedInstanced(36, 3, 0, 0, 0);
    ...
}
...

```

The change to the ShaderStructures.h file is fairly intuitive but would look something like this:

```
namespace NameSpaceOfTheApp
{
    // Used to send per-instance data to the vertex shader
    struct VertexPosition
    {
        DirectX::XMFLOAT3 pos;
    };

    // Used to send per-vertex data to the vertex shader.
    struct VertexPositionColor
    {
        DirectX::XMFLOAT3 pos;
        DirectX::XMFLOAT3 color;
    };

    // Constant buffer used to send MVP matrices to the vertex shader.
    struct ModelViewProjectionConstantBuffer
    {
        DirectX::XMFLOAT4X4 model;
        DirectX::XMFLOAT4X4 view;
        DirectX::XMFLOAT4X4 projection;
    };
}

```

I don't have the exact code for this specific question anymore, but I have a walkthrough for a very similar problem posted here:

https://www.utilars.com/Blog/shawn-eary/2018/9/19/dx12Instancing

So the basic answer to the question follows from the comment above about me failing to perform the mechanism as Tubby94 suggested. Basically, I wasn't setting m\_vertexBufferView up correctly. One thing in particular I failed to so was call IASetVertexBuffers on it in the Render function of Sample3DSceneRenderer.cpp

---
Tags: instancing, directx12
---


# Question
Title: Loading a list of items from JSON, all entries are null
(I posted a very similar question here recently and the response I received was helpful. But I have been advised to start a new question, and here it is.)

I am developing a Unity game which includes a multiple-choice quiz. I've placed what I believe is a properly-formatted .json file (the quiz question, four answer choices, the correct answer, and an explanation for the answer) (which I checked with a .json formatter) in the StreamingAssets folder in the Unity project. I've created a custom class for the question, the four answer choices, the correct answer and the explanation of the answer. I am trying to load the entire contents of the .json file into an array, "questions," then copy that array into another array, "questionsCopy." To avoid repeating questions, as a question is used during the gameplay, I will remove it (and its corresponding answer choices, correct answer and explanation) from the questionsCopy array. (I have not yet developed the GUI to show the question, answer choices and eventually the correct answer and its explanation.)

Here are the updated relevant sections of what I've coded so far:

1) The REVISED custom class:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Linq; // LINQ (Language Integrated Query). The most common uses for LINQ statements tend to be sorting, searching, and filtering (though there’s plenty more you can do with it).
using System.IO;

// ******************************************************************
// See: https://gamedev.stackexchange.com/questions/166759/trying-to-load-json-questions-and-answers-into-a-multiple-choice-quiz-game-in-u
[System.Serializable]
public class QuestionCollection
{
    public QuestionChoicesAnswerHintExplanation[] questions;
}
// ******************************************************************

[System.Serializable]
public class QuestionChoicesAnswerHintExplanation : MonoBehaviour {

    public string[] question; // An array of strings (rather than just a string) so that line spacing, which doesn't play well with .json, could be preserved
    public string[] answerChoices;
    public int correctAnswerIndex;
    public string hint;
    public string explanation;

}

```

2) From the REVISED GameController:

```
    public QuestionCollection questionCollection; // See: https://gamedev.stackexchange.com/questions/166759/trying-to-load-json-questions-and-answers-into-a-multiple-choice-quiz-game-in-u

    public QuestionChoicesAnswerHintExplanation[] questions; // This is the fixed size array of the questions, answer choices, answers, hints, and explanations.
    private static List<QuestionChoicesAnswerHintExplanation> questionsCopy; // This is the resizeable list (originally a copy of the array). The size of this list will diminish as we remove items after presenting each question.
    private QuestionChoicesAnswerHintExplanation currentQuestion; // The current question drawn at random.
    private int randomIndex; // the index used to pick the random question.

    string path; // The path to the .json file storing the questions, answer choices, correct answer index, hints, explanations.
    string jsonString; // The contents of the .json file.

```

In the REVISED Start() in the GameController:

```
    path = Application.streamingAssetsPath + "/questionsAndAnswers.json";
    jsonString = File.ReadAllText(path);

    questionCollection = JsonUtility.FromJson<QuestionCollection>(jsonString); // questionCollection contains an array of question-answer choices-answer-hint-explanation objects
    questions = questionCollection.questions;

    //questions = JsonUtility.FromJson<QuestionChoicesAnswerExplanation[]>(jsonString);

    Debug.LogWarning("questionCollection:");
    Debug.LogWarning(questionCollection);

    Debug.LogWarning("Questions:");
    Debug.LogWarning(questions);

    if (questionsCopy == null || questionsCopy.Count == 0) // A list with zero elements isn't always null.
    {
        // questionsCopy = questions.ToList<QuestionChoicesAnswerExplanation>(); // <---- That was incorrect.
questionsCopy = questions.ToList<QuestionChoicesAnswerHintExplanation>();

        Debug.LogWarning("questionsCopy:");
        Debug.LogWarning(questionsCopy);
        Debug.LogWarning("questionsCopy.Count:");
        Debug.LogWarning(questionsCopy.Count);
        Debug.LogWarning("questionsCopy[0]:");
        Debug.LogWarning(questionsCopy[0]);
        Debug.LogWarning("questionsCopy[1]:");
        Debug.LogWarning(questionsCopy[1]);
        Debug.LogWarning("questionsCopy[2]:");
        Debug.LogWarning(questionsCopy[2]);

    }

    PickRandomQuestion();

```

Further down the GameController, here is the REVISED PickRandomQuestion():

```
    public void PickRandomQuestion()
{
    randomIndex = Random.Range(0, questionsCopy.Count);
    currentQuestion = questionsCopy[randomIndex];
    questionsCopy.RemoveAt(randomIndex);
}

```

3) Here are the contents of the .json file in the StreamingAssets folder:

```
    {
    "questions":

    [

{
     "question": ["Trinculo admits 'I have been in such a pickle...' in this comedy:"],
     "answerChoices": ["'The Tempest'", "'Henry 4, Part 1'", "'Henry 5'", "'The Merry Wives of Windsor'"],
     "correctAnswerIndex": 0,
     "hint": "Hint: Trinculo is stranded on an island.",
     "explanation": "'Henry 4, Part 1,' and 'Henry 5, are both histories. To be in 'a pickle' usually means to be in a quandary. A broader view of this passage reveals Trinculo to be drunk: \n\nAlonso: \nAnd Trinculo is reeling ripe: where should they \nFind this grand liquor that hath gilded 'em? \nHow camest thou in this pickle? \n\nTrinculo: \nI have been in such a pickle since I \nsaw you last that, I fear me, will never out of \nmy bones: I shall not fear fly-blowing.' \n\n'The Tempest' 5.1."
     },
     {
     "question": ["In 'Hamlet,' this character remarks: 'Neither a borrower nor a lender be; \nFor loan oft loses both itself and friend, \nAnd borrowing dulls the edge of husbandry. \nThis above all: to thine own self be true,\nAnd it must follow, as the night the day,\nThou canst not then be false to any man:'"],
     "answerChoices": ["Fortinbras", "Gertrude", "Polonius", "The Ghost of Hamlet's Father"],
     "correctAnswerIndex": 2,
     "hint": "Hint: This character is very talkative.",
     "explanation": "The verbose Polonius is speaking to his son Laertes. 'Hamlet' 1.3."
     },
     {
     "question": ["Roger Daltrey, well into his career with The Who, played the roles for both Dromios, the twin servants, in a 1983 BBC production of:"],
     "answerChoices": ["'King John'", "'King Lear'", "'Coriolanus'", "'The Comedy of Errors'"],
     "correctAnswerIndex": 3,
     "hint": "Hint: This play is a comedy.",
     "explanation": "'The Comedy of Errors.'"
     }

     ]
    }

```

**This is not working, however.** In the console, **I am getting correct values** for questionsCopy.Count and for randomIndex. **But I am getting null values** for questionsCopy\[0\], questionsCopy, and questionsCopy\[2\]. I would appreciate any helpful advice. Thanks.

# Answer
> 1 votes
Here is you object declaration:

```
public class QuestionCollection
{
    public QuestionChoicesAnswerHintExplanation[] questions;
}

```

And here is what you do:

```
  questionCollection = JsonUtility.FromJson<QuestionCollection>(jsonString);
  questions = questionCollection.questions;
  questionsCopy = questions.ToList<QuestionChoicesAnswerExplanation>();

```

I bet you've checked this code many times, so you don't catch the problem. Let me show it as a list:

* `QuestionChoicesAnswerHintExplanation` is the type of the collection items.
* `QuestionChoicesAnswerExplanation` is the type you ask `Linq` to cast the items to.

Unless `QuestionChoicesAnswerExplanation` is a base class of `QuestionChoicesAnswerHintExplanation`, you'll be getting nulls.

---
Tags: unity, serialization, json
---


# Question
Title: error X4016: SV_InstanceID semantic cannot be used with 10Level9 targets
I'm using a variant of the D3D12 UWP template that comes with VS2017 Community Edition and I have two related questions:

When I add ***this italicized and bolded code*** to the vertex shader signature, I get an X4016 error:

PixelShaderInput main(VertexShaderInput input, ***uint instanceID : SV\_InstanceID***)

The full text of the error is:
error X4016: SV\_InstanceID semantic cannot be used with 10Level9 targets

I don't understand what this means because when the template calls D3D12CreateDevice, it sets D3D\_FEATURE\_LEVEL\_11\_0.

Per this post, I'm *thinking* SV\_InstanceID is supported in DX11 and above: https://stackoverflow.com/questions/21241207/dx11-c-shader-cant-receive-instance-buffer-content

If I'm using a D3D12 template that is setting D3D\_FEATURE\_LEVEL\_11\_0 in the D3D12CreateDeveice call, why does the template think I have 10Level9 target?

Where can I go to change the template so that it uses a target that is compatible with the SV\_InstanceID semantic in the vertex shader?

NOTE: I'm trying to loosely follow the example on Page 561 of Frank Luna's "3D Game Programming with DirectX 12" Text where he passes instanceID into the vertex shader.

# Answer
> 3 votes
**TL;DR:** Edit your shader compilation to use Shader Model 5.1 or later.

> With the DirectX 12 API, there is no supported device to date that supports anything less than Direct3D Feature Level 11.0. Therefore, there is no point in using any of the down-level profiles lower than 5.1. See Microsoft Docs

The default in most UWP templates if you don't set an explicit shader model is `4_0_level_9_3` which is a 10level9 feature level.

There are two solutions here:

1. Right-click on each `.hlsl` file in your project, make sure you are set to All Configurations and All Platforms, then under HLSL Compiler -\> General -\> Shader Model set it to "Shader Model 5.1 /5\_1"
2. A better solution is to open the `.vcxproj` in notepad and add the following lines:

* Search for `Label="UserMacros"`
    * In each of the `ItemDefinitionGroup` blocks that follow for each configuration/platform combination, add a section just after the `</CLCompile>`:

```
<FXCompile>
     <ShaderModel>5.1</ShaderModel>
</FXCompile>

```

This will look something like:

```
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup>

    <PackageCertificateKeyFile>App1_TemporaryKey.pfx</PackageCertificateKeyFile>

  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\arm; $(VCInstallDir)\lib\arm</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\arm; $(VCInstallDir)\lib\arm</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\arm64; $(VCInstallDir)\lib\arm64</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\arm64; $(VCInstallDir)\lib\arm64</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store; $(VCInstallDir)\lib</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store; $(VCInstallDir)\lib</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\amd64; $(VCInstallDir)\lib\amd64</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <Link>
      <AdditionalDependencies>d3d12.lib;dxgi.lib;dxguid.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories); $(VCInstallDir)\lib\store\amd64; $(VCInstallDir)\lib\amd64</AdditionalLibraryDirectories>
    </Link>
    <ClCompile>
      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
      <PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <FXCompile>
      <ShaderModel>5.1</ShaderModel>
    </FXCompile>
  </ItemDefinitionGroup>

```

This will make all your shader compilation default to 5.1 unless you set something else.

> I use the second solution in my various Direct3D Game VS templates on GitHub.

---
Tags: directx, directx11, instancing, vertex-shader, directx12
---


# Question
Title: is there any method to simply ignore some files in unity build?
as im trying to build my new app on unity android specially when i want to use gradle, there is always some conflict with manifest or libraries and .....

for debug and problem exploration i need to ignore some folders to check for those bugs instead of need to move them somewhere else.

i just thought about git branching but it can cause lots of branches and maybe not efficient

# Answer
> 3 votes
You can rename the folders to one of the Unity's 'Special Folder Names' and they will be ignored: If you're on Windows, setting the folders to 'Hidden' would probably be the easiest as it likely won't be picked up as a 'change' by version control.

> During the import process, Unity completely ignores the following files and folders in the Assets folder (or a sub-folder within it):
>
> * Hidden folders.
> * Files and folders which start with ‘.’.
> * Files and folders which end with ‘~’.
> * Files and folders named cvs.
> * Files with the extension .tmp.

https://docs.unity3d.com/Manual/SpecialFolders.html

---
Tags: unity, debugging, build-process
---


title: Camera to the right from the character

text:
# Question
Title: Camera to the right from the character
I'm trying to create a camera like in **Fortnite** or **Gears of War**. It's focus must be to the right side from the character:

But when I rotate the camera, the character slightly shivers. **Lerping** and multiplying by `Time.deltatTime` doesn't help.

This is my code:

```
    using UnityEngine;

    [RequireComponent(typeof(Camera))]

    public class ThirdPersonCamera : MonoBehaviour
    {
        [Header("Sensitivity")]
        [SerializeField] private float xSensitivity;
        [SerializeField] private float ySensitivity;

    [Header("Limit angles")]
    [SerializeField] private float upLimit;
    [SerializeField] private float downLimit;

    [Header("Positioning")]
    [SerializeField] private Vector3 offset;
    [SerializeField] private float maxDistanceFromPlayer;
    [SerializeField] private Transform player;

    private float rotationAboutX;
    private float rotationAboutY;

    // Start is called before the first frame update
    void Start()
    {
        rotationAboutX = transform.localEulerAngles.x;
        rotationAboutY = transform.localEulerAngles.y;
    }

    void Update()
    {
        rotationAboutX -= Input.GetAxis("Mouse Y") * ySensitivity;
        rotationAboutY += Input.GetAxis("Mouse X") * xSensitivity;

        rotationAboutX = Mathf.Clamp(rotationAboutX, downLimit, upLimit);
    }

    // Adjust camera position.
    void LateUpdate()
    {
        Vector3 direction = new Vector3(0.0f, 0.0f, -maxDistanceFromPlayer);
        Quaternion rotation = Quaternion.Euler(rotationAboutX, rotationAboutY, 0);
        // Point to look at in the runitme.
        Vector3 focus = player.position + transform.TransformDirection(offset);

        // Rotate vector according to mouse inputs.
        transform.position = focus + rotation * direction;

        transform.LookAt(focus);
    }
}

```

It shivers only if offset is not zero. Otherwise it's ok.

# Answer
I have solved the problem. It was enough to use this simple code instead of computing focus manually:

```
transform.LookAt(player.position);
transform.Translate(offset, transform);

```
> 1 votes

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


title: Asset Bundle hashes appear inconsistent

text:
# Question
Title: Asset Bundle hashes appear inconsistent
The flow I see people discussing using is the following

1. In your build asset bundles step, grab the hash of each bundle
2. Store that on your server somewhere
3. Fetch those hashes at runtime
4. Use the Caching.IsVersionCached with that hash to detect if you already have a bundle
5. If not download the bundle and cache it
6. success

If this is how you are supposed to do it, why does the main mainfest(example Android.manifest) which can be loaded into a class AssetBundleManifest, have a function to get the hashes for you: unity doc

I was able to just use that technique up until now, but I have hit a problem where it failed to detect a hash change properly and that function is not giving me back the same hash that I see in one of my other bundles .manifest file

Hashes:

AssetFileHash:

serializedVersion: 2

Hash: a44a4d42247721b8bd6f32531f73f9e3

TypeTreeHash:

serializedVersion: 2

Hash: ea5a42e0fd8ea905efa7aa926a3b8944

I am under the impression that the first value above is what would should match what you had stored on your server.

# Answer
Just an update to this in case a future traveler encounters issues of hashes not seeming to work right. After banging my head against this (as using the server stored hashes had the same problem) all day long, I finally found out what was going on. There was a stealth dupe of an asset being inserted into another bundle. The reason I thought my hashes were not correct is because despite the correct asset being in bundle A, there was the stealth copy of the image in bundle B that was the old version. Unity was choosing to use the one in B. This stealth asset does not appear in the manifest for bundle B and is not mentioned in the browser as a warning duplicate asset... Truly a mystery. Makes me wonder how much dupe garbage file size is being used up by other stealth assets...
> 1 votes

---
Tags: unity, asset-workflow
---