# Question
Title: A* Quad/Oc Tree path-finding vs Navigation Mesh path-finding
**Main**

---

What are the differences between those path-finding algorithms.

* Is Navigation Mesh faster in finding the path?
* Is it more correct than Quad/Oc Tree?
* Does Navigation Mesh use Quad/Oc tree under the hood?

My problem is that while creating RTS game I have to make a decision between the 2. The main reason I haven't yet is that Quad Tree is a very good solution because the space is partitioned into bigger nodes that makes path finding quite faster. But if NavMesh in unity uses the same techniques under the hood then there is no reason to bother with Quad Tree.

I have noticed that by the way how the NavMesh is built in Unity it creates quite large chunks of NavMesh, so I can assume that this helps to reduce the calculations if the path lies through that big chunk.

---

**Less Important**

---

Also, I am wondering if NavMesh uses HPA\* under the hood?

\[With combination of Oct Tree that allows to partition path-finding to bigger chunks and calculate the path in them separately and then combine.\] --- --- --- --- --- --- (This last part doesn't seem like it would be an optimization at all, as it just basically calculates the path the same way as without it, so the previous path would be recalculated anyway on fail, but if some custom design solutions could be added to it, like corridors to another part of nav mesh (thinking about it now - it could be implemented with current NavMesh as custom soltuion))

If any clarifications about the split into bigger chunks would be required I can try to draw and provide some images.

# Answer
> 1 votes
There are some tech specs & blog posts on Unity Navigation floating around, if you're curious. But if you're looking for the best approach for your particular game, you'd need to consider a host of factors:

* Entity load - how many entities will be actively pathfinding at once
* Path complexity - static/fixed vs dynamic/variable terrain, will there be other moving and/or pathfinding entities
* Performance on your target platforms, including your other systems, what do you consider to be acceptable frame rates
* Ease of integration & support - your time is valuable, could it be better spent on a different area of production
* Timelines/targets - pathfinding is a key system, that other aspects of development rely on, so working on a custom PF implementation will delay your overall project, if that's important

Really these are general considerations for any game subsystem/component, but hope that helps.

---
Tags: unity, algorithm, path-finding
---


title: 3d game terrain creation approach

text:
# Question
Title: 3d game terrain creation approach
I want to create a terrain/world map for my 3d game.

I want a huge map. For example, ill make it in Blender or generate from a heightmap. Then I plan to divide it in chunks so I can load/unload and show/hide them when needed in the game.

If I want to remake the map, then I will have to divide it in chunks again, and again spend time on placing world objects on the terrain. I'm not sure that is the best way.

What approach is optimal here?

# Answer
> 1 votes
The most versatile, reproducible approach that scales well, would be to both generate and populate your terrain procedurally.

It may be a bridge too far to place everything using code, but things like rocks, vegetation, even roads, could be done procedurally. And maybe leave the high level stuff like buildings, towns, etc, to hand-placing?

If terrain needs to be regenerated with a different seed, populating basic stuff on it will have been taken care off.

As a bonus, you could generate the chunks on-the-fly, so you don't have to store them on disk.

Look for articles on the term 'procgen' to get inspiration. Since you want, in your own words, a huge map, you probably don't have enough level designers helping you populate it anyway.

---
Tags: maps, terrain
---


# Question
Title: Split tile based map file into multiple files
I have a gigantic map file (1440x1080) that I wish to split into smaller files (45x45) for faster client reading. I plan to split offline (when running DEV server) so I am not too worried about speed. Picture the below as my source file:

> ```
> 5, 5, 5, 4, 5, 6, 5... 5
> ...
> 5, 6, 2, 44, 5, 66, 5... 5
>
> ```

I am getting the file to be slightly off towards the end - having trouble doing the math I suppose. I am totally open to changing the code, but here is what I had so far:

```
int filesAcross = mapWidth / 45;
int acrossCount = 0;
int filesDown = mapHeight / 45;
int downCount = 0;
int totalFileCount = filesAcross * filesDown;

//create a bunch of stringbuilder holders to split the large file into
StringBuilder[] sbGroundLayerHolders = new StringBuilder[totalFileCount];
for (int kk = 0; kk < totalFileCount; kk++) {
    sbGroundLayerHolders[kk] = new StringBuilder();
}

int countt = 0;
while(scanner.hasNext()){
    int fileCounter = (acrossCount / 45) + ((downCount / 45) * filesAcross);
    //  LOGGER.info("fileCounter: " + fileCounter + "   acrossCount: " + acrossCount +
    //"   downCount: " + downCount + "   countt: " + countt);
    try {
        sbGroundLayerHolders[fileCounter].append(scanner.nextShort());
        sbGroundLayerHolders[fileCounter].append(",");
        acrossCount++;

        countt++;
    } catch (InputMismatchException e){
        scanner.nextLine();
        downCount++;
        acrossCount = 0;

        countt++;
    } catch (ArrayIndexOutOfBoundsException e){
        LOGGER.fatal("Array Out of Bounds on ground Layer - count:" + countt, e);
        System.exit(1);
    }
}

//write array contents into files
for (int kk = 0; kk < totalFileCount; kk++) {
    String s = sbGroundLayerHolders[kk].toString();
    s = s.substring(0, s.length() - 1);
    String[] sSplit = s.split(",");

    StringBuilder q = new StringBuilder();
    for (int jj = 0; jj < sSplit.length; jj++) {
        q.append(sSplit[jj]);

        if (((jj+1) % 45) == 0 && jj != 0) {
            q.append(System.lineSeparator());
        } else {
            q.append(",");
        }
    }

    LOGGER.info("map string(" + kk + "): " + q);
    //createFileLocally(folderPath, filename, text);
}

```

Here is a sample image of what I want to do (smaller scale). Start with the big grid 6x6 and split into files 2x2.

# Answer
Here is how I solved this in case anyone else needs to do this:

```
int filesAcross = mapWidth / CHUNKSIZE;
int acrossCount = 0;
int filesDown = mapHeight / CHUNKSIZE;
int downCount = 0;
int totalFileCount = filesAcross * filesDown;

//create a bunch of stringbuilder holders to split the large file into
StringBuilder[] sbGroundLayerHolders = new StringBuilder[totalFileCount];
for (int kk = 0; kk < totalFileCount; kk++) {
    sbGroundLayerHolders[kk] = new StringBuilder();
}

int countt = 0;
while(scanner.hasNextLine()){
    String line = scanner.nextLine();
    if (downCount != mapHeight - 1) {
        line = line.substring(0, line.length() - 1); //to remove the last ,
    }
    String[] lineSplit = line.split(", ");
    while(acrossCount < lineSplit.length) {
        int fileCounter = (acrossCount / CHUNKSIZE) + ((downCount / CHUNKSIZE) * filesAcross);
        //LOGGER.info("fileCounter: " + fileCounter + "   acrossCount: " + acrossCount +
        //"   downCount: " + downCount + "   countt: " + countt);
        Short t = Short.parseShort(lineSplit[acrossCount]);
        //LOGGER.info("short: " + t);
        sbGroundLayerHolders[fileCounter].append(t);
        if (((acrossCount + 1) % CHUNKSIZE) == 0 && downCount != CHUNKSIZE - 1) {
            sbGroundLayerHolders[fileCounter].append(System.lineSeparator());
        } else {
            if (acrossCount != lineSplit.length - 1) {
                sbGroundLayerHolders[fileCounter].append(",");
            }
        }
        acrossCount++;

        countt++;
    }
    downCount++;
    acrossCount = 0;
}

```
> 0 votes

---
Tags: java, tilemap
---


# Question
Title: Unity Editor - Call a method from a ScriptableObject from its own custom Editor
I have a class like this:

```
public class NoiseMap : ScriptableObject
{
    public string Hello()
    {
        //...
    }
}

```

Now I am building its custom editor:

```
[CustomEditor(typeof(NoiseMap))]
public class NoiseMapEditor : Editor
{

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        // How to call Hello() ???

        serializedObject.ApplyModifiedProperties();
    }

}

```

I would like to get the value of the method `Hello`. How could I achieve this?

# Answer
you're really close. You just need to get a target reference to the main script like so:

```
public override void OnInspectorGUI()
{
    NoiseMap noiseMap = (NoiseMap)target;

    //then you can reference it like so:

    noiseMap.Hello();
}

```
> 2 votes

---
Tags: unity
---


# Question
Title: How do I find the downward sliding direction of a plane?
first time poster.

I'm curious as to how I can obtain a vector that defines the downward slope of a 3D plane. The goal is to apply this to a player as a force to achieve a sliding mechanic, like in Mario 64 (for steep floors and slide levels).

My attempts at this used variations of this equation, but it's not quite what I'm looking for.

b * ( -2\*(V dot N)\*N + V ) where v is the vector that you want to reflect, n is the normal of the plane, b is the amount of momentum preserved (0.0 - 1.0).

this gives a reflected vector

I also have means to calculate the plane normal and get the intersection point of the player

Any other ideas to solve this are also appreciated

# Answer
> 5 votes
Take a vector representing your global up direction, and cross it with your plane normal.

This gives you a horizontal vector pointing across your slope. By the properties of the cross product it has to be perpendicular to both the plane normal (putting it in the plane) and the up vector (putting it in the horizontal plane).

```
Vector3 acrossSlope = Vector3.Cross(globalUp, planeNormal);

```

Now we can cross this vector with your plane normal again to get a vector pointing down-slope:

```
Vector3 downSlope = Vector3.Cross(acrossSlope, planeNormal);

```

Again by construction, this has to be perpendicular to both the plane normal (putting it in the plane) and the "across" vector (meaning it points up/down the plane, depending on the order you put the two arguments.

You can normalize the result to get it back to unit length.

---
Tags: 3d, mathematics, vector
---


# Question
Title: Can't figure out why my mouse picking code doesn't work
I am trying to create code to check for intersections between bounding spheres and the mouse. I get a mouse ray but it doesnt seem to point in the direction you think it should Attached is a screenshot and code. If anyone can help I would appreciate it as this is driving me crazy.

```
    auto state = m_mouse->GetState();

    float mouseX = state.x;
    float mouseY = state.y;
    float m_screenWidth = m_deviceResources->GetScreenViewport().Width;
    float m_screenHeight = m_deviceResources->GetScreenViewport().Height;

    // Normalized device coordinates
    float x = (2.0f * mouseX) / m_screenWidth - 1.0f;
    float y = 1.0f - (2.0f * mouseY) / m_screenHeight;

    DirectX::XMMATRIX viewMatrix = DirectX::XMMatrixTranspose(DirectX::XMLoadFloat4x4(&cameraComponentHandle->view));
    DirectX::XMMATRIX projectionMatrix = DirectX::XMMatrixTranspose(DirectX::XMLoadFloat4x4(&cameraComponentHandle->projection));
    DirectX::XMMATRIX inverseviewproj = DirectX::XMMatrixInverse(nullptr, viewMatrix * projectionMatrix);

    DirectX::SimpleMath::Vector3 origin = DirectX::SimpleMath::Vector3(x, y, 0);
    DirectX::SimpleMath::Vector3 farPoint = DirectX::SimpleMath::Vector3(x, y, 1);

    DirectX::SimpleMath::Vector3 rayorigin = DirectX::XMVector3TransformCoord(origin, inverseviewproj);
    DirectX::SimpleMath::Vector3 rayend = DirectX::XMVector3TransformCoord(farPoint, inverseviewproj);
    DirectX::SimpleMath::Vector3 raydirection = (rayend - rayorigin);
    raydirection.Normalize();

    rayComponentHandle->position = rayorigin;
    rayComponentHandle->direction = raydirection;

```

# Answer
As it turns out the code is correct and my problem was with the rendering of the ray itself. I was calculating a world matrix when the coordinates were already in worldspace.
> 1 votes

---
Tags: c++, directx, directx11, raycasting, picking
---


# Question
Title: Better way to handle speed able time and action in unity
I have came across a problem where i have to do some time based task(simulation) like, As the game started:

* After 2 mintues launch a missle.
* After 4 mintues star a train on track
* after 12 minutes start the charater walk etc Now i am considering two approaches (other are also welcome)

**Each script manage its time:**

```
void Start()
{
    StartCoroutine("MyEvent");
}

private IEnumerator MyEvent()
{

    yield return new WaitForSeconds(120f); // wait two minutes
    //Launch missle etc

}

```

Like this kind of script attach with every object that require action after certain time: Problem:

1. How do i speed up its time ?
2. Maybe Performance intensive.

**One Timer Global script:**

```
function Update ()
{
Timer += Time.deltaTime; //Time.deltaTime will increase the value with 1 every second.
if (timer>= 120){
//launch missle, an so one conditions
}

```

}

Now using above script i can get Timer variable in other script and can execute my task on based on time. Now the question is that how do i manage it first way or second way or third way(by you)? Beacause i also want to speedup the time too which seems impossible with coroutine.

# Answer
> 1 votes
## What I would do:

Honestly, the *global approach* doesn't look like the best way to approach this, since it can raise multiple problems: What if I want to update the `waitTime` of a specific object? How do I get a reference to it? What happens if I delete it at runtime? \[...\] That quickly becomes taxing on performance;

I would honestly create a `Timer` class, which you attach to every object you want to be activated after a certain amount of time (I don't have a compiler at hand, so there might be a couple of errors. Edits are welcome!)

### Timer

```
using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour
{
     private float m_WaitTime = 1.0f;

     public void WaitTime(float newtime)
     {
          Deactivate(); // deactivate the object
          StopCoroutine(Wait()); // stop the coroutine
          m_WaitTime = newtime; // update the time
          StartCoroutine(Wait()); // wait for "newtime" seconds
     }

     private IENumerator Wait()
     {
         // wait until the wait time is 0
         while (m_WaitTime > 0.0f)
         {
             // decrease the wait time on every iteration of this loop
             m_WaitTime -= Time.deltaTime;
             yield return null;
         }
         // finally, activate the object
         Activate();
     }

     private void Activate()
     {
          Debug.Log("Object Activated");
     }

     private void Deactivate()
     {
          Debug.Log("Object Deactivated");
     }
}

```

This way we can have multiple *self-managed* entities, that don't rely on a global object and that can be added, removed or updated without causing any issues.

You could even make an abstract class and implement different types of behaviours, or maybe use an enum and change the object's behaviour based on it's value ;)

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


title: Closest node in A* pathfinding

text:
# Question
Title: Closest node in A* pathfinding
For my 2D Unity game, I've implemented A\* pathfinding based on waypoints. System already handles building graph from waypoints on scene (which are manually placed objects), as well as finding and caching closest routes.

So, general idea is to select closest waypoint to character, closest waypoint to target position, and use pathfinding algorithm to find closest route (which is pre-cached already).

Yet, I've stumbled into issue - I don't know how to actually get closest waypoint. Well, there are several ways I think of, in the worst case I can just brute-force closest non-blocked waypoint from the collection, but that would be bad performance-wise.

So, are there any proper ways to get start or end points?

# Answer
> 1 votes
If the movement is limited per frame you only need to look at the neighbours of the previous character and target waypoints to find the new ones. So you only need the expensive search when you have teleports or on spawn. And with fixed teleport targets and spawn points you can cache those as well.

The standard computer science answer for finding closest node is to build a voronoi diagram with the nodes and get closest nodes from that.

However any spatial partitioning will give you the speedup you need.

---
Tags: unity, path-finding
---


title: How to calculate suitable attack speed

text:
# Question
Title: How to calculate suitable attack speed
I'm developing an RPG and am stuck trying to create a formula for attack speed, using four stats and a base speed.

Basically, I'm trying to get an outcome where the encumbrance (basically weight and ease of handling in a single stat) of armor and weapon along with the players´ strength and agility will effect the attack speed.

So - for example: A player with a heavy armor and a 2-handed maul might end up with 0.35 attacks per second, while an unarmored dagger-wielding player should have around 2.5 or even 3 (which would be the maximum speed).

Weapons and armor have an `encumbrance` stat. Players have `agility` and `strength`.

In order to make it more realistic, I'm trying to integrate the following into the formula:

* The penalty from the total `encumbrance` of all items should have a smaller impact on the attack speed than the `encumbrance` of the weapon
* The penalty from the weapon `encumbrance` should depend on both agility and strength
* There should be a maximum attack speed (around 3 attacks per second)
* Higher `agility` should result in higher attack speed
* Higher `strength` should lessen the overall `encumbrance` penalty

I'm not yet sure if the ranges or min/max stats are needed for the formula, but currently player stats will range between 1-10 and encumbrance (per item) from 1-10 as well.

I've given this a couple of hours of thought but I feel that my math skills might simply not be up to par.

Here's the current state of my attempt (non-functional): https://docs.google.com/spreadsheets/d/1S\_NOsJp-FegY7ruR6EZTqWRxuP6gDnZJr9LYw8ETZKQ/edit#gid=0

# Answer
> 0 votes
Here goes one possible answer that can be further tweaked:

Let's first consider that your attack speed **AS** comes directly from agility modified by some constants, thus:

```
AS = Agility * alpha

```

If we say that Agility goes from 1 - 10, and alpha = 3/10, this means that at the lowest agility, you'd have 0.3 attacks per second and 3 attacks per second at the highest agility.

Now, we want encumbrance to modify this value, so adding to the equation gets us:

```
AS = (Agility * alpha) * EncMod,

```

where EncMod goes from 0.7 to 1.3 (or any other range, this is just to say it will modify the first portion of the equation by -30% to +30%).

EncMod will depend from both Strength and Agility, and will have an arbitrary range that must be converted to 0.7 to 1.3. Let's call this arbitrary encumbrance EncArb.

```
EncArb = 1/(EqEnc * 1/(Strength * gamma + Agility*sigma))

```

EqEnc is the encumbrance defined by equipment. This will be modified by strength and agility (modified by proportional contributions gamma and sigma). The inversions are somewhat messy, but they do the job here.

Putting it all together, we have:

```
EncMod = ((1.3 - 0.7)/(15-0.15))*EncArb + 0.7;

```

NOTE: Why 15 - 0.15? Those are the maximum and minimum EncArb values. They vary according to gamma, sigma, and maximum EqEnc, Agility and Strength. Those are sample values only.

Ok, time to put everything together. The final equation then is:

```
AS = ((Agility + beta)*alpha) * EncMod

```

(beta here is just helping the lowest attack speed not to fall too much).

To give some illustrative values:

I have set

```
gamma  = 1
sigma  = .5
alpha  = 2.25
beta   = 0.75

```

Agility, Strength, and EqEnc all varying between 1 and 10.

So:

```
Ag = 10, St = 10, EqEnc = 1 --> AS = 3.1
Ag = 1, St = 1, EqEnc = 10 --> AS = 0.28
Ag = 5, St = 5, EqEnc = 5 --> AS = 0.98
Ag = 5, St = 10, EqEnc = 5 --> AS = 1.03

```

As you can see, you still need to play a bit with gamma and sigma values to make it more balanced (and make strength less useless), but this is more a matter of adjusting the values rather than the calculation.

# Answer
> 0 votes
I'd say start easy, there's actually not much math in here.

* What is the default attack speed? Let's say it's 2 attacks per second.
* Now you add to the formula the encumbrance of the weapon. What's the maximum encumbrance that you want to have? How slow is the slowest weapon? Let's say it's a giant two-handed hammer that can only do half the attacks, i.e. 1 per second. That means the weapon encumbrance has to be such that it halves the attacks per second. So, you need a number that multiplied by 2 gives you 1, which is 0.5. The slowest weapon has an encumbrance of 0.5.
* Now add the encumbrance of the inventory. Again, what's the slowest you can get? Let's say the maximum penalty is going from 2 attacks per second to 1.5. So, you need a number that multiplied by 2 gives you 1.5. That's 0.75.
* These are actually the "speeds" of your inventory and weapon more than the encumbrance (because the higher you get, the faster you are). You could get the encumbrance by simply using `1 - speed`. In this case `1 - 0.75` = 0.25
* A first, basic formula would than be `(1 - inventory_speed) * (1 - weapon_speed) * basic_attack_speed`.

Until now, with the slowest values, you'd get `(1 - 0.25) * (1 - 0.50) * 2 = 0.375` attacks per second.

* Now, if you have strength such that the encumbrance is reduced (which means: the speed is increased), you can apply that before the formula, and use the new speed/encumbrance values in the formula.
* So, you first apply the strength bonus by reducing encumbrance (increasing speed), then you use the above formula.
* Same idea: what's the highest bonus you can get?

Repeat for agility, and you'll have your formula in no time.

---
Tags: mathematics, rpg
---


# Question
Title: In Unity, my mesh is not rendering when huge (scale of 1400000)
Any help/tips? This is for a space game and I really want realistic measures. The user WILL get really close to the sun. Any tips with dealing this? I can see the whole "Corona" but not the big sphere at the center

# Answer
If you have to scale something to 1.400.000, then you are doing something wrong.

If you want to create a massive planet to be ultra realistic and have everything on it loaded at all times, I doubt there is any machine capable at running something like that with more than 1 frame a second. And that's if I'm really optimistic.

The right way to do it, is to create the "illusion" that everything is there. You want to show a massive planet? Sure, instead of a sprite (or model) being millions of units away and millions of times scaled so that it covers half of the sky, make the planet be only 200-300 units away, so that it's closer, and scale it only 100 times, because it's already bigger. This would give the illusion that the planet is massive, and everyone knows planets are far away, so I doubt anyone will notice anything wrong with it.

You want to travel to the surface of the planet? Simple, while you approach the planet, for each unit that you travel, the planet moves half as much away from you, but becomes bigger 3 times as much (example numbers). This would make your player keep approaching the planet, and the planet will slowly get bigger, but it will look like you are just getting closer to it.

These are just examples of how you can approach problems like these. Floating points become less accurate the bigger they become, so it's always a bad idea if they are too big.
> 2 votes

---
Tags: unity
---


# Question
Title: How to find 1/3 and 2/3 of the distance between two given points?
I know how to find the middle of two given points:

```
var midpoint = (pointA + pointB)/2;

```

where `pointA` and `pointB` are `Vector2`

I thought that

```
var thirdBtnPoints = (pointA + pointB)/3;
var twoThirdBtnPoints = 2*(pointA + pointB)/3;

```

should give me 1/3 and 2/3 between the two points but it doesn't. I guess this might be more of a math question though, but how can I find 1/3 and 2/3 of the distance between two given points?

# Answer
> 2 votes
Let A and B be the two points. The formula looks like this:

```
desiredPoint = A +(B-A) *2/3;

```

Replace `2/3` by your desired fraction. This counts from point `A`, so `2/3` means the resulting point will be closer to point `B`.

The explanation is simple. You take point `A`, then move towards `B` (`+(B-A)`), and multiply that by how long towards `B` to move (`*2/3`).

Since you are using Unity, you can use its own function `Lerp`: (Thanks @DMGregory)

```
Vector3 desiredPoint = Vector3.Lerp(A, B, 2f/3f);

```

This basically gives the same result as the explanation above.

---
Tags: unity, mathematics
---


# Question
Title: Android Unity black screen on game start up
Squishing bugs on my first game currently, came across a problem I'm not sure what could cause.

When the game is launched there is simply a black screen before even the unity logo shows up, the duration is about 5 seconds. Checked on 2 devices: S6 and 1st gen Moto X, the duration is about the same.

The scene loaded on start-up is a simple menu with almost no logic, just some buttons.

I am using the Unity Google Play plug-in, could it be somehow connected with this issue?

# Answer
The problem was caused by it being a development build with script debugging, a normal build works as expected.
> 2 votes

# Answer
A somewhat hilarious yet very real situation:

My blackscreen was caused by the fact that I had a canvas or camera with the "EditorOnly" tag. Removing this tag made the objects work correctly during the actual builds, and the black screen was no more.
> 1 votes

---
Tags: unity, c#, android, google-play
---


# Question
Title: Raymarching in Unity's new SRP & Post Processing V2
Hello wonderful wizards of the shader world!

I've seen a few tutorials featuring the use of Raymarching via the older `OnRenderImage` function, however, that is no longer called in the new stack (what is the correct terminology -- is it SRP? Post Processing V2? HDRP?). The intention is to eventually add depth into the rendering so the raymarched objects can be culled/occluded in object space.

Anyways, here is my attempt at rendering a simple sphere. The issue here is the sphere is not being drawn until the camera is physically touching the sphere, at which point the entire viewport is drawing the sphere's color.

Post Processing Script

```
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
[Serializable]
[PostProcess(typeof(DebugRenderer), PostProcessEvent.AfterStack, "Custom/Debug")]
public sealed class Debug : PostProcessEffectSettings
{
    public IntParameter maxIterations = new IntParameter { value = 64 };
    public FloatParameter maxDistance = new FloatParameter { value = 100f };
    public FloatParameter minDistance = new FloatParameter { value = 0.01f };
    public DepthTextureMode GetCameraFlags()
    {
        return DepthTextureMode.Depth; //| DepthTextureMode.DepthNormals;
    }
}
public sealed class DebugRenderer : PostProcessEffectRenderer<Debug>
{
    //public override DepthTextureMode GetCameraFlags()
    //{
    //    return DepthTextureMode.Depth;
    //}
    [SerializeField]
    private Shader _shader;
    public Material _raymarchMaterial
    {
        get
        {
            if (!_raymarchMat && _shader)
            {
                _raymarchMat = new Material(_shader);
                _raymarchMat.hideFlags = HideFlags.HideAndDontSave;
            }
            return _raymarchMat;
        }
    }
    private Material _raymarchMat;
    public Camera _camera
    {
        get
        {
            if (!_cam)
            {
                _cam = Camera.main;
            }
            return _cam;
        }
    }
    private Camera _cam;
    public override void Render(PostProcessRenderContext context)
    {
        if (!_cam)
        {
            _cam = Camera.main;
        }
        var sheet = context.propertySheets.Get(Shader.Find("Hidden/Debug"));
        sheet.properties.SetMatrix("_CamFrustum", FrustumCorners(_cam));
        sheet.properties.SetMatrix("_CamToWorld", _cam.cameraToWorldMatrix);
        sheet.properties.SetVector("_CamWorldSpace", _cam.transform.position);
        sheet.properties.SetInt("_MaxIterations", settings.maxIterations);
        sheet.properties.SetFloat("_MaxDistance", settings.maxDistance);
        sheet.properties.SetFloat("_MinDistance", settings.minDistance);
        context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
    }
    private Matrix4x4 FrustumCorners(Camera cam)
    {
        Transform camtr = cam.transform;
        Vector3[] frustumCorners = new Vector3[4];
        cam.CalculateFrustumCorners(new Rect(0, 0, 1, 1), cam.farClipPlane, cam.stereoActiveEye, frustumCorners);
        var bottomLeft = camtr.TransformVector(frustumCorners[0]);
        var topLeft = camtr.TransformVector(frustumCorners[1]);
        var topRight = camtr.TransformVector(frustumCorners[2]);
        var bottomRight = camtr.TransformVector(frustumCorners[3]);
        Matrix4x4 frustumCornersArray = Matrix4x4.identity;
        frustumCornersArray.SetRow(0, bottomLeft);
        frustumCornersArray.SetRow(1, bottomRight);
        frustumCornersArray.SetRow(2, topLeft);
        frustumCornersArray.SetRow(3, topRight);
        return frustumCornersArray;
    }
}

```

Shader

```
Shader "Hidden/Debug"
{

    SubShader
    {
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            HLSLPROGRAM

            #pragma target 3.5

            #pragma vertex vert
            #pragma fragment frag

            //#include "Packages/com.unity.postprocessing/PostProcessing/Shaders/StdLib.hlsl"
            //#include "HLSLSupport.cginc"
            #include "UnityCG.cginc"

            //TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex);
            uniform sampler2D _MainTex;
            uniform sampler2D_float _CameraDepthTexture;
            half4 _MainTex_ST;
            uniform float4 _CamWorldSpace;
            uniform float4x4 _CamFrustum,  _CamToWorld;
            uniform int _MaxIterations;
            uniform float _MaxDistance;
            uniform float _MinDistance;
            float4 _Tint;

            uniform float4 _MainTex_TexelSize;

            struct AttributesDefault
            {
                float3 vertex : POSITION;
                half2 texcoord : TEXCOORD0;
            };
            struct VaryingsDefault
            {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                //float2 uvStereo : TEXCOORD1;
                float2 uv_depth : TEXCOORD1;
                float4 interpolatedRay : TEXCOORD2;
            };

            float LinearEyeDepth135( float z )
            {
                return LinearEyeDepth( z );
            }
            // Vertex manipulation
            float2 TransformTriangleVertexToUV(float2 vertex)
            {
                float2 uv = (vertex + 1.0) * 0.5;
                return uv;
            }

            VaryingsDefault vert(AttributesDefault v  )
            {
                VaryingsDefault o;
                v.vertex.z = 0.1;
                o.pos = float4(v.vertex.xy, 0.0, 1.0);
                o.uv = TransformTriangleVertexToUV(v.vertex.xy);
                o.uv_depth = v.texcoord.xy;
                #if UNITY_UV_STARTS_AT_TOP
                    o.uv = o.uv * float2(1.0, -1.0) + float2(0.0, 1.0);
                #endif

                //o.uvStereo = TransformStereoScreenSpaceTex(o.uv, 1.0);
                #if UNITY_UV_STARTS_AT_TOP
                    if (_MainTex_TexelSize.y < 0)
                        o.uv.y = 1 - o.uv.y;
                #endif
                int frustumIndex = v.texcoord.x + (2 * o.uv.y);
                o.interpolatedRay = _CamFrustum[frustumIndex];
                o.interpolatedRay.w = frustumIndex;
                return o;
            }

            float sdSphere(float3 position, float3 origin, float radius)
            {
                return distance(position, origin) - radius;
            }

            fixed4 raymarching(float3 ro, float3 rd) {
                fixed4 result = float4(1, 1, 1, 1);
                float t = 0; // Distance Traveled from ray origin (ro) along the ray direction (rd)

                for (int i = 0; i < _MaxIterations; i++)
                {
                    if (t > _MaxDistance)
                    {
                        result = float4(rd, 1); // color backround from ray direction for debugging
                        break;
                    }

                    float3 p = ro + rd * t;    // This is our current position
                    float d = sdSphere(ro, float3(0, 0, 0), 1); // should be a sphere at (0, 0, 0) with a radius of 1
                    if (d <= _MinDistance) // We have hit something
                    {
                        // shading
                        result = float4(1, 1, 0, 1); // yellow sphere should be drawn at (0, 0, 0)
                        break;
                    }

                    t += d;
                }

                return result;
            }

            float4 frag(VaryingsDefault i) : SV_Target
            {
                float4 wsDir = normalize(i.interpolatedRay);
                float4 wsPos = _CamWorldSpace;
                fixed4 result = raymarching(wsPos, wsDir);
                return result;
            }

            ENDHLSL
        }
    }
}

```

For reference, I am converting the C# script and shader from Peer Play's tutorial video to the SRP.

Anyways, thanks for reading, and please let me know if I can provide any more information.

Cheers!

Edit: I think the issue may be in the vert function as I am not handling `v.vertex` and `o.vertex` the same as in the video. This clashes with my limited understanding of what is going on in the `VertDefault` function found in `PostProcessing/StdLib.hlsl`

# Answer
Update: more info, including object space culling, found here.

YES!!! After SO many days, so much time spent feeling defeated, I GOT IT!

Many thanks to this blog post and this forum post for giving me clues for the right direction.

Here is the completely hideous working solution to raymarch a sphere in Unity's PostFX V2 stack!

`Debug.cs`

```
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;

[Serializable]
[PostProcess(typeof(DebugRenderer), PostProcessEvent.AfterStack, "Custom/Debug")]
public sealed class Debug : PostProcessEffectSettings
{
    public IntParameter maxIterations = new IntParameter { value = 64 };
    public FloatParameter maxDistance = new FloatParameter { value = 100f };
    public FloatParameter minDistance = new FloatParameter { value = 0.01f };

    public DepthTextureMode GetCameraFlags()
    {
        return DepthTextureMode.Depth; //| DepthTextureMode.DepthNormals;
    }
}

public sealed class DebugRenderer : PostProcessEffectRenderer<Debug>
{
    public override void Render(PostProcessRenderContext context)
    {
        Camera _cam = context.camera;

        var sheet = context.propertySheets.Get(Shader.Find("Hidden/Debug"));
        sheet.properties.SetMatrix("_CamFrustum", FrustumCorners2(_cam));
        sheet.properties.SetMatrix("_CamToWorld", _cam.cameraToWorldMatrix);
        sheet.properties.SetVector("_CamWorldSpace", _cam.transform.position);
        sheet.properties.SetInt("_MaxIterations", settings.maxIterations);
        sheet.properties.SetFloat("_MaxDistance", settings.maxDistance);
        sheet.properties.SetFloat("_MinDistance", settings.minDistance);

        context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
    }

    private Matrix4x4 CamFrustum(Camera cam)
    {
        Matrix4x4 frustum = Matrix4x4.identity;
        float fov = Mathf.Tan((cam.fieldOfView * 0.5f) * Mathf.Deg2Rad);

        Vector3 goUp = Vector3.up * fov;
        Vector3 goRight = Vector3.right * fov * cam.aspect;

        Vector3 TL = (-Vector3.forward - goRight + goUp);
        Vector3 TR = (-Vector3.forward + goRight + goUp);
        Vector3 BR = (-Vector3.forward + goRight - goUp);
        Vector3 BL = (-Vector3.forward - goRight - goUp);

        frustum.SetRow(0, TL);
        frustum.SetRow(1, TR);
        frustum.SetRow(2, BR);
        frustum.SetRow(3, BL);

        return frustum;
    }

    private Matrix4x4 GetFrustumCorners(Camera cam)
    {
        float camFov = cam.fieldOfView;
        float camAspect = cam.aspect;

        Matrix4x4 frustumCorners = Matrix4x4.identity;

        float fovWHalf = camFov * 0.5f;

        float tan_fov = Mathf.Tan(fovWHalf * Mathf.Deg2Rad);

        Vector3 toRight = Vector3.right * tan_fov * camAspect;
        Vector3 toTop = Vector3.up * tan_fov;

        Vector3 topLeft = (-Vector3.forward - toRight + toTop);
        Vector3 topRight = (-Vector3.forward + toRight + toTop);
        Vector3 bottomRight = (-Vector3.forward + toRight - toTop);
        Vector3 bottomLeft = (-Vector3.forward - toRight - toTop);

        frustumCorners.SetRow(0, topLeft);
        frustumCorners.SetRow(1, topRight);
        frustumCorners.SetRow(2, bottomRight);
        frustumCorners.SetRow(3, bottomLeft);

        return frustumCorners;
    }

    private Matrix4x4 FrustumCorners(Camera cam)
    {
        Transform camtr = cam.transform;
        Vector3[] frustumCorners = new Vector3[4];
        cam.CalculateFrustumCorners(new Rect(0, 0, 1, 1), cam.farClipPlane, cam.stereoActiveEye, frustumCorners);
        var bottomLeft = camtr.TransformVector(frustumCorners[0]);
        var topLeft = camtr.TransformVector(frustumCorners[1]);
        var topRight = camtr.TransformVector(frustumCorners[2]);
        var bottomRight = camtr.TransformVector(frustumCorners[3]);

        Matrix4x4 frustumCornersArray = Matrix4x4.identity;
        frustumCornersArray.SetRow(0, bottomLeft);
        frustumCornersArray.SetRow(1, bottomRight);
        frustumCornersArray.SetRow(2, topLeft);
        frustumCornersArray.SetRow(3, topRight);

        return frustumCornersArray;
    }

    private Matrix4x4 FrustumCorners2(Camera cam)
    {
        Transform camtr = cam.transform;

        Vector3[] frustumCorners = new Vector3[4];
        cam.CalculateFrustumCorners(new Rect(0, 0, 1, 1),
         cam.farClipPlane, cam.stereoActiveEye, frustumCorners);
        var bottomLeft = camtr.TransformVector(frustumCorners[1]);
        var topLeft = camtr.TransformVector(frustumCorners[0]);
        var bottomRight = camtr.TransformVector(frustumCorners[2]);

        Matrix4x4 frustumVectorsArray = Matrix4x4.identity;
        frustumVectorsArray.SetRow(0, bottomLeft);
        frustumVectorsArray.SetRow(1, bottomLeft + (bottomRight - bottomLeft) * 2);
        frustumVectorsArray.SetRow(2, bottomLeft + (topLeft - bottomLeft) * 2);

        return frustumVectorsArray;
    }
}

```

`Debug.shader`

```
Shader "Hidden/Debug"
{

    SubShader
    {
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            HLSLPROGRAM

            #pragma target 3.5

            #pragma vertex vert
            #pragma fragment frag

            //#include "Packages/com.unity.postprocessing/PostProcessing/Shaders/StdLib.hlsl"
            //#include "HLSLSupport.cginc"
            #include "UnityCG.cginc"

            //TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex);
            uniform sampler2D _MainTex;
            uniform sampler2D_float _CameraDepthTexture, sampler_CameraDepthTexture;
            half4 _MainTex_ST;
            uniform float4 _CamWorldSpace;
            uniform float4x4 _CamFrustum,  _CamToWorld;
            uniform int _MaxIterations;
            uniform float _MaxDistance;
            uniform float _MinDistance;
            float4 _Tint;

            uniform float4 _MainTex_TexelSize;

            struct AttributesDefault
            {
                float3 vertex : POSITION;
                half2 texcoord : TEXCOORD0;
            };

            struct VaryingsDefault
            {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                float2 uvStereo : TEXCOORD4;
                //float2 uvStereo : TEXCOORD1;
                float2 uv_depth : TEXCOORD1;
                float4 interpolatedRay : TEXCOORD2;
                float3 wPos : TEXCOORD3;
            };

            struct v2f
            {
             float4 vertex : SV_POSITION;
             float2 texcoord : TEXCOORD0;
             float2 texcoordStereo : TEXCOORD1;
             float4 ray : TEXCOORD2;
            };

            float LinearEyeDepth135( float z )
            {
                return LinearEyeDepth( z );
            }
            // Vertex manipulation
            float2 TransformTriangleVertexToUV(float2 vertex)
            {
                float2 uv = (vertex + 1.0) * 0.5;
                return uv;
            }

            //VaryingsDefault vert(AttributesDefault v  )
            //{
            //  VaryingsDefault o;
            //  v.vertex.z = 0.1;
            //  o.wPos =  mul(UNITY_MATRIX_VP, v.vertex);
            //  o.pos = float4(v.vertex.xy, 0.0, 1.0);
            //  o.uv = TransformTriangleVertexToUV(v.vertex.xy);
            //  o.uv_depth = v.texcoord.xy;

            //  #if UNITY_UV_STARTS_AT_TOP
            //      o.uv = o.uv * float2(1.0, -1.0) + float2(0.0, 1.0);
            //  #endif

            //  o.uvStereo = TransformStereoScreenSpaceTex(o.uv, 1.0);

            //  #if UNITY_UV_STARTS_AT_TOP
            //      if (_MainTex_TexelSize.y < 0)
            //          o.uv.y = 1 - o.uv.y;
            //  #endif

            //  //int frustumIndex = v.texcoord.x + (2 * o.uv.y);
            //  //o.interpolatedRay = _CamFrustum[frustumIndex];
            //  //o.interpolatedRay.w = frustumIndex;

            //  int index = (o.uv.x / 2) + o.uv.y;
            //  o.interpolatedRay = _CamFrustum[index];
            //  //o.interpolatedRay /= abs(o.interpolatedRay.z);
            //  //o.interpolatedRay = mul(_CamToWorld, o.interpolatedRay);

            //  return o;
            //}

            v2f vert(AttributesDefault v  )
            {
                v2f o;
                v.vertex.z = 0.1;
                //o.vertex = mul(UNITY_MATRIX_VP, v.vertex);
                o.vertex = float4(v.vertex.xy, 0.0, 1.0);
                o.texcoord = TransformTriangleVertexToUV(v.vertex.xy);

                //#if UNITY_UV_STARTS_AT_TOP
                //  o.texcoord = o.texcoord * float2(1.0, -1.0) + float2(0.0, 1.0);
                //#endif

                o.texcoordStereo = TransformStereoScreenSpaceTex(o.texcoord, 1.0);

                //#if UNITY_UV_STARTS_AT_TOP
                //  if (_MainTex_TexelSize.y < 0)
                //      o.texcoord.y = 1 - o.texcoord.y;
                //#endif

                //int index = v.texcoord.x + (2 * o.texcoord.y);
                int index = (o.texcoord.x / 2) + o.texcoord.y;
                o.ray = _CamFrustum[index];

                return o;
            }

            float sdSphere(float3 position, float3 origin, float radius)
            {
                return distance(position, origin) - radius;
            }

            float sdf_sphere(float3 p, float3 c, float r)
             {
                 return distance(p, c) - r;
             }

            fixed4 raymarching(float3 rayOrigin, float3 rayDirection) {
                fixed4 result = float4(1, 1, 1, 1);
                float t = 0.01; // Distance Traveled from ray origin (ro) along the ray direction (rd)

                for (int i = 0; i < _MaxIterations; i++)
                {
                    if (t > _MaxDistance)
                    {
                        result = float4(rayDirection, 1); // color backround from ray direction for debugging
                        break;
                    }

                    float3 p = rayOrigin + rayDirection * t;    // This is our current position
                    //float3 p = float3(5, 0, 0) + (float3(1, 0, 0) * t);   // This is our current position
                    //float d = sdSphere(p, float3(1, 0, 0), 2); // should be a sphere at (0, 0, 0) with a radius of 1
                    float d = sdf_sphere(p, float3(0, 0, 0), 1);
                    if (d <= _MinDistance) // We have hit something
                    {
                        // shading
                        result = float4(1, 1, 1, 1); // yellow sphere should be drawn at (0, 0, 0)
                        break;
                    }

                    //t += max(0.01, 0.02 * 2);
                    t += d;
                }

                return result;
            }

            fixed4 rm (float3 ro, float3 rd) {
                fixed4 result = float4(0, 0, 0, 1);
                float t = 0;

                for (int i = 0; i < 100; i++) {
                    float3 p = ro + rd * t;
                    float d = sdf_sphere(p, float3(0, 0, 0), 0.8);
                    if (d <= _MinDistance) // We have hit something
                    {
                        // shading
                        result = float4(1, 1, 0, 1); // yellow sphere should be drawn at (0, 0, 0)
                        break;
                    }

                    t += d;
                }

                return result;
            }

            float4 frag(v2f i) : SV_Target
            {
                //float rawDepth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, UnityStereoTransformScreenSpaceTex(i.uv ));
                //float dpth = Linear01Depth(rawDepth);

                //float depth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, sampler_CameraDepthTexture, i.uvStereo);
                //depth = Linear01Depth(depth);

                //float rawDepth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uvStereo);
                //float dpth = Linear01Depth(rawDepth);

                ////float4 wsDir = normalize(i.interpolatedRay);
                //float3 wsDir = normalize(i.interpolatedRay);
                //float4 wsPos = _CamWorldSpace;
                ////fixed4 result = raymarching(_CamWorldSpace, normalize(i.interpolatedRay.xyz));
                //fixed4 result = rm(_CamWorldSpace, normalize(i.interpolatedRay.xyz));
                //return result;

                //float dpth = Linear01Depth(rawDepth);
                //return raymarching(_WorldSpaceCameraPos, normalize(i.interpolatedRay));

                return raymarching(_CamWorldSpace, normalize(i.ray));

                //half4 sceneColor = tex2D(_MainTex, UnityStereoTransformScreenSpaceTex(i.uv));

                //// Reconstruct world space position & direction
                //// towards this screen pixel.
                //float rawDepth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, UnityStereoTransformScreenSpaceTex(i.uv ));

                //float dpth = Linear01Depth(rawDepth);
                //float4 wsDir = dpth * i.interpolatedRay;
                //float4 wsPos = _CamWorldSpace + wsDir;

                //return wsPos;
                //return raymarching(wsPos, wsDir);
            }

            ENDHLSL
        }
    }
}

```
> 1 votes

---
Tags: unity, raymarching
---


# Question
Title: Object coming from far away effect in 2D
I have a path made using segments of sine wave interpolation put together that is drawn flat on the screen. And I would like to give the path the effect of coming towards the player. I tried to draw what I want to do, left is what I have now and right is the desired effect:

so the "farther" away the end of the segment is the smaller it's scale is and the segments are closer together. I think this would give the effect I'm looking for but I'm not sure how to do it.

This is the code I use to create a segment. It keeps track of the last point of the segment so the next segment can start from there.

```
private void createSegment() {
    int g = r.Next(i, i + 240);
    for (float j = 0; j < 1f; j += 0.01f) {
        Points.Add(new Vector2(CosineInterpolate(lastX, g, j), startY));
        startY--;
    }
    lastX = g;
}

```

# Answer
I will make some assumptions about your function, that you need to call it twice, once for both the left and and right hand sides of your road. For what you are doing, you are close.

```
private void createSegment(float desiredWidth, float direction, List<Vector2> pointsList) {
    int g = r.Next(i, i + 240);
    for (float j = 0; j < 1f; j += 0.01f)
    {
        float modifier = desiredWidth * j * direction;
        pointsList.Add(new Vector2(CosineInterpolate(lastX, g, j), startY) + new Vector2(modifier, 0));
        startY--;
    }
    lastX = g;
}

```

I'm going to assume that you will have 2 lists that will represent the left and right hand sides. And that as you iterate through creating your list of points. Just a heads up, you can use any sort of scaling in the modifier variable. You may want to add some small exponential calculation if you want to make it look more 3d.

as mentioned, i've made some assumptions about what you're trying to achieve. If this isn't a fit, then all ok! GL
> 1 votes

---
Tags: c#, 2d, monogame, effect
---


# Question
Title: Black screen after running emulation mode in the Unity Editor for hololens
I am having issues with black screen when running the emulation mode or simulator for Microsoft hololens. In the preview the camera shows what the user should see. I see no obvious reason to behave like this and no error/warning is given. I am using code snippets from the Origami tutorial,except I chose to use RayCastNonAlloc.

Movement.cs
`public class Movement : MonoBehaviour {
public GameObject person;
 public float seconds;
private Vector3 point = new Vector3(0,0,0);
 private RaycastHit[] rayHit = new RaycastHit[5];`

```
void OnSelect()
{
    person.transform.position = Vector3.Lerp(person.transform.position, point, seconds * Time.deltaTime);
}

// Update is called once per frame
void Update()
{
    if (Physics.RaycastNonAlloc(Camera.main.transform.position, Camera.main.transform.forward, rayHit, Mathf.Infinity, ~0) > 0)
    {

        foreach (RaycastHit hit in rayHit)
        {

            point.x = Mathf.Clamp(hit.point.x, -290f, 6970f);
            point.y = Mathf.Clamp(hit.point.y, -40f, 1860f);
            point.z = Mathf.Clamp(hit.point.z, -1700f, 140f);
        }
    }

}
}`

```

Scene.cs
`using UnityEngine; using UnityEngine.XR.WSA.Input; public class Scene : MonoBehaviour`

{

```
public GameObject cursor;
public GameObject Focused { get; private set; }
public Scene Instance { get; private set; }

private GestureRecognizer recognizer;
private MeshRenderer Renderer;
private readonly RaycastHit[] rayHit = new RaycastHit[5];

void Awake()
{
    Instance = this;
    recognizer = new GestureRecognizer();
    recognizer.Tapped += (args) =>
    {
        if (Focused != null)
        {
            Focused.SendMessageUpwards("OnSelect", SendMessageOptions.DontRequireReceiver);
        }

    };
    recognizer.StartCapturingGestures();
    Renderer = cursor.GetComponent<MeshRenderer>();
}

void Update()
{
    GameObject oldFocused = Focused;

    if (Physics.RaycastNonAlloc(Camera.main.transform.position,Camera.main.transform.forward,rayHit,Mathf.Infinity,~0)>0)
    {
        Renderer.enabled = true;
        foreach ( RaycastHit hit in rayHit)
        {

            cursor.transform.position = hit.point;
            cursor.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
            Focused = hit.collider.gameObject;
        }
    }

    else
    {
        Focused = null;
        Renderer.enabled = false;
    }
    if (Focused != oldFocused)
    {
        recognizer.CancelGestures();
        recognizer.StartCapturingGestures();
    }
}

```

}

# Answer
Your camera has 0 fov in the second image which is why it isn't rendering anything.

You may not have the project set up properly to use XR for the Hololens/Windows Mixed Reality as Unity sets the fov automatically for the device. (Source) Try checking that.

I suggest also to use either the Holotoolkit or the MixedRealityToolkit from the Github page. (Both exist in the Releases)

You can also follow the setup without the Toolkit on the MSDN page.
> 1 votes

---
Tags: unity, c#, augmented-reality, hololens
---


# Question
Title: Unity smooth local rotation around one Axis, oriented toward a target
I want to acheive the same rotation you see in the inspector. In short: a smooth local Y rotation, toward a target

I have a Vector3 orientation: `Vector3 dirOrientation = targetToLook.position - movingCamera.position;`

So, every Update, what should I do ? I try many thing, but I don't realy understand Quaternion...

I just want to rotate localy in Y, toward a precise moving target, NOT in X or Z. and smoothly with some Lerp or Slerp.

Thanks !

# Answer
> 1 votes
Using the trick discussed in a similar question here and also here, we can define a helper method to point our local Y axis exactly in a particular direction, while turning our local Z axis to face (as close as possible) toward another direction.

```
Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp)
{
    Quaternion rotateZToUp = Quaternion.LookRotation(exactUp, -approximateForward);
    Quaternion rotateYToZ = Quaternion.Euler(90f, 0f, 0f);

    return rotateZToUp * rotateYToZ;
}

```

Now we can use that in Update to face toward our target:

```
void Update() {
    // Form the direction we want to look towards
    Vector3 offsetToTarget = target.position - transform.position;

    // Preserve our current up direction
    // (or you could calculate this as the direction away from the planet's center)
    Vector3 up = transform.up;

    // Form a rotation facing the desired direction while keeping our
    // local up vector exactly matching the current up direction.
    Quaternion desiredOrientation = TurretLookRotation(offsetToTarget, up);

    // Move toward that rotation at a controlled, even speed regardless of framerate.
    transform.rotation = Quaternion.RotateTowards(
                            transform.rotation,
                            desiredOrientation,
                            maxDegreesPerSecond * Time.deltaTime
                         );

}

```

---
Tags: c#, rotation, quaternion
---


# Question
Title: IndexOutOfRangeException on array of transform prefabs in Unity
I have a public array of length 9 containing prefabs I'm using as position references for a moving object. The start function finds the transform.position of the appropriate transform in the array and makes it the target for a Vector3.MoveTowards() function that is called every update. I have an exception for the start function, but the object moves fine. If I print the length of the array on every update, It shows zero every other frame, and 9 otherwise. There's nothing in the script changing the array, how is this happening?

I'm using the Linux build of Unity.

# Answer
> 0 votes
It sounds like you have a second copy of your script in your scene somewhere, with the array unpopulated.

Each frame, the correctly-configured instance prints a length of 9, and the incorrectly-configured instance prints a length of 0, making it look like you have alternation from frame to frame, when it's really coming from two different instances in the same frame.

Try Debug.Logging the name of your object and its path in the hierarchy in Start() (before the exception) - I bet you'll get two lines printing: one for the correctly-configured object, and one for the accidental dupe, helping you track it down and delete it.

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


title: synchronise two coordinate planes

text:
# Question
Title: synchronise two coordinate planes
So i have two coordinate planes. One is player and mouse click position relative to player. Other is the world map.

I need to find the point on the world map, where the mouse clicks.

The map is generated from a 64\*64 heightmap, so for now i want to find the mouse click inside the 64\*64 bounds.

Im having trouble determining the coordinates at the world map, where the mouse clicked.

The map has a multiplier of 10. Im not really sure how it is applied, but when it is 10, the world map is in bounds -10,-10 to 10, 10. When it is 20, it is in -20,-20 to 20, 20, when 50 then in -50,-50 to 50,50. Those are click coordinates in relation to player.

To get the world vertex i need to supply a coordinate (0-63, 0-63).

How do i transform the mouse click coordinates so that they are aproppriate to the world map?

# Answer
This looks like simple multiplication & division, no?

```
float2 mapHalfExtents = new float2(10.0f, 10.0f);
int2 mapVertexCount = new int2(64, 64);

int2 GetClosestVertexCoordinates(float2 clickedWorldPoint) {
    // Reduce to the range -0.5...0.5
    float2 normalizedPosition = clickedWorldPoint / (2.0f * mapHalfExtents);

    // Shift to 0...1 (placing the bottom-left corner at the origin)
    normalizedPosition += new float2(0.5f, 0.5f);

    // Map to the range 0...64
    float2 mapSpace = normalizedPosition * mapVertexCount;

    return RoundToInt2(mapSpace);
}

```
> 1 votes

---
Tags: 3d
---


title: Unity prefab from multiple sprites

text:
# Question
Title: Unity prefab from multiple sprites
I am making a prefab of a simple building by combining sprites. As you can see in the Hierarchy view, this simple building is composed of very many gameobjects which I created via dragging sprites into the scene/Hierarchy and then manually editing their coordinate positions.

Is there a simpler way of doing this? I feel that the process of creating this building consumed too much time I could spend on other aspects of development. If this is the only way, then in what ways could I optimize my workflow?

# Answer
> 1 votes
Inside of the grid that you already have, create a new tilemap and call it 'Building'. Then create the building using tiles, and when you're done, just make a prefab out of that tilemap.

# Answer
> 1 votes
You could have used texture tiling from a mesh renderer to duplicate pieces automatically. 3D components can be used for 2D objects to add more complex functionality.Drag and drop the sprite you want to duplicate as a material in the parent game object and change the shader to 'unlit texture.' You can play with the offset and tiling settings. Make sure the wrap mode in your import settings is set to 'repeat.'

You could have done this even faster by using gimp for the editing. Gimp has built in functions and plugins that handle this use case well. Filters \> Map \> Tile is one.

---
Tags: unity, 2d, sprites
---


# Question
Title: If I want to become a professional game developer, is learning Win32 API a must?
If I want to become a game developer, is learning Win32 API a must?

Does X-BOX or PS based game developers need to know Win32 API?

Is it possible for a professional game developer to develop games by only scripting game engines and not using Win32 API?

# Answer
No.

Consider that many, many games are now made for and sold on platforms that don't even have the Win32 API; I doubt many Android or iOS game developers have a daily need for Win32. But even if you work on a PC/XBOX only title, chances are you will be using multiplatform middleware or your company's game engine and someone else has already done the Win32 programming. The likelihood of a new developer needing to do much beyond a bit of maintenance of Win32 code is pretty low.

In general learning APIs for their own sake is not a productive endeavor. You're much better off learning concepts and fundamentals, then when you need to do something on a specific platform you don't start reading the API documentation like you're starting over from nothing, you find the APIs that do what you already know you need to do. There are a few exceptions to this like learning sockets, as that API is basically a de-facto standard if you need to do that sort of thing on any platform, so knowing anything about networking (at least lowish level) implies knowing how to use sockets. OpenGL is close as well, as it is the graphics API for mobile and WebGL is gaining some steam, although knowing the fundamentals is still most important.
> 1 votes

# Answer
The Win32 API is not a must. Professional games can be developed in anything from AGS to Flash to XNA to low-level C++. The Win32 API is only used for some Windows games, and not at all on non-Windows systems.

I will note, however, that a skilled general-purpose game developer would be able to pick up the Win32 API and learn how to use it if it was the best tool for the job. I wouldn't pick Win32 as the introduction for a new game developer, but it can be a useful tool and isn't fundamentally different than any other API. I find its naming conventions and way of doing business irritating, but I know that I can use it if I feel the need.
> 11 votes

# Answer
The vast majority of game devs I've worked with have had only a passing knowledge of Win32 at best.

Only a teeny tiny fraction of a game's codebase is going to use any platform-specific APIs in general, and unless you're the engine dev who's writing the abstraction layers for those, you can get away without knowing anything about Win32.

Most indie games even just use a simple Win32 message loop (which you can practically cut and paste from Microsoft's documentation) or use an existing abstraction library like SDL or SFML.
> 4 votes

# Answer
Win32 API is simply an interface one uses to natively hook up one's game into the infrastructure of Windows. Managing the application handler, creating windows pertaining to your application/game and registering with the system.

This is what most indie game developers deem as boilerplate code, the bare minimum that has to be done on a specific platform in order to get your **relevant code** up and running. After you've done that, your code becomes game specific. Mostly you won't tie into Win32 for your GUI needs because you'll have something of your own cooked up. Or perhaps, someone else's solution.

While knowledge of Win32 is useful if you wish to write some hardcore native tools that will wrap around your game engine's content editing environment, you'll most likely find indie developers coding wrappers in a more forthcoming environment, like .NET's C# which makes Windows GUI development a breeze. But that will make your code on Windows dependent on .NET frameworks which forces users to download it, so if that irritates you, you might run back to Win32 and doing a little bit more boilerplate code in return for which you'll gain some *sweet nativeness*.

It is logical to keep your game code (and that includes everything, from low-level rendering to high-level game logic) separated from platform-specific code. That will open porting opportunities and many other sweet things. Not to mention the ease of development which comes from abstracting away the boilerplate and concentrating on what matters - **the game**.

In that respect, many choose SDL (and thus OpenGL) to do their boilerplate. And some simply enjoy the challenge of extended understanding and getting the most out of every platform. Remember, the easier it gets, the more conformed you are to a given platform.

*"By using the technology of the mass relays, your society develops along the paths we desire"* \- Sovereign, Mass Effect

Applies here. So, it is not mandatory to know Win32. But it's nice. However, with today's many platforms and available runtime-managed solutions which tie in with OS-included tools for application development, it would be a shame not to utilize the offerings.
> 2 votes

# Answer
No

The Win32 API is simply an interface, it is not that much required for becoming a game developer. Having knowledge of Win32 is also useful.
> -2 votes

---
Tags: career, winapi
---


# Question
Title: Rotation Problem in Mario galaxy like controller
i'm doing a Mario galaxy like CCC. And I have a serious rotation problem, may be Gimble lock, or maybe not.

So first, I have a parent object ("**PLAYER**") who can rotate toward a planet: https://youtu.be/j3VkemYQTa8

With this 3 line:

```
Vector3 dirOrientation = GetNormal() //here the normal collision
Quaternion targetRotation = Quaternion.FromToRotation(PLAYER.transform.up, dirOrientation) * PLAYER.transform.rotation;
PLAYER.transform.rotation = Quaternion.RotateTowards(PLAYER.transform.rotation, targetRotation, speedRotate);

```

Ok, next, I want to rotate the child object ("**CHILDPLAYER**"), who contain the render, according to the input of the player See in editor: https://youtu.be/4Sb8t82OT-E

So here... I managed to get the direction of the input, according to the camera. See in blue, the directionnal line: the Vector3 point to the good direction according to the player and the camera, yes ! https://youtu.be/4TvPsXp-W9U

```
Vector2 dirInput = playerInput.GetDirInput();//input player with the stick, X,Y
//here REFOBJECT is the camera (who dictate the "forward" of the player
Vector3 relativeDirection = REFOBJECT.right * dirInput.x + REFOBJECT .forward * dirInput.y;
Debug.DrawRay(CHILDPLAYER.position, relativeDirection, Color.cyan, 0.4f);

```

But now... As you see even if I have the good direction (cf blue line in the vidéo). I can't manage to rotate the child gameObject accordingly... I have to localy rotate smoothly the **CHILDPLAYER** only in Y toward my new calculated vector...

Here the code I use to rotate the **CHILDPLAYER**, with my **relativeDirection** Vector3:

```
CHILDPLAYER.localRotation = DirObject(CHILDPLAYER.localRotation, relativeDirection, turnRate);

public Quaternion DirObject(Quaternion rotation, Vector3 dir, float turnRate)
    {
        float heading = Mathf.Atan2(-dir.x * turnRate * Time.deltaTime, dir.z * turnRate * Time.deltaTime);

        Quaternion _targetRotation = Quaternion.identity;

        float x = 0;
        float y = heading * -1 * Mathf.Rad2Deg;
        float z = 0;

        _targetRotation = Quaternion.Euler(x, y, z);
        rotation = Quaternion.RotateTowards(rotation, _targetRotation, turnRate * Time.deltaTime);
        return (rotation);
    }

```

See the final result: https://youtu.be/lSQQFDDuj7U Here, I'm going ALWAYS DOWN with the stick... and even if the direction calculated in relativeDirection is good, the child player rotate itself... ...

# Answer
Thanks yo @DMGregory, here is the answers: Unity smooth local rotation around one Axis, oriented toward a target

Sorry for the duplicate, I thought this was 2 separate problem. It was not.
> 0 votes

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


# Question
Title: Move a point to another, along an elipse
according to this picture, I want to move my **yellow** object, *smoothly* to the **red** one. And I want to have an eliptic trajectory in relation to my **center point**.

So for now I'm having this code:

```
yellowPoint.position = Vector3.SmoothDamp(yellowPoint.position, redPoint.position, ref currentVelocity, dampingMove);

```

How can I change it to add the elipse, depending on a third center point ? the itinial code can change of course.

Thanks you !

# Answer
> 2 votes
There are multiple ways to do that, depending on what kind of curve you want.

For example **bezier curves**:

The logic behind them is that, you take three points that define your curve. The first point is the beginning of the curve, and the last one is the end of the curve. The other is a "control point" meant to give the curve its shape.

To calculate this, you need to be familiar with a function like `Lerp`, which is used to find a point that lies between two other points. Following that, you end up with this:

```
// The points of the curve
Vector3 P0, P1, P2;

// time going from 0.0f to 1.0f
float t;

Vector3 pointInCurve =
    Vector3.Lerp(Vector3.Lerp(P0, P1, t), Vector3.Lerp(P1, P2, t), t);

```

The logic behind it is: Assuming you have a variable `t` that says at which position on the curve you currently are, find the point between `P0` and `P1`, depending on `t`, so that in the beginning it's closer to `t` (so closer to `P0`) and as time passes, it goes closer to `1` (so closer to `P1`). Do the same for another point that goes from `P1` to `P2`. These are the two green points illustrated on the gif.

Then do the exact same thing, for finding your desired point, which is now between the two green points. The result is the black dot on the gif, following the red curve/path.

You can follow the same logic to do quadratic bezier curves:

Just take 4 points instead of 3, calculate all the in-between points, until you end up with 3 new points, which then you can treat as a regular bezier curve and follow the steps above. In fact this way you can have as many points as you want.

There's also the **Catmull-Rom** curves:

They follow a similar logic, they have 4 points, but here the path travels from the second to the third point, using the first and last as control points. I've used this one before to simulate a "path" a flying creature is following, as when it reaches the end of that curve, you can create a new curve using points 2, 3 and 4, and generate one last point towards the direction that you want, so the path is smooth.

Unfortunately my familiarity with how these curves work behind the scenes is limited, but you can read more about them in Wikipedia - Centripetal Catmull–Rom spline.

Once you get the hang of how curves work, you can experiment with how fast `t` is updated to create effects like in easings.net.

---
Tags: unity, mathematics, rotation, quaternion
---


# Question
Title: Transfer mouse movements to a GameObject in 3D according to camera position and rotation
I'd like the game object to follow the mouse but I have trouble doing this when the object is in 3D and the camera has been rotated.

The only thing that seems to be true (and still it works only when camera isn't rotated) is :

* The visible X for the camera is equal to `2 * Mathf.Abs(object.position.z - camera.position.z)`
* The visible Y for the camera is equal to `VisibleX * (camera.pixelHeight / (float)camera.pixelWidth)` (casting to `float` to avoid `int` divided by `int` returning an `int`)

# Answer
> 1 votes
If you want an object to snap to the mouse position while keeping the same depth in front of the camera, you can use the ScreenToWorldPoint convenience method:

```
// Capture the position of the mouse on screen/window,
// measured in pixels from the bottom-left corner.
Vector3 screenPosition = Input.mousePosition;

// Track the current depth of the object in front of the camera.
// (You could also set this to some fixed constant or stored variable)
screenPosition.z = Vector3.Dot(
                     object.transform.position - camera.transform.position,
                     camera.transform.forward
                   );

// Transform this screen position to a world position,
// using the camera's transformation & projection/viewport settings.
Vector3 worldPosition = camera.ScreenToWorldPoint(screenPosition);

// Snap the object to this position.
object.transform.position = worldPosition;

```

---
Tags: unity, c#, 3d, camera, mouse
---


# Question
Title: How to know the adresses an editor modifies while saving a file
I hope this question belongs here.

Suppose an editor for a specific file extension. It usually has a user friendly interface so you don't see raw data. Once you edit anything and save the editor modifies some data. Is there any way to keep track of these changes and see which specific data is modified? This is motivated by the fact that an editor is a program that has its limitations and sometimes it does not allow some changes. This protects the original file from fatal damage. As an example suppose a .nes file that can be edited through the HEX editor or a "level" editor. I might not know the ROM address where some level information is stored but (i guess) the "level" editor knows. So I can edit, save and search the region of the ROM, with the HEX editor, that was modified. That would give me information on where this level data is stored and be able to understand it.

My system is Windows so I wonder if there is any "save register" that keeps track of this save operations. Or is it an editor specific thing and each one has its own way of saving data, meaning i should look into the editor's code more than a general Windows place?

Thanks,

PD: I'm sorry if I misunderstood something essential but I'm not experienced with how this precesses work.

# Answer
You can look at the date modified stamp on files to figure out which ones have recently been written to. Windows's search features will let you search a group of folders to find all files modified within a time span you choose.

Once you know which file(s) were written to, you can save a copy of them elsewhere. The next time you modify those files with your editor, use a diff tool to compare the pre-modification versions you saved elsewhere against the current versions. This will identify the particular parts that changed (though if the files are in an unknown binary format, or compressed or encrypted, the results might not be very informative).

Now that you know, please use your powers only for good, to make awesome games and mods, not to cheat or rip off other developers' hard work. ;)
> 1 votes

---
Tags: modding, debugging, editors, roms
---


# Question
Title: The character does not stand still on the moving platform
I'm trying to create a simple platforming game. I have an animated platform moving in 2 opposite directions. I use this simple code to make the character move along with the platform while he is standing on it:

```
public class PlatformMoving : MonoBehaviour
{
    private void OnTriggerEnter(Collider other) => other.transform.parent = transform;

    private void OnTriggerExit(Collider other) => other.transform.parent = null;
}

```

The character moves with `CharacterController.Move()`. When he stands still on the platform and movement vector equals to `Vector3.zero`, he moves in the direction opposite to the platform movement direction and can even fall down from the platform. But if I comment `charController.Move(movement)` line in a character motion script, everything works properly and the character does not move when he shouldn't do that. How to solve it?

# Answer
> 3 votes
Welcome to the game developers hub, @**zergon321**!

Eventough, I've answered your question in comments, other people might be interested as well, so I'm putting the answer over here.

# The answer

Try checking if there's any movement input before applying it with `CharacterController`. So for example:

```
if(movement != Vector3.zero)
    charController.Move(movement);

```

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


# Question
Title: Diagonal movement is faster than horizontal or vertical movement. How to fix?
When using Horizontal or Vertical input keys, the the movement is normal. But when trying to move diagonal, multiple keys are to be pressed, and the speed just stacks up.

Yes there are many answers to such questions. But I'm having a hard time figuring out a solution. I am actually using an asset, and the code is kinda hard to understand for me. The script is on my drive and the link is below: https://drive.google.com/open?id=1Lt4DZBw7Jv2LNyYR-03aNUpV2a29F7dm

Please provide a solution. I am not so good at coding. And I'm in real need to make that game because of many reasons as fast as I can so I will learn all coding later. (and in the script please search for Move, Movement or related words to go to specific movement code, thank you a lot)

# Answer
> 0 votes
Try setting velocity to your desired velocity if both left and up (or right and down, etc) are pressed at the same time. That should do it.

# Answer
> 0 votes
If Unity3D:

```
this._inputs = Vector3.zero;
this._inputs.x = Input.GetAxis("Horizontal");
this._inputs.z = Input.GetAxis("Vertical");
if(this._inputs.magnitude > 1)
  this._inputs = this._inputs.normalized;

```

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


title: PyGame - Top down shooter mechanics

text:
# Question
Title: PyGame - Top down shooter mechanics
I'm currently developing a game for some school work using the PyGame library for Python. I'm almost done with most of the game's core mechanics, but have gotten hung up on the shooting mechanics. My current code is too long to post fully, but I'll put excerpts of it and explain what I have so far.

```
all_sprites_list = pygame.sprite.Group()

bullets = []
bullet_list = pygame.sprite.Group()
bullet_speed = 10

class Bullet(pygame.sprite.Sprite):
def __init__(self):
    super().__init__()

    self.image = pygame.Surface([4,10])
    self.image.fill(red)
    self.rect = self.image.get_rect()

def update(self):
    if self.rect.x > chx:
        self.rect.x -= bullet_speed
    elif self.rect.x < chx:
        self.rect.x += bullet_speed
    if self.rect.y > chy:
        self.rect.y -= bullet_speed
    elif self.rect.y < chy:
        self.rect.y += bullet_speed

```

This code shows the class I have for my bullets and their movement. The problems with this right now are that A) the bullets get stuck around the crosshair position, of which the `chx` and `chy` variables show the x and y position of the mouse.

```
    if event.type == pygame.MOUSEBUTTONDOWN:
        bullet = Bullet()
        if weapon == "hg" and hg_move == True:
            bullet.rect.x = hgrect.x
            bullet.rect.y = hgrect.y
            all_sprites_list.add(bullet)
            bullet_list.add(bullet)

```

This code shows an example of one of the firing commands later in the main game loop. `hg`, `hg_move`, and `hgrect.x/y` are all variables used for the movement of the character depending on the type of weapon he is holding.

Some of the main issues are seemingly caused by the fact that I can't find a way store a static value of the likes of the crosshair positions, or to keep the bullets going on a trajectory until they leave the screen or hit an object.

Any help would be greatly appreciated!

# Answer
> 1 votes
You will need to fix your update method and add some variables to your Bullet class:

# Bullet Class

class Bullet(pygame.sprite.Sprite):
   def __init__(self, vx, vy):
       super().__init__()

       self.image = pygame.Surface([4,10])
       self.image.fill(red)
       self.rect = self.image.get_rect()
       self.velocity_x = vx
       self.velocity_y = vy

   def update(self):
       self.rect.x += self.velocity_x
       self.rect.y += self.velocity_y

# Spawning the Bullet

# 1. You need to determine the direction from the player to the crosshair

# X distance from player to crosshair
dx = (chx - hgrect.x)
# Y distance from player to crosshair
dy = (chy - hgrect.y)
# Direction from player to crosshair in radians
dir = math.atan2(dy, dx)

# 2. Calculate a velocity vector with a given speed and the direction above
speed = 20 # units: pixels/update
vx = speed * math.cos(dir)
vy = speed * math.sin(dir)

# 3. Create the bullet with the calculated X and Y velocity
bullet = new Bullet(vx, vy)
```

---
Tags: python, pygame, shooter
---


# Question
Title: How to convert coordinates between world coordinates and screen coordinates
I am using a tilemap in which I have square tiles.
Knowing that, the size of the screen and the player position(in world coordinates) how I convert between this systems? Is there any formula?

EDIT:
For example:
The top left corner is (0,0)
**player position in tiles:** (ScreenX / 2, ScreenY / 2)
**player position in screen:** always (0, 0)
**grass tile position in tiles:** (Gx, Gy)

Now the question is: how can I get the screen coordinates for the grass tile?

# Answer
> 1 votes
If your grass tile's position in the tilemap is `<Gx,Gy>` then its pixel position in the game world will be:

```
tile_worldX = Gx * Tile_Size
tile_worldY = Gy * Tile_Size

```

Then you subtract the position of the screen's top-left corner from these coordinates to get their on-screen pixel position:

```
tile_screenX = tile_worldX - view_x
tile_screenY = tile_worldY - view_y

```

This assumes that the screen's top-left corner is 0,0 in your viewport. Sometimes game engines will move 0,0 to the middle or bottom-left of the viewport so you may have to compensate for that difference.

---
Tags: python, pygame, coordinates
---


# Question
Title: How to convert RotateAround speed to directional speed in Unity?
I am currently using

```
transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond * Time.deltaTime)

```

to make an object rotate around another object. This works well, but I want to make the object stop rotating around and instead move in a certain direction at the same speed that it was rotating. However, I can not figure out how to convert the `degreesPerSecond` into a directional speed.

My goal is to have something like this:

```
if(rotating) {
    transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond * Time.deltaTime)
} else {
    transform.position += transform.right * DegreesToDirectionalSpeed(degreesPerSecond ) * Time.deltaTime;
}

float DegreesToDirectionalSpeed(int degrees) {
    // Code that I don't know goes here
}

```

Any tips on how to achieve this?

# Answer
> 2 votes
Romen's answer is correct regarding the physics concepts involved.

In terms of implementation in Unity, you can do it like this:

```
Transform center;
float degreesPerSecond;
Vector3 axis = Vector3.forward;
bool hasReleased;
Vector3 releaseVelocity;

// Call this when you want to let the sling loose to fly in a straight line.
public void Release() {
    Vector3 offsetFromCenter = transform.position - center.position;
    float radius = offsetFromCenter.magnitude;

    Vector3 travelDirection = Vector3.Cross(axis, offsetFromCenter).normalized;

    releaseVelocity = radius * degreesPerSecond * Mathf.Deg2Rad * travelDirection;

    hasReleased = true;
}

void Update() {
    if(!hasReleased) {
        transform.RotateAround(center.position, axis, degreesPerSecond * Time.deltaTime);
    } else {
        transform.Translate(releaseVelocity * Time.deltaTime, Space.World);
    }
}

```

# Answer
> 1 votes
You are looking for something called the tangential velocity vector.

A point on a rotating object at **r** distance away from the center of rotation will be moving a speed equal to **r** * **ω**
Where **ω** is the angular velocity of the object in radians per second.

If you can determine the distance between the entity and the point it is rotating around you simply multiply the angular speed by that distance.
Note that this only calculates the speed of the object, its direction will be determined by the tangent to the circle at that point.

An explanation of angular velocity can be found here:
http://hyperphysics.phy-astr.gsu.edu/hbase/rotq.html

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


# Question
Title: Is there a quick way to determine if a vector is in a quadrant?
I am wondering if there is a quick easy way to determine if a given vector is in a specified quadrant.

In the below image, I've define the ranges of the blue quadrants.

For example, if I am given a sample vector of -9.4,13.3 is there an easy way to figure out which of the four quadrants it is in (Q2)?

I'm looking to know if there is some vector math that can determine this relatively simply instead of doing a bunch of less than / greater than operators on a fixed range.

Considering that I could have more or less than 4 quadrants and they might not be at this nice 45 degree angle.

# Answer
In this case, what is wrong with comparisons? It's (in this case) pretty easy, just

```
if(abs(x) > abs(y)
  if(x > 0) q = "q2"; else q = "q4";
else
  if(y > 0) q = "q1"; else q = "q3";

```

Alternatively, you could do something like (hopefully I'll get this right)

```
angle = atan2(y, x);
angle -= pi/4; // now (0,pi/2) is all Q1
quadrant = angle / (pi/2);
if(quadrant < 0) quadrant += 4;
quadrant++; // to make it 1 to 4. (not quite right for the numbering, but...)

```

This can be generalized for any evenly-spaced wedges. (They can be called "quadrants" when there's four of them.)

If the wedges aren't evenly spaced, you could still have a list of their angles, calculated when they change, also with atan2. Then it becomes a search problem, given the angle from the origin for a point of interest versus the wedge list. For a small number of wedges, a linear search is probably fine. If you have dozens, or thousands, a binary search might be nicer.

If it must be inside the circle, check the distance to origin first... Is there a reason it must be done "in vector math"?
> 4 votes

# Answer
This is inspired by how OpenGL handles Cubemaps:

(Pseudocode)

```
vector = normalize(vector);
if(abs(vector.x) > abs(vector.y)){
  if(vector.x < 0)
    //Q1
  else
    //Q3
}else{
  if(vector.y < 0)
    //Q4
  else
    //Q2
}

```

(i hope you don't count this as "a bunch") Another way would be to calculate the angle which would involve a arctan and that should be a lot slower than my approach.
> 0 votes

# Answer
Yes.

First calculate the matrix for the transformation that maps your custom quadrants to the standard quadrants numbering CCW from +ve X and +ve Y.

Second apply this matrix to the point of interest (call it (x,y)) to get a mapped point in standard quadrant space (x',y'):.

Now apply this formula to the resulting vector (x',y'):

```
Quadrant = 1 + (1 - sign(y')) - ( sign(y') (1 - sign(x') ) / 2

```
> 0 votes

# Answer
If the sectors are of equal size then one approach would be to calculate the angle, divide by a full rotation and then multiply by the number or sectors:

```
rad = atan2(x, y)
normalised_angle = rad / (2 * pi)
sector = (int)(normalised_angle * sector_count)

```

For the example given in the question we would also require a `π/4` offset to account for a quadrant straddling the zero angle. This offset also requires wrapping the angle value to ensure that it remains between `0` and

```
sector_count = 4
offset =  pi / 4

rad = atan2(x, y) + offset

while (rad < 0):
    rad += 2 * pi
while (rad > 2 * pi):
    rad -= 2 * pi

normalised_angle = rad / (2 * pi)
sector = (int)(normalised_angle * sector_count)

```
> 0 votes

# Answer
Yes, you can perform simple binary search on region divisor vectors.
If you pre-process and sort your divisors ccw(and you probably should), it is sublinear *log(n)* complexity for *n* regions (oposed to other answers with linear complexity), moreover it doesnt rely on inaccurate and slow functions like `atan`, in addition your regions does not need to be quadrants or evenly spaced, it works for any number of any regions.
All you need is to determine if queried vecor lies to left or to right to the tested divisor(that is one vector operation) and apply this greater/lesser logic on same binary search like you already know. Code example(not tested):

```
Divisor findRegion(vec2 query_vec) {
return *(std::lower_bound(divisors.begin(), divisors.end(), query_vec, isLeft));
}

```

*Please note you might need to implement additional logic if you allow regions greater than `pi`, but I assume you need use this for more smaller regions*
> 0 votes

# Answer
Quadrant(1,2,3,4)=4-(1+sign(x))\* (1-sign(y^2))-(2-sign(y))\* (1-sign(x^2))

```
       -sign(x^2*y^2)*((1+sign(abs(x)-abs(y)))*(1+sign(x))/2

                      +(1-sign(abs(x)-abs(y)))*(1-sign(y)/2))

```
> -1 votes

---
Tags: mathematics, vector
---


# Question
Title: Running OpenGL app on Windows XP x86 produces incorrect texture colors
I'm working with the Cen64 emulator and I compiled from source a x86 version that operates fine on Windows 10 x64. As soon as I run it on a Windows XP x86 machine the colors are then all incorrect. Here are some screenshots:

Running on Win 10  Running on Win XP SP3
The color format is set to GL\_UNSIGNED\_SHORT\_5\_5\_5\_1 and the internal format is GL\_RGBA:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, hres + hskip, vres,
    0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, buffer);

```

I'm pretty new to configuring color packing formats but it appears like some color channels are getting swapped? Maybe some sort of endianness issue going from an x64 to an x86 architecture?

Please let me know if I need to show more of my code to help debug the issue. Thanks for any help! ^\_^

# Answer
Got the issue finally sorted. I'm probably wrong but I think there's a bug in my old OpenGL 2.1 driver that is not setting the byte swapping for the frame buffer: https://github.com/n64dev/cen64/blob/b27960c94f9f4d5997fc2b64a76fb30e79b13be4/vi/render.c#L46

I fixed by just manually rolling my own byte swapper and now all is good! ^\_^ https://github.com/deadcast2/cen64/blob/cd8ae9c48a150d0b9121d4c38a82ea019680b4f4/vi/controller.c#L135

```
// Do a manual byte swap since a bug in opengl 2.1 driver
uint8_t *frame_buffer = vi->window->frame_buffer;
for (size_t i = 0; i < copy_size; i += 2) {
  uint16_t color = frame_buffer[i] | (frame_buffer[i + 1] << 8);
  frame_buffer[i] = color >> 8;
  frame_buffer[i + 1] = color;
}

```

Happy pipe now :D
> 1 votes

---
Tags: opengl, textures, rendering, graphics, color
---


title: Getting AABB Collision to work - C++

text:
# Question
Title: Getting AABB Collision to work - C++
I've been trying for weeks to get AABB collision set up on my DX11 project.

So far, I have a 'condition' set up in place, so that when both cubes collide the 'light' cube will show within the scene. At this moment, the cubes pass through each other, which causes the light to show, but I can't figure out how to actually stop them from passing through each other. When cube1 hits cube2, they'll simply collide and won't be able to pass through each other.

This manages the user input

```
//Manage the users input via keyboard
class Vector3 {
public:
    float x;
    float y;
    float z;
};

class UserInput
{
public:
    float xPos;
    float yPos;
    float zPos;
    Vector3 vecMin;
    Vector3 vecMax;
    float rotationX;
    float rotationY;
    float rotationZ;
    bool isMoving;
    bool isMovingRight;
    bool isMovingLeft;
    bool isMovingUp;
    bool isMovingDown;
    bool isMovingCloser;
    bool isMovingFurther;
    bool isRotatingX;
    bool isRotatingY;
    bool isRotatingZ;
    UserInput()
    {
        rotationX = 0.0f;
        rotationY = 0.0f;
        rotationZ = 0.0f;
        isMovingRight = false;
        isMovingLeft = false;
        isMovingUp = false;
        isMovingDown = false;
        isMovingCloser = false;
        isMovingFurther = false;
        isRotatingX = false;
        isRotatingY = false;
        isRotatingZ = false;
    }

    void UpdatePos()
    {
        //-1 and +1 from the origin of the cube (centre)
        vecMin.x = xPos - 1.0f;
        vecMax.x = xPos + 1.0f;
        vecMin.y = yPos - 1.0f;
        vecMax.y = yPos + 1.0f;
        vecMin.z = zPos - 1.0f;
        vecMax.z = zPos + 1.0f;
    }
};

```

AABB Collision Function

```
bool AABBtoAABB(const UserInput& box1, const UserInput& box2)
{
    return!(box1.vecMin.x > box2.vecMax.x ||
        box1.vecMax.x < box2.vecMin.x ||
        box1.vecMax.y < box2.vecMin.y ||
        box1.vecMin.y > box2.vecMax.y ||
        box1.vecMin.z > box2.vecMax.z ||
        box1.vecMax.z < box2.vecMin.z);
}

```

Update Function

```
//Update each Frame
void Update()
{
    AABBtoAABB(input[0], input[1]);
    input[0].UpdatePos();
    input[1].UpdatePos();
}

```

# Answer
> 1 votes
Give the objects a velocity. Set the velocity to zero on each axis if there would be a collision in that place.

```
// Object
velocity.x = 4
velocity.y = 2

if is_collision(velocity.x, 0, other) velocity.x = 0
x += velocity.x

if is_collision(0, velocity.y, other) velocity.y = 0
y += velocity.y

// Collision function
is_collision(offset.x, offset.y, other)

```

---
Tags: c++, directx
---


# Question
Title: Difference between two perspective projection representations
When researching perspective projections on the web, I've come across two different representations. One is unrelated to OpenGL and the other is strictly associated with it.

What is the relation of these two projections? Both are called the same but the matrices are quite different. The first one seems to project unto the xy plane (z=0), the OpenGL one to the z=near plane.

# Answer
> 2 votes
My knowledge in matrices is not that great, but from what I understand the first one refers to **Weak-Perspective Projection**. This is meant as a "simple" way to give the illusion of 3D. The only thing it does it to make the objects with big Z values appear smaller on the screen, so it divines both the X and Y with Z.

The second matrix is the standard matrix for perspective projection, where it transforms everything in the camera's frustum (depending on its near/far plane, and left/top/right/bottom values) to a cube extending from -1 to 1 in all dimensions. Usually after this transformation, vectors are again (like in Weak-Perspective Projection) divined by Z, but that is not part of this matrix.

The results from the Weak-Perspective Projection are not ideal. Maybe this picture can help understand why:

More information on both matrices on Wikipedia - 3D projection

---
Tags: opengl, mathematics, projection, perspective
---


# Question
Title: Pushing Rigidbody forward doesn't go straight
I have a object that pushing rigidbody forward when it's instantiated:

```
GameObject grenade = Instantiate(projectilePrefab, shootPoint.position, shootPoint.rotation);
grenade.GetComponent<Rigidbody>().velocity = transform.forward.normalized * 50;

```

It seems fine, but when I ran the game, projectile always not going straight and it's little bit moving left or right.

So I thought that shoot point wasn't pointing the right direction or my crosshair didn't centered properly, but unfortunately there were nothing wrong with them.

I think there's no extra forces that affects physics in my scene except gravity, and gravity has default settings which only affects downside. But why projectile doesn't go straight and move little bit left?

What am I missing?

# Answer
> 1 votes
As previously answered. If you spawn your projectile offset from the camera, and shoot it in the direction of a transform attached to the rifle then it won't line up with the camera because the rifle is not lined up with the camera

The way to solve this is to do one of the following:

A) Shoot the projectile from the camera.

B) Project the crosshair out from the rifle instead of the camera.

C) Force the rifle to line up with what the camera is looking at.

You'll find that most FPS games go with option A. Recently there have been a few games that do a combination of options B and C.

# Answer
> 2 votes
Those calculations you made are taking into account a direction that is forward of the camera center. But you are instanciating the grenade in an arbitrary transform called ShootPoint.

so how to actually aim with the camera and shoot toward that direction ? i guess that's your question.

```
GameObject grenade = Instantiate(projectilePrefab, shootPoint.position, shootPoint.rotation);
grenade.GetComponent<Rigidbody>().velocity = Camera.main.transform.forward.normalized * 50;

```

Not the cleanest and modular code out there as your grenade have a direct dependency on Camera.main but it should solve your aiming issues.

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


# Question
Title: How to arrange copies in circle that includes the cloned object not at the centre
I am using the editor code below to create copies of a game object in a circle with a given radius from the cloned object. The result is A in the image below, the cloned object at the centre with copies around. I want to achieve B, which has the game object (`CircleSpawn`) at the centre and the cloned object included in the copies that are created around the centre. The cloned object should be able to rotate and function in a way similar to it's copies. How can I fix my code to create this?

CircleSpawn

```
public class CircleSpawn : MonoBehaviour
{

public float radius, radiusLast, spin, spinLast;
public int numOfItems;
public GameObject clonedObject;
public List<GameObject> spawnedObjects;

}

```

CircleSpawnEditor

```
[CustomEditor(typeof(CircleSpawn))]
public class CircleSpawnEditor : Editor
{

public override void OnInspectorGUI()
{
    var tar = (CircleSpawn)target;
    tar.clonedObject = (GameObject)EditorGUILayout.ObjectField(tar.clonedObject,
        typeof(GameObject), true);
    if (!tar.clonedObject) return;

    EditorGUILayout.LabelField("Radius"); // Set as required
    tar.radius = EditorGUILayout.Slider(tar.radius, 0f, 5f);
    EditorGUILayout.LabelField("Angle"); // Set as required
    tar.spin = EditorGUILayout.Slider(tar.spin, 0f, 360f);
    EditorGUILayout.LabelField("Number of Items"); // Set as required
    tar.numOfItems = EditorGUILayout.IntSlider(tar.numOfItems, 0, 12);
    EditorGUILayout.LabelField("Object");

    float angle, angleBetween = 360.0f / tar.numOfItems;

    if (tar.spawnedObjects == null)
        tar.spawnedObjects = new List<GameObject>();

    if (tar.spawnedObjects.Count != tar.numOfItems)
    {
        foreach (var ob in tar.spawnedObjects)
            DestroyImmediate(ob);

        tar.spawnedObjects.Clear();
        angle = 0f;

        for (int i = 0; i < tar.numOfItems; i++)
        {
            var rot = Quaternion.Euler(0f, 0f, tar.spin + angle);
            var localPos = rot * Vector3.right * tar.radius;
            tar.spawnedObjects.Add(Instantiate(tar.clonedObject,
            tar.transform.position + localPos, rot));
            angle += angleBetween;

        }
    }

    if (!Mathf.Approximately(tar.spin, tar.spinLast) ||
        !Mathf.Approximately(tar.radius, tar.radiusLast))
    {
        tar.spinLast = tar.spin;
        tar.radiusLast = tar.radius;
        angle = 0f;

        for (int i = 0; i < tar.numOfItems; i++)
        {
            var rot = Quaternion.Euler(0f, 0f, tar.spin + angle);
            var localPos = rot * Vector3.right * tar.radius;
            tar.spawnedObjects[i].transform.position =
            tar.transform.position + localPos;
            tar.spawnedObjects[i].transform.rotation = rot;
            angle += angleBetween;

        }
    }
}
}

```

# Answer
> 1 votes
1. wow thanks for the code very interesting
2. As I understand it, you get version A because you add an object from the scene to the "clonedObject" field. You need to create a prefab of the target object and in the "clonedObject" field specify the prefab itself

---
Tags: unity
---


# Question
Title: How to detect syntax error in unity shader scripting
Hi. I'm following shader scripting tutorial and I often make syntax mistakes. like other languages, can you have visual studio automatically underline with red color?

# Answer
> 0 votes
Have you tried Shader Unity Support?

also you need to install parts of Visual Studio C/C++ for this to work

---
Tags: unity, shaders
---