# Question
Title: What dynamic range of numbers do games typically use?
Most of the numeric quantities used in games (aside from integers for counting or indexing objects) are single-precision floating point. This is IEEE format, which allows for numbers as big as 1e38 and as small as 1e-38.

Such a large dynamic range makes sense in the context in which the IEEE floating-point standard was defined: roughly speaking, for scientists, who routinely deal with very large and very small numbers.

Intuitively, games seem unlikely to have to deal with such a wide range. Say you measure distance in meters. Draw distance maybe a few kilometers? Smallest objects a few millimeters? Granted that multiplying numbers can temporarily take them out of the original range, it would seem sufficient to have a dynamic range like 1e8 to 1e-6, whereupon more of the bits could've been used for greater precision.

But maybe I am missing something about the data and calculations routinely used in games.

What sort of dynamic range do games actually use?

# Answer
> 1 votes
As games cover such a wide range of things, there is really no typical. However, for 3D worlds, greater scale is becoming more popular. Open worlds, for example, can cover any size you care to imagine.

Based on my experiments, if you want accuracy in the millimeters throughout, then with single precision, a world of about 70,000m is fine before you can start to notice some jitter.

Some math on this: single precision has a max mantissa value of 2^23-1, or 8,388,607. 70,000 / 8,388,607 is about 0.008m or 8mm. However, the resolution or error in 3D space is a 3D geometric formula, not the 1D calculation I just did.

If you factor in that the base error is a 3D geometric formula, the actual error is a factor of 3.4xdistance (ref geometric relative error) greater than what I calculated. I.E instead of 8mm accuracy the worst case accuracy much lower - probably in the centimetres to a meter.

Then if you do any calculations, the error is magnified by propagation. E.g. a multiply by 10 will make it 10x bigger.

The takeaway is that mm resolution is not achievable beyond 70km and most likely at a smaller range.

Practical proof: In the video: I demonstrate visible errors at the 70km range from distant relative jitter: Distant relative jitter (bookmark "Attempt to move to a point intersection". As I try to move to a point where two squares meet, the visible error would appear to be about 0.5 to a meter. The jitter at times appears to be less: in the cm range. The sliding motion demonstrates loss of resolution in at least one axis.

In contrast, at the bookmark: "At least mm accuracy when move to target" motion to target is smooth and accurate. This is because the design manages the resolution at that place by nesting a high-resolution virtual space within the World space.

# Answer
> 1 votes
I can give the game I'm working on as an example. It certainly does not fit "routinely used" being something of an outlier, but still might be illustrative as an example that the storage of the world doesn't need to be limited to what the graphics card can handle.

I'm working on a game set in a realistically scaled galaxy (10^18 km across, or even larger, and I also want to be able to fly outside it), with a unit scale of 10 km. For this, single precision floats or even double precision floats would have inadequate precision, and single precision floats are even problematic with dynamic range in intermediate calculations (I have overflowed them several times). My solution is that positions are stored as 64 bit integers, with 128 bit integers for some intermediate calculations.

The main target for this is Android. I can't assume the graphics card can handle anything bigger than single precision floats, so there is some juggling going on. One technique I use is to pass the graphics card offsets (as floats) from a particular point in space (the zero point), and occasionally re-center the zero point to be near the viewpoint to limit the distortion that would be caused by the zero point being far from the viewpoint. (This sort of distortion can be seen in Minecraft if you go very far from the start area).

I will also have to consider changing scales to something finer than a 10 km resolution for planets or moons when the viewpoint goes close to them.

---
Tags: models, data, floating-point
---


# Question
Title: How to stop player when they hit an axis aligned bounding box?
I'm in the process of creating a game using `electron` and `HTML5`. It's going to be a pretty basic story-based platformer, but I'm programming the game engine myself. So far it's going well, but I encountered some difficulty when trying to implement solid objects, things the player can't go through.

In the first revision of my engine, the algorithm is as follows:

```
//when the player moves left
var moveby = -player.speed; //player.x - player.speed => player moves left
//for each solid object
for (var i = 0; i < Game.currentmap.solids.length; i++) {
  var solid = Game.currentmap.solids[i];
  //if player isn't going to touch the solid object when it moves, continue loop
  if (!Game.check_collision(x - speed, y - speed, w + (speed * 2), h + (speed * 2), solid.x, solid.y, solid.w, solid.h)) {
    continue;
  }
  //a hitbox on the side of the solid object
  var hitbox = {
    x: ogbox[0] + ogbox[2],
    y: ogbox[1],
    w: speed,
    h: ogbox[3]
  }
  if (Game.check_collision(x, y, w, h, hitbox.x, hitbox.y, hitbox.w, hitbox.h)) {
    //move player left until they hit it, then break loop
    moveby = hitbox.x - x;
    break;
  }
}
return moveby;

```

Essentially, this code is copied for each direction the player can move (up, down, left, and right). The `x`, `y`, `w`, and `h` variables are the `x`, `y`, `width`, and `height` of the player's hitbox. The game will check if the player will collide with the solid object when it moves. If it won't, the loop continues. If it will, the function will calculate how far the player moves before it will hit the solid object, then moves the player that far.

Clearly, this isn't very efficient, and the code looks terrible. But I can't think of a better way to go about this. Could somebody please give me a better recommendation?

# Answer
> 1 votes
Firstly, I wouldn't recommend writing a separate piece of code for each direction. Instead, try to formulate a general solution. Also, if you need more complex collision checking and handling, you might want to use a physics engine like Box2D. But if you want to write the code yourself, here is my explanation:

I assume you are using a rectangle as your player's collision box and that you don't need continuous collision detection (needed for very fast objects). I also assume that going in positive y-direction is going 'up' and going in positive x-direction is going 'right'. I don't know electron, but will try to use obvious variable and function names. Further down I defined some utility functions. The minimal approach I can think of works as follows.

Separate your code into two parts:

1. Calculating your player's speed and setting new position
2. Detecting and handling collisions

## Calculating player's speed and setting new position

* Calculate the player's speed as a 2D vector with x- and y- components (this may involve walking, jumping, falling)

```
  // Set horizontal speed depending on user's input
  if (key_is_pressed(LEFT) && !keyIsPressed(RIGHT)) {
      speed.x = -walk_speed;
  } else if (key_is_pressed(RIGHT) && !keyIsPressed(LEFT)) {
      speed.x = walk_speed;
  } else {
      speed.x = 0;
  }

  // Calculate vertical speed (jumping, gravity)
  if (isGrounded) {
      key_is_pressed(UP) {  // JUMP
          isGrounded = false;
          speed.y = jump_speed;
      }
  } else {
      speed.y -= gravity;  // FALL - accelerate downwards
  }

  // Move player to new position
  x = x + speed.x;
  y = y + speed.y;

```

## Detecting and handling collisions

* Check whether the player is colliding with a solid object
* If there is a collision, move the player out of the solid object either horizontally or vertically depending on his/her position relative to the solid object and set the player's respective speed to 0

This pseudocode is a more detailed description of the last step:

```
// FOR LOOP START
if (check_collision_rectangle(x, y, w, h, solid.x, solid.y, solid.w, solid.h)) {
    deltaX = get_x_overlap(x, y, w, h, solid.x, solid.y, solid.w, solid.h);
    deltaY = get_y_overlap(x, y, w, h, solid.x, solid.y, solid.w, solid.h);
    // Move player out of solid object horizontally or vertically,
    // whichever is shorter, and set respective speed to 0
    if (Math.abs(deltaX) <= Math.abs(deltaY)) {
        x = x + deltaX;
    } else {
        if (deltaY < 0) {  // if player just landed
            isGrounded = true;
        }
        y = y + deltaY;
    }
}
// FOR LOOP END

```

## Moving in steps of limited size

Should you face the problem, that the player is penetrating solid objects or behaving weirdly, it might be due to a too big jump from one frame to the next. In this case you could moving the player at steps of a limited size at a time. Do this by moving the player by the step size into the desired direction. This can be done by first normalizing the speed-vector. Then multiply it by step\_size and then executing the code inside a loop until the player was moved by the full amount.

```
let magnitude = Math.pow(speed.x, 2) + Math.pow(speed.y, 2);
let speedNormalizedX = speed.x / magnitude;
let speedNormalizedY = speed.y / magnitude;
let stepSize = 5;

while(magnitude > 0) {
    if magnitude >= stepSize {
        x = x + speedNormalizedX * stepSize;
        y = y + speedNormalizedY * stepSize;
    } else {
        x = x + speedNormalizedX * magnitude;
        y = y + speedNormalizedY * magnitude;
    }
    magnitude = magnitude - stepSize;

    // DO COLLISION CHECKING AND HANDLING HERE
}

```

Note that this is not very performant, if the step size is small. But it shouldn't cause problems for a basic platformer.

## Utility functions

```
function get_x_overlap(x1, y1, w1, h1, x2, y2, w2, h2) {
    leftOverlap = x2 - (x1 + w1);
    rightOverlap = x1 - (x2 + w2);
    // if not overlapping return 0
    if (leftOverlap <= 0 || rightOverlap <= 0) {
        return 0;
    }
    if (leftOverlap < rightOverlap) {
        return -leftOverlap;
    } else {
        return rightOverlap;
    }
}

function get_y_overlap(x1, y1, w1, h1, x2, y2, w2, h2) {
    bottomOverlap = y2 - (y1 + h1);
    topOverlap = y1 - (y2 + h2);
    // if not overlapping return 0
    if (bottomOverlap <= 0 || topOverlap  <= 0) {
        return 0;
    }
    if (bottomOverlap < topOverlap ) {
        return -bottomOverlap;
    } else {
        return topOverlap;
    }
}

function check_collision_rectangle(x1, y1, w1, h1, x2, y2, w2, h2) {
    // if rect1 is above, below, left or right of rect2, return false
    if (y1 > y2 + h2) {  // above
        return false;
    }
    if (y1 + h1 < y2) {  // below
        return false;
    }
    if (x1 + w1 < x2) {  // left
        return false;
    }
    if (x1 > x2 + w2) {  // right
        return false;
    }

    // else return true
    return true;
}

```

---
Tags: collision-detection, javascript, collision-resolution, physics-engine, aabb
---


# Question
Title: Make linear parameter change seem chaotic
I'm trying to solve a challenge with linearity of my animation. Let say we have a Tug of war mechanic. One team is much stronger and it moves line from point A(0) to point B(10) with a speed of 1 unit per second. It's easy to calculate it takes 10 second to move the line from 0 to 10.

Now the problem is that I want to simulate that both teams are fighting with each other, trying to win so value is fluctuating, being very chaotic, but final result is that after 10 seconds it's in point B(10).

The initial idea was to use random easing functions with intervals \<0,1\> so without outBack, OutElastic, etc., because I don't want to go with value under 0 and beyond 10. The issue is that easing functions are good for smooth animations, but not to simulate fighting.

My second idea was to use multiple random easing functions. For example between \<0,1\> I use InQuad, \<1,2\> Out Expo ... \<9,10\> InOutCirc. I expect it to seem much more random than just using 1 easing function for whole animation.

I want to ask if you know of any algorithm or other solution to my problem that is better fit than combining easing functions?

# Answer
Add a sine curve to the value. It makes the value seem fluctuate. But the integral of the sine function is 0, so in the long run it doesn't change the result.
> 1 votes

---
Tags: algorithm, easing
---


# Question
Title: How to implement collision detection using opengl and c++
I am trying to implement collision detection system in opengl and c++ and I have a few qustions about best directions. I will just explain my ideas.

So, I have a cube and a sphere as a basic collision example. Well, maybe more basic example would be two spheres but let us ust go with this. So, main idea is to check the distance between cube faces and a sphere. Idea of checking the distance from some plain is mathematically clear to me, but in practice, I have to give my vertices to gpu and then do transformations there. So, what I could do, I could transform my vertices on cpu side also, but obviously this would be done just for the vertices, not for all the points. So I could know where my cube is and where are all the corners. So, I can check if I am above any cube side and if I am I can check if I am colliding with it. But what I can't check is what is exact point of collision since I do not have every point on cpu side tracked. If I want to have realistic collisions I would need to know this in order to calculate cube rotation and translation. So should I solve plane/line intersections or what? Should I maintain an equation for each plane of the cube and solve for intersections to know exact spot? Of course, I would do this only after being sure that I am colliding with that plane. Basicaly, what is the best way of manipulating data on cpu side to keep track of everything?

# Answer
> 1 votes
The whole process involved in what you want to do is too broad for the context of a StackExchange question, so I'll cover broadly what you're looking for.

As it's been said in the comments, collision detection is not done on the GPU. The GPU is not aware of the concept of *physics*, it cares only about the graphics (¬), so you'll want to process the physics on the CPU and then send the results to the GPU (through a matrix) so that it shows correctly the world state. Alternatively, the physics engine does not care about the GPU or what the users sees (and how they see it).

To do that, you need a part of your code to only care about physics. Let's say you have two primitives:

* cube
* sphere

You need a way to define those items; for a cube it's its length, and for a sphere, it's the radius. You can assume that those are centered at the origin, so the vertices of the cube, in *local frame* are situated at `±l/2` where `l` is the length of the cube.

Then you'll need to know how those are positioned in the world, so you add to each of those a *transform matrix* used to transform the object from *local frame* to world frame; it is essentially containing the position and the orientation of the object. This is what you'll end up sending to the GPU each frame.

The primitive length/radius and the transform matrix give you all the information you need to know where exactly is the object.

You'll use this information to determine if objects collide. You'll need some functions to tell you if two objects collide (I suggest you look up those using your favourite search engine, it's been implemented many times):

Each frame, you check each pairs of objects using those functions, and if they collide, you then handle the collision in the way you see fit (sometimes, those function will tell you the point(s) of contact and how much they penetrate, along with the axis of penetration, so you can push them out if you want them to only "touch").

¤

That's it. Once you have handled the collisions, the objects are placed at their final location this frame using their transform matrix, so the next physics step is ready to go. It's now time to make your user aware of it: you find a way to send the transform matrix (that's your "model" matrix) to the GPU (AFAIK, you need to set a uniform before drawing your primitive's VAO).

---

¬ I'm pretty sure some physics can be done on the GPU in some context, but generally speaking in game development, you'll want some parts of your game logic aware of the results of the physics steps (e.g. a bullet has hit an enemy, so you'll want to remove some hit points on the enemy entity), and going from the GPU back to the CPU (where your game logic executes) is not trivial/optimal.

¤ Often, physics engines will have "two phases" when checking for collisions

* the broad phase, where they roughly check if the two object *may be* colliding (e.g. using AABB)
* the narrow phase, if the broad phase concluded that they may be colliding, the narrow phase will actually check more precisely if the two objects collide, and how they collide.

---
Tags: opengl, collision-detection
---


# Question
Title: Can't serialize plain struct with Nullable fields
I try to save game data in `PlayerPrefs` as JSON string. I read in documentation that I can use plain struct/class with `[Serializable]` attribute but it doesn't work...

First I thought that data didn't arrive so I start to debug and watch values and saw that data is arrived. Then thought that (may be) `SetString` method is asynchronous, but when I evaluate the expression `JsonUtility.ToJson(GameData)` it showed me empty string again

Also I tried:

* add `[SerializeField]` to both fields
* use `int` instead of `enum`
* add/remove `[Serializable]` attribute for enum

The problems disappears when I don't use `Nullable` fields. Is there any workaround to use `Nullable` fields?

using System;
using UnityEngine;

[Serializable]
public enum FPSValues {
    High = 60,
    Low = 30
}

[Serializable]
public struct GameData {
    public FPSValues? FPS;
    public bool? IsAudioEnabled;
}

public class GameDataManager : MonoBehaviour {
    public static GameData GameData;

    private void Awake() {
        Load();
    }

    public static void Save() {
        PlayerPrefs.SetString("GameData", JsonUtility.ToJson(GameData));
        var x = PlayerPrefs.GetString("GameData");
    }

    private void Load() {
        var x = JsonUtility.FromJson<GameData>(PlayerPrefs.GetString("GameData"));
        GameData = x;
    }
}
```
</code></pre>

# Answer
You can gain the effect of the nullable just by updating your enums:

```
[System.Serializable]
public enum FPSValues : byte {
    Unset = 0,
    High = 60,
    Low = 30,
}

[System.Serializable]
public enum OptionalBool : byte {
    Unset,
    False,
    True
}

```

Now instead of `if (FPS != null) ...` you'd write `if (FPS != FPSValues.Unset) ...` and the rest is pretty much the same as working with your unmodified enums.

In fact, it even lets you handle all three cases in a single switch:

```
switch (FPS) {
    case FPSValues.Low: /*...*/ break;
    case FPSValues.High: /*...*/ break;
    default: /*...*/ break;
}

```

While with a nullable you'd need to write the slightly more cumbersome:

```
if (FPS.HasValue) {
   switch (FPS.Value) {
       case FPSValues.Low: /*...*/ break;
       case FPSValues.High: /*...*/ break;
   }
} else {
   /* Default behaviour... */
}

```

This plays nicely with the Unity serializer for both JSON and Inspector parameters (the same logic is used for both, so a good way to check whether a type is supported is to see if you can edit it in the Inspector).

And as a bonus: it uses less memory! The previous nullable versions used 2-8 bytes each (due to adding separate storage for the null flag, plus alignment), while these new enums fit in just a single byte.
> 1 votes

# Answer
There is nothing wrong with your code. x is null in your example because that line of code did not yet get executed. If you add another line after it, you will see that x will be of type `GameData`.

```
public static void Save() {
    PlayerPrefs.SetString("GameData", JsonUtility.ToJson(GameData));
    var x = PlayerPrefs.GetString("GameData");
    Debug.Log(x);
}

```

To make your code read easier, don't name the variable the exactly the same as your class/ struct, enum. Use _ or different case to make sure when you mean the variable and when the class.
> 1 votes

---
Tags: unity, c#, serialization, json
---


# Question
Title: Mesh isn't rotating with Quaternion.Euler
I am trying to get a clock tower to rotate it's analog time according to the actual time.

However, the mesh or materials won't rotate using the "DateTime.Now.TimeOfDay; hours.localRotation = Quaternion.Euler" method. It stays still. Can anyone please help?

Code:

```
private const float
    hoursToDegrees = 360f / 12f,
    minutesToDegrees = 360f / 60f,
    secondsToDegrees = 360f / 60f;

public Transform hours, minutes, seconds;
public bool analog;

void Update()
{
    if (analog)
    {
        TimeSpan timespan = DateTime.Now.TimeOfDay;
        hours.localRotation =
            Quaternion.Euler(0f, 0f, (float)timespan.TotalHours * -hoursToDegrees);
        minutes.localRotation =
            Quaternion.Euler(0f, 0f, (float)timespan.TotalMinutes * -minutesToDegrees);
        seconds.localRotation =
            Quaternion.Euler(0f, 0f, (float)timespan.TotalSeconds * -secondsToDegrees);
        print(timespan);
    }
    else
    {
        DateTime time = DateTime.Now;
        hours.localRotation = Quaternion.Euler(0f, 0f, time.Hour * -hoursToDegrees);
        minutes.localRotation = Quaternion.Euler(0f, 0f, time.Minute * -minutesToDegrees);
        seconds.localRotation = Quaternion.Euler(0f, 0f, time.Second * -secondsToDegrees);
    }
}
}

```

# Answer
> 0 votes
A good debugging trick: keep your Console tab visible, and read all the errors it prints.

A correctly coded game will print no errors here. If you have errors, the compiler or runtime are telling you that you made a mistake, and you should ensure all such mistakes are fixed before looking for problems elsewhere.

If you have trouble understanding an error message, put the exact text into a search engine. You won't be the first person to see this message, so you'll quickly find existing Q&A and guides that tell you what to do about it.

In this case, the runtime is telling you that you have an "UnassignedReferenceException: The variable `seconds` of `BigBen` has not been assigned."

This means that you forgot to tell BigBen which object it should be rotating, by dragging that object into the corresponding field in the script's inspector, or using an appropriate `Find...` method. When it tries to rotate this object that it hasn't been given, the script aborts, and no code beyond that point will execute this frame.

There may be other problems once you fix this one. Ensure you fix every error message before posting here, to eliminate the easy stuff and isolate the problem you really need help with.

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


title: How to prevent memory hacks?

text:
# Question
Title: How to prevent memory hacks?
For cheating or maybe just making some trainers, it's possible for hackers to read and update variables directly in the game's memory.

Is this something that can simply be prevented, or is the answer still to "validate critical data on the server"?

As I searched, I found a tool like a cheat engine that helps hackers to find the changing value and where it changes to change some variable on memory. A very basic suggested approach is to add some offset to critical variables to keep them undiscoverable from hackers with their value. but I think there should be more robust techniques for that.

I know there are many game mechanics that cannot be authorized by servers: a well-known example is weapon recoil, which is hacked by many cheating tools.

I need to know better techniques for memory cheat prevention.

# Answer
> 6 votes
I've seen some folks suggest obfuscating your variables something like this:

```
public class ObfuscatedInt {

    int _mask;
    int _masked;

    public ObfuscatedInt() {
        _mask = GetRandomInteger();
        _masked = ~_mask;
    }

    public int Value {
         get { return _masked ^ _mask; }
         set { _masked = value ^ _mask; }
    }
}

```

Now any variable you store in one of these isn't written to memory in a recognizable way - its bits are randomly scrambled so a trivial search for a specific bit pattern, like the life counter changing from 3 to 2, won't find it.

The deal-breaker for any client-side security is this: **the player is under no obligation to run the code you provided**.

A hacker could take the game executable, decompile it, and find this `ObfuscatedInt` type. Then they replace `_mask = GetRandomInteger();` with `_mask = 0;` (or a similar no-op) and recompile. Now they have a version of your game with all unmasked variables, and can go back to memory hacking just as before.

Or say you have a piece of code that watches particular variables and trips an alarm if they change values in an unsanctioned way. Again, a hacker can find the alarm code and just delete it, so this watcher code does nothing.

The same goes for code that tries to read the running executable, and trip an alarm if it detects that its own code has been tampered with. No-op the "then" case, and it's completely defanged.

So you might attempt to solve this from the server: have the server ask unpredictable questions about the client code, and if a client gives a wrong answer, block it as a cheater. But even here, a hacker can run a valid, unmodified client in a sandbox, forward the server's quizzes to it, intercept its answers, and report them as its own.

Every client-side anti-cheat on a desktop PC is just layers and flavours of these tactics, and you're just hoping the hacker will run out of motivation before you run out of layers of obfuscation. You cannot *prevent* memory hacks, only delay them.

Meanwhile, all those layers cause real performance impacts and an increased risk of bugs for all of your players, even if most of them are honest.

That's what folks mean when they say "validate critical data on the server" - this is not a temporary inconvenience that surely will be solved in another year or two. This is the fundamental nature of remote users running code on devices they control. You have no way in principle of verifying that the code they're running is the code you wrote, and not a forgery or hacked copy. So: **the client is in the hands of the enemy. Never trust the client.**

---
Tags: memory, anti-cheat
---


# Question
Title: How do I make a doorway going into the next scene?
I new to GDevelop and I use it on a Chromebook.

I'm making this game that I'm kind of proud of! I've found a way to teleport players to the next scene, by just putting the condition, then just make the event: Open url (and then the link of the scene I want the player to travel to). When I use the method I am using now, The game keeps opening tabs of different scenes! And, when I try going back to a tab, It creates like, eight new tabs! It is probably just a glitch. I go to the events section then I set the action to be: open url or file: And then the link of the next scene. I would just like to find a better way.

Can I get a javascript code to make the player teleport when it touches the door or the teleporter?

I would really like to find a BETTER way to teleport the player.

# Answer
This is very simple (unless the game is supposed to open a new link, if so please specify).

You can just use the collision condition for when the player is in collision with a door and use the change the scene action to change the scene to the next scene.
> 0 votes

---
Tags: scene, gdevelop
---


# Question
Title: Find where two (mirrored) 2d vectors intersect a rectangle bounds
I've created a 2d gradient shader which uses an absolute start/end point to determine how an arbitrary amount of colors are positioned along the gradient line. I now am creating an api to create a gradient with an angle to describe the direction the linear gradient gets drawn, and calculating the start/end points of the gradient based on that angle & the bounds of a quad. Running into an issue here finding those same start/end points which I'm struggling to solve..

This is a visual of the problem I'm trying to solve. I need to determine `x,y` & `x2, y2` based on any two (opposite) vectors. The vectors will always originate from the center of the rectangle, and can be in any direction (opposite of each other). Could also think of it as one line segment from `x,y` -\> `x2,y2`. I've tried a trigonometry based approach here which almost kind of works but fails as the angle approaches the corner of the bounds. Hoping for a more clean solution using vector math which will be more efficient.

My initial thoughts are just to represent the rectangle as 4 axis-aligned line segments and attempt to calculate intersection that way, but struggling to figure out how to go about this.. I only have an angle right now that I'm using with the center point to calculate a unit vector in the proper direction. Any help appreciated!

# Answer
Imagine we're firing a bullet from `E` with velocity `v`. At some time `t`, the point `E + v*t` will hit the horizontal line joining `A-B` or the vertical line joining `B-D` (or their mirror images in the negative case). We want the earliest such intersection - the value of `t` closest to zero.

Since we know the distance the ray has to cross for each case, vertically and horizontally, and the speed expressed by `v` in each axis, we can find the time it takes to cross those gaps with two divisions:

```
float2 gap = B - E;
float2 hitTime = abs(gap/v);
// That's component-wise division:
// float2(gap.x/v.x, gap.y/v.y)

float t = min(hitTime.x, hitTime.y);

float2 intersection = E + v * t;
float2 otherIntersection = E - v * t;

```

(If `v` is a unit vector, then you can also think of `t` as the length we're travelling in direction `v`)
> 0 votes

---
Tags: mathematics, linear-algebra
---


# Question
Title: What is the legality of publishing a free game on itch.io under the age of 18?
I am planning on publishing my first game on itch.io and I need to know if this is legal.

The game will be free and I don't plan on receiving any type of monetization on the game if that's important.

# Answer
Yes. At the time of writing itch.io allows individuals under 18 years to publish games if they have parental or guardian consent. I quote from itch.io Terms of Service:

> If you register an account to sell, distribute, or publish games or other content on itch.io, you agree to be bound to the terms of this Agreement as a platform publisher (“Publisher”). Publishers affirm that they are either more than 18 years of age, or possess legal parental or guardian consent, and are fully able and competent to enter into the terms, conditions, obligations, affirmations, representations and warranties set forth in this Agreement.
> 22 votes

---
Tags: legal, publishing
---


# Question
Title: Why is my simple movement script making Capsule go into the air when movement is fast?
I am trying to create a simple movement script. Currently I don't have any jumping implemented; the movement script should just move rigidbody-based Capsule left, right, forward, backward based on Camera direction.

What is happening, however, is that the Capsule will go into the air after moving consistently for a few seconds. This especially happens if you hit two movement keys (W and A) at once.

Any ideas why this happens and how to prevent it? "Use Gravity" is checked. The constraints of the Rigidbody are "Freeze Rotation" on X, Y, and Z. All values for Rigidbody settings are default.

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

public class Scratcher : MonoBehaviour
{
    Rigidbody r;
    public CapsuleCollider capsule;
    public Transform cameraTransform;

    //Base Movement
    public float horizontalInput;
    public float verticalInput;
    public Vector3 moveDirection;
    public Vector3 moveDirectionRaw;
    public int rotDegPerSecond = 720;
    public float speed;

    //GroundChecking
    public LayerMask groundLayerMask;
    public Transform groundCheckTransform;
    public bool isGrounded;
    public float groundCheckRadius = 0.25f;
    public float distanceToGround;

    void Awake()
    {
        r = GetComponent<Rigidbody>();
        capsule = GetComponent<CapsuleCollider>();
    }

    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
    }

    private void FixedUpdate()
    {
        GroundCheck();

        moveDirection = new Vector3(horizontalInput, 0.0f, verticalInput).normalized;
        moveDirection = (Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * moveDirection).normalized;
        moveDirectionRaw = new Vector3(Input.GetAxisRaw("Horizontal"), 0.0f, Input.GetAxisRaw("Vertical")).normalized;
        moveDirectionRaw = (Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * moveDirectionRaw).normalized;

        if (moveDirectionRaw != Vector3.zero && moveDirection != Vector3.zero)
        {
            Quaternion targetRotation = Quaternion.LookRotation(moveDirection); //or moveDirectionRaw
            targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotDegPerSecond * Time.deltaTime);
            r.MoveRotation(targetRotation);
        }

        Vector3 force = moveDirection * speed;
        r.AddForce(force, ForceMode.VelocityChange);

        GroundStopSlide();
    }

    void GroundStopSlide()
    {
        if (moveDirectionRaw == Vector3.zero)
        {
            Vector3 zeroMe = new Vector3(0, r.velocity.y, 0);
            r.velocity = zeroMe;
        }
    }

    public void GroundCheck()
    {
        isGrounded = Physics.CheckSphere(groundCheckTransform.position, groundCheckRadius, groundLayerMask);

        RaycastHit groundHit = new RaycastHit();
        if (Physics.Raycast(transform.position, -Vector3.up, out groundHit))
        {
            distanceToGround = groundHit.distance;
        }
    }
}

```

# Answer
> 0 votes
maybe your move direction have a force that upwards, check the script in FixedUpdate and physicmaterial "bounce"

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


# Question
Title: Spawning enough game objects between two points
I am trying to spawn enough gameobjects (`ropePieces`) between two point sort of like a rope. But I don't know how to stop when I reach the end point

```
extends Node

onready var rb=$RigidBody2D
onready var start=$StaticBody2D
onready var end=$StaticBody2D2
var piece= preload("res://scenes/RopePiece.tscn")

var isStop=false
onready var obj2=$StaticBody2D

func _ready():
    for n in 5:
        var obj=piece.instance()
        add_child(obj)
        obj.position=obj2.position
        obj.position.y+=30

        obj.get_node("PinJoint2D").node_a=obj2.get_node(".").get_path()
        obj.get_node("PinJoint2D").node_b=obj.get_node(".").get_path()
        obj2=obj
        var distance=obj2.position-obj.position
        print(distance)

```

# Answer
> 1 votes
What I see is that you are advancing 30 pixels per object:

```
obj.position.y+=30

```

If that is the space one object ought to take, and you can divide the total distance by 30 and that should give you the number of objects. Something like this:

```
var total = ceil(start.position.distance_to(end.position) / 30)

```

Then use that to iterate (`for n in total: #…`).

---
Tags: godot
---


title: Batch rendering model matrix to shader

text:
# Question
Title: Batch rendering model matrix to shader
I'm working on a batch renderer. I'm limited to using one shader per batch (one draw call for everything).

I want to use a TBN matrix for my lighting. To calculate the TBN matrix for each object I need to provide a model matrix to describe the individual objects' change in position. Providing hundreds of matrixes via uniforms or adding them to the vertexes might be very slow. (providing the updated vertex locations instead of the matrix wont work as the TBN matrix needs to know the translation that occurred not the position of the vertices)

Are there any solutions to this issue? I'd rather keep using my batch rendering for my 3d models as it's nice and fast.

further context: I need TBN matrix to convert my vectors into tangent space so my lighting values and my normals all work nicely in the same space. Since the TBN matrix uses an object's position translation matrix and I'm batch rendering with many objects all using the same shader, I run into this issue.

The TBN matrix is a very important matrix to calculate the lighting and view vectors and normals in the same space: quote from https://learnopengl.com/Advanced-Lighting/Normal-Mapping

> So now that we have a TBN matrix, how are we going to use it? There are two ways we can use a TBN matrix for normal mapping, and we'll demonstrate both of them:

> 1. We take the TBN matrix that transforms any vector from tangent to world space, give it to the fragment shader, and transform the sampled normal from tangent space to world space using the TBN matrix; the normal is then in the same space as the other lighting variables.
> 2. We take the inverse of the TBN matrix that transforms any vector from world space to tangent space, and use this matrix to transform not the normal, but the other relevant lighting variables to tangent space; the normal is then again in the same space as the other lighting variables.

My batching technique:

I am currently recalculating the positions of the vertices on the cpu. and updating the buffer with the new vertices, they are passed to the shader using layouts. The only matrix being passed to the shader right now is the vp matrix.

# Answer
> 1 votes
If I understand your batching strategy correctly, you're using CPU-side code to "bake out" many objects' transformations, multiplying their mesh vertex positions by the object's local-to-world matrix, and saving these pre-transformed vertices into a single vertex buffer. This buffer is now in world space, so no model transformations are needed on the GPU to put the vertices into the right places.

If that's accurate, then as part of this process, you'll also want to transform each vertex's normal and tangent vectors by the inverse transpose of the object's local-to-world matrix. That way these vectors will *also* be in a single unified world space before you pass them to the GPU.

Since all per-object information is already baked into these vectors, your shader doesn't need to apply any further compensations. The TBN matrix it computes from the normals and tangents you baked this way will inherit the per-object info you baked into them.

This all works if your batch is pre-transformed into view space too. Just make sure whatever matrix you use for vertex positions, you use its inverse transpose for the tangents and normals. (Though as a shortcut, if your models never contain non-uniform scale or shear, you can get away with using the upper-left 3x3 of the matrix instead of computing the inverse transpose).

---
Tags: opengl, c++, shaders, glsl, batching
---


# Question
Title: Can both High poly model go with a low poly scene?
I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model.

# Answer
> 1 votes
There is a lot you could by choosing the right material/texture that will give you that 'minimalistic look'. Like Theraot mentioned, there are ways to make your mesh low poly. Check out the script provided here by the user 'robertbu'. It worked great for me and it might too for you!

Good luck,

Alex

# Answer
> 1 votes
I know it's and old question, but for everyone who finds this question.

)One option as mentioned by the other answer is using a low-poly shader to emulate the low poly look with a high poly model. This doesn't actually reduce the polygons, but just makes the model look low-poly. If you are using the low poly style because you have extremely low specs like on an Oculus Quest 1 this will be a problem. There is even an unity asset to bake it into the model and texture without actually needing to use a shader.

> https://assetstore.unity.com/packages/vfx/shaders/lowpoly-shader-197219 https://assetstore.unity.com/packages/tools/modeling/lowpoly-mesh-generator-196511

)Use blender or some other modelling software to reduce the poygons of the model so much so much that it becomes low-poly style. I don't know much about modelling but the `Decimate modifier` in blender seems to make a mesh low-poly.

> https://www.youtube.com/watch?v=GrD71-wXrIA

)As for characters you can look at anime games. Anime style characters are used with many different environment styles. For eg. realistic, stylized and I assume low-poly wouldn't look out of place either. You can use these games as reference for mixing styles. The humanoid characters are mostly anime and the enemies could be anything. But you have to keep consistency unless you want your game to be called an asset flip. All humanoid characters be one style and the environments to be one style and the non-humanoid ones match the environment or character style. Mixing and matching too much is gonna be a deal breaker for many players.

And slightly offtopic if you want to make all your characters Anime then you can use the free Anime Character creator calle VRoid Studio. You can just set some sliders and vallah! you have an anime character. And as for the clothes, some clothes are available for free and some others are sold cheaply on booth.pm . One just needs to select the clothes and they are applied. No 3d modeling skills needed.

> https://vroid.com/en/studio

---
Tags: unity, art
---


# Question
Title: Collision normal for sphere near edge of triangle face
When my sphere (or bottom part of a capsule) moves with its bottom near the edge of a mostly horizontal triangle (a face of a heightmap), I am sometimes getting very bad (mostly horizontal) normals. How should a proper collision normal be calculated in this situation?

Here's my attempt to explain the current situation leading to these bad normals. Running the usual separating axis tests, it is determined that the best axis is mostly vertical. Based on this axis, the colliding features of the shapes are determined. The feature of the sphere is always a point on the bottom, and the feature of the triangle can be the whole face, an edge or a point. The bad normals here are arising from point-edge collisions. Namely, the best axis was determined to be mostly vertical, but it can happen that the point is extremely close to the edge, and vertically closer than horizontally (and so apparently a separating axis in the plane of the triangle was not considered or not the best), so that the contact pair consisting of the point of the sphere and the closest point on the edge has a normal which is mostly horizontal.

How should this problem be solved?

For reference: this is Godot issue #69683 which I would like to fix.

# Answer
> 0 votes
If possible, compute the collision with the triangle mesh, not a single triangle, as follows:

Any time the sphere-triangle collision test decides the sphere is colliding with the edge of the triangle, that means you should instead be colliding the sphere with the adjacent triangle across that edge.

If both triangles think the collision is on edge, then use a normal determined by the contact point on the sphere, or perhaps (this might be better for height fields) the average of the two triangles' normals.

---
Tags: collision-detection, physics, 3d, separating-axis-theorem
---


# Question
Title: How to keep the sunlight out of the interior even with a transparent roof?
In my Unity project, the player sees the action from a bird's eye view. If he walks into a building, the roof should become invisible. The problem now is that the lighting shouldn't change, which means that the sun and other light sources that didn't penetrate through the roof before shouldn't do the same with the transparent roof. This means that the interior remains illuminated only by the interior lighting, even if there is no longer a roof.

*The blue areas in the image should simulate the shadows cast by the sunlight source. Note: This does not fully describe the problem mentioned, since it is not only about the shadows, but also about the illumination of the interior. (But I didn't know how to draw this...)*

How can I achieve this?

---

## EDIT

Through @DMGregory's answer, I set the MeshRenderer of all roof objects to "OnlyCastShadow" via script. However, this doesn't seem to work in play mode. It looks as if the sun's rays are penetrating the building again outside of a certain area.

Gif Link

What could be the reason?

# Answer
> 0 votes
I think I could fix the problem now. In essence, @DMGregory's answer helped by setting the roofs to "MeshRenderer -\> Cast Shadows -\> "Shadow only".

Then there was the problem with the incorrect and circular shadows. This can be solved in two ways.

1. In ProjectSettings -\> Quality -\> Set Shadow Projection to "Close Fit".
2. Alternatively, it can remain set to "Stable Fit", but then the camera's far clipping plane must be set to a much higher value until the sector of the circle is no longer visible.

---
Tags: unity, lighting
---


# Question
Title: UnityWebRequest / UnityEngine.WWW — FileNotFoundException when loading class from Json
I'm trying to load a class using `JsonUtility` to populate a few strings. I navigate to the file using Unity Simple File Browser and load it using the following coroutine:

```
IEnumerator ShowLoad()
{
    yield return FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.Files, false, null, null, "Upload", "Select");

    if (FileBrowser.Success)
    {
        Debug.Log("File Browsed: " + FileBrowser.Result[0]);

        UnityWebRequest url = new UnityWebRequest("file:///" + FileBrowser.Result[0]);

        yield return url;

        StreamReader reader = new StreamReader(url.ToString());
        string json = reader.ReadToEnd();

        Campaign c = JsonUtility.FromJson<Campaign>(json);
        CampaignName = c.CampaignName;
        saveFolder = c.saveFolder;
        savePath = c.savePath;
        persistentFolder = c.persistentFolder;
        persistentPath = c.persistentPath;
    }
}

```

But every time I try to run the code I get the following error:

```
FileNotFoundException: Could not find file "C:\Users\arily\Documents\GitKraken\DND-Astra\Astra\UnityEngine.Networking.UnityWebRequest"
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) (at <7b935204f5ff4bcab44b3b0ebca330bf>:0)
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options) (at <7b935204f5ff4bcab44b3b0ebca330bf>:0)
(wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,System.IO.FileOptions)
System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize) (at <7b935204f5ff4bcab44b3b0ebca330bf>:0)
System.IO.StreamReader..ctor (System.String path, System.Boolean detectEncodingFromByteOrderMarks) (at <7b935204f5ff4bcab44b3b0ebca330bf>:0)
System.IO.StreamReader..ctor (System.String path) (at <7b935204f5ff4bcab44b3b0ebca330bf>:0)
(wrapper remoting-invoke-with-check) System.IO.StreamReader..ctor(string)
Campaign+<ShowLoad>d__12.MoveNext () (at Assets/Campaign.cs:90)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <ab7de6937a4448b0a6ccd59e9820599a>:0)

```

I have tried the same method using `WWW` to load an image and it worked, but when loading a JSON using `WWW` I get the same error referring to `UnityEngine.WWW` instead. I haven't been able to find anything online about it, so I'm posting here. Any insight or tips would be much appreciated, thank you!

# Answer
> 0 votes
Resolved this a long time ago and forgot to post my solution here. I think UnityWebRequest was the problem, so I used SerializationUtility instead.

```
public IEnumerator ShowLoad()
    {
        yield return FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.Files, false, null, null, "Upload", "Select");

        if (FileBrowser.Success)
        {
            Debug.Log("File Browsed: " + FileBrowser.Result[0].ToString());

            using StreamReader reader = new StreamReader(FileBrowser.Result[0]);
            string json = reader.ReadToEnd();

            var bytes = System.Text.Encoding.UTF8.GetBytes(json);

            Campaign c = SerializationUtility.DeserializeValue<Campaign>(bytes, DataFormat.JSON);

            yield return c;

            CampaignName = c.CampaignName;

            savedCrafts = new List<CraftingRecipe>(c.savedCrafts);
            foreach (CraftingRecipe recipe in savedCrafts)
            {
                recipe.loaded = true;
            }

            TimeManager.SetTime(c.campaignMonth, c.campaignDay, c.campaignYear, c.campaignHour);

            SetPaths();

            Debug.Log("Campaign Loaded: " + CampaignName);

            PlayerManager.Manager.CmdSendCampaign(json);
        }
    }
```

# Answer
> 1 votes
Your resultant path is wrong:

`"C:\Users\arily\Documents\GitKraken\DND-Astra\Astra\UnityEngine.Networking.UnityWebRequest"`

Surely that should be something more like,

`"C:\Users\arily\Documents\GitKraken\DND-Astra\Astra\myfile.json"`

I think you've got this part wrong:

`FileBrowser.Result[0]`

Should probably be something like `FileBrowser.Result[0].fileName` as its currently converting an `object` to a `string` representation.

---
Tags: unity
---


title: How to get selected value in a dropdown

text:
# Question
Title: How to get selected value in a dropdown
I made a simple survey from a guide on YouTube.

The trouble is that dropdowns are not mentioned in there, and I have totally no idea how to get the selected text value from it.

I tried multiple options, but they don't work for me, even if the compiler doesn't return any errors. Maybe the thing is that I'm implementing the code in wrong place or I miss something different.

The solution I'll paste here looks quite logical for me and I have no idea why doesn't it work. The part of code where I tried to 'read' the dropdown value is:

```
else if (a.GetComponent<Dropdown>()!=null)
{
    result.Answer = a.transform.GetChild(0).Find("Label").GetComponent<Text>().text;
}

```

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

public class UIScript07 : MonoBehaviour

{
    public GameObject[] questionGroupArr;
    public QAClass07[] qaArr;
    public GameObject AnswerPanel;

    void Start()
    {
        qaArr = new QAClass07[questionGroupArr.Length];
    }
    // Update is called once per frame
    void Update()
    {

    }
    public void SubmitAnswer()
    {
        for (int i = 0; i < qaArr.Length; i++)
        {
            qaArr[i] = ReadQuestionAndAnswer(questionGroupArr[i]);
        }
    }
    QAClass07 ReadQuestionAndAnswer(GameObject questionGroup)
    {
        QAClass07 result = new QAClass07();

        GameObject q = questionGroup.transform.Find("Question").gameObject;
        GameObject a = questionGroup.transform.Find("Answer").gameObject;

    result.Question = q.GetComponent<Text>().text;

        if (a.GetComponent<ToggleGroup>() != null)
        {
            for (int i = 0; i < a.transform.childCount; i++)
            {
                if (a.transform.GetChild(i).GetComponent<Toggle>().isOn)
                {
                    result.Answer = a.transform.GetChild(i).Find("Label").GetComponent<Text>().text;
                    break;
                }

            }
        }

    else if (a.GetComponent<Dropdown>()!=null)
        {
            **result.Answer = a.transform.GetChild(0).Find("Label").GetComponent<Text>().text;**
        }
        else if (a.GetComponent<ToggleGroup>() == null)
        {
            string s = "";
            int counter = 0;

            for (int i = 0; i < a.transform.childCount - 1; i++)
            {
                if (a.transform.GetChild(i).GetComponent<Toggle>().isOn)
                {
                    if (counter != 0)
                    {
                        s = s + ", ";
                    }
                    s = s + a.transform.GetChild(i).Find("Label").GetComponent<Text>().text;
                    counter++;
                }
                if (i == a.transform.childCount - 1)
                {
                    s = s + "";
                }
            }

            result.Answer = s;
        }
        return result;
    }
}
[System.Serializable]
public class QAClass07
{
    public string Question = "";
    public string Answer = "";
}

```

# Answer
This is really simple, all you need is to access the `.value` field of the dropdown. This gives you the index that is selected (starting at 0). So for a dropdown with 3 options, you get 0, 1 or 2 back. If you need the exact string, you can go over that with `dropdown.options[dropdown.value].text`. But you do not need to go the options way since probably load those already from an array.

Small example code with one dropdown and button in the scene, the script is on the button and ClickTest is getting called on button click

```
public class ClickTest: MonoBehaviour {

    [SerializeField] private Dropdown dropdown;

    public void SelectedText() {
        Debug.Log(dropdown.value);
        Debug.Log(dropdown.options[dropdown.value].text);
    }
}

```

To somehow map it to your code, it would look something like that

```
Dropdown tempDropdown = a.GetComponent<Dropdown>();
if (tempDropdown != null) {
    result.Answer = tempDropdown.options[tempDropdown.value].text;
}

```

Since we need to access the Dropdown component more often, we temporary store it to not always call `a.GetComponent<Dropdown>()` again.
> 2 votes

# Answer
For new Dropdown component in Unit, add the `Dropdown` component to your `inspector` and in `OnValueChanged` section, reference the method below (Don't forget to send itself as a parameter):

```
public void OnDropdownChanged(Dropdown dropdown) {
    var newSelectedIndex = dropdown.value;
    var newSelectedValue = dropdown.options[newSelectedIndex].text;
    var newSelectedSprite = dropdown.options[newSelectedIndex].image;
    //...
}

```

If you use `TextMeshPro Dropdown` change the parameter class with `TMP_Dropdown`:

```
public void OnDropdownChanged(TMP_Dropdown dropdown)

```
> 0 votes

---
Tags: unity, c#, input, unity-ui
---


# Question
Title: How to render to texture with VR distortion?
I've also asked the question on Unity Answers.

So, I want to do some post processing effects in VR. I put a camera as a child of the Main Camera and set it to render-to-texture. Then, I take what is rendered, and display it (with my post-proc shader) on a quad in front of the Main Camera (The main camera and the child camera render different layers, so I don't render the same thing twice). (Also worth noting- I know that the depth will be collapsed out of the rendered-to-texture content; this is intentional.) The problem is, in this process, the positional data (that was rendered to texture) gets misaligned.

I've already fixed a problem where I have to manually set

```
camera_project.GetComponent<Camera>().aspect
 = main_camera.GetComponent<Camera>().aspect;

```

every frame. (Changing/setting the screen size auto sets the aspect ratio of the main camera- it does *not* automatically set the aspect ratio of the child camera).

So, with just that, everything lines up great and looks fine when it *isn't* in VR. But, when it *is* in VR, it appears that maybe some distortion is happening to the main camera that *isn't* happening to the render-to-texture camera, and thus, the overlay (the post-processed content) isn't lining up.

So what can I do to emulate the VR distortion in the child camera? Are there other properties of the Main Camera that are getting auto-set in VR that I can manually copy to the Main Camera?

# Answer
The best I've been able to come up with (not 100% perfect) is to just set the FOV of the render-to-texture cameras to be 96.5 (the main camera is set to 60). I just came up with this number experimentally. I'm not sure if under the hood it's just auto-setting the fov of the main to something similar to 96.5, but I can't find any hard info...

edit: Ok! I found hard info. Looks like it just auto-sets the fov of the main camera *during runtime* to exactly 96.01604. So, either set your render-to-texture cameras to that, or assign it at runtime from the main camera.
> 1 votes

# Answer
I have searched a lot on the internet. I can save you time. One day as of this post Unity offers absolutely nothing to get a single render texture with stereoscopic view using Single Instance.

But of course, there is the issue that if you want to make a relatively complex game Single Instance is practically mandatory.

The only solution I have found is also quite simple: use two cameras for each of the eyes of the HMD viewer. So, for each stereoscopic texture that we want, for example a portal, we will have to create two cameras that will track the position of the eyes in a relative way, recording the texture in two render textures that we can assign to each of the textures of a shader that unify in a single vision.
> 0 votes

---
Tags: unity, textures, camera, virtual-reality
---


# Question
Title: Key presses and game quit sometimes delayed by seconds
U'm currently trying to develop a 2D RPG similar to early Final Fantasy titles for the NES.

Up until now I've been reading C++ tutorials on SDL2 and doing my best to convert the concepts into OCaml. However, I'm not sure how I should handle input.

Right now I'm just reading keyboard input in my main game loop as such:

```
let handle_events game =
  let e = Sdl.Event.create () in
  let _ = Sdl.poll_event (Some e) in
  match Sdl.Event.(enum (get e typ)) with
  | `Quit -> game.running <- false
  | `Key_down -> print_endline "key was pressed"
  | _ -> ()

```

(For those unfamiliar with functional pattern matching, a `match` statement here kind of behaves like a switch-case statement) This janky "event handler" is then called every frame in my main, as such:

```
  while game.running do
    frame_start := Int32.to_int (Sdl.get_ticks ());
    Game_loop.handle_events game;
    Game_loop.update game;
    Game_loop.render game;
    frame_time := Int32.to_int (Sdl.get_ticks ()) - !frame_start;
    if frame_delay > !frame_time then
      Sdl.delay (Int32.of_int (frame_delay - !frame_time))
  done;

```

The problem is, this approach does not seem to be well-performing — sometimes when I press a key repeatedly or hold a key down, the game takes seconds before `"key was pressed"` shows up in the console. That, and sometimes I can't even quit the game.

I'm have a feeling I'm going about this the wrong way, but how?

# Answer
@DMGregory found the issue regarding the lag — it was the fact that my event handler was only handling one event per frame. Changing it to a while loop over `Sdl.poll_event` fixed the lag.

```
let handle_events game =
  let e = Sdl.Event.create () in
  while Sdl.poll_event (Some e) do
    match Sdl.Event.(enum (get e typ)) with
    | `Quit -> game.running <- false
    | `Key_down -> (
        match
          Sdl.Event.get e Sdl.Event.keyboard_keycode |> Sdl.get_key_name
        with
        | "W" -> Sprite.update game.player_ecs 0 (-10)
        | _ -> ())
    | _ -> ()
  done

```
> 3 votes

---
Tags: input, game-loop, sdl2
---


# Question
Title: Constructing a world ray from mouse coordinates
I've got the following c++ code. It produces a Ray from the mouse coordinates given. However the `z` coordinate is wrong, I expect it to be on the near plane of the view matrix, in this case `1` (from `position = { 0, 0, 1 }`). But it consistently returns `-1`

```
using namespace glm;
projection = perspective(radians(fov), (Floating)width / (Floating)height, 0.0001f, 10000.f);
vec3 center = position + direction;
view = lookAt(position, center, up);
vec2 mousePosition = { .x, .y };
vec2 normalisedCoords = {
 -1.0f + 2.0f * position.x / width,
  1.0f + -2.0f * position.y / height
};
//                                                      near z plane?
vec4 clipCoords = { normalisedCoords.x, normalisedCoords.y, -1, 1 };
mat4 invProjection = inverse(projection);
vec4 eyeCoords = invProjection * clipCoords;
mat4 invView = inverse(view);
vec4 rayWorld = invView * eyeCoords;
vec3 mouseRay = { rayWorld.x, rayWorld.y, rayWorld.z };

```

What modifications do I need to make to fix the `z` component? That or can someone suggest a better way of casting a world ray.

# Answer
`eyeCoords.w` component must be 1.0 before getting the `rayWorld`. You need to divide the `eyeCoords` vector components by `eyeCoords.w`. That way you will get 1.0 for the w component and the mouse ray will show the correct value for z.

```
//                                                      near z plane?
vec4 clipCoords = { normalisedCoords.x, normalisedCoords.y, -1, 1 };
mat4 invProjection = inverse(projection);
vec4 eyeCoords = invProjection * clipCoords;
// vvvvvvvvvvvvvvv
eyeCoords /= eyeCoords.w;  // divide each component by w component
// ^^^^^^^^^^^^^^^
mat4 invView = inverse(view);
vec4 rayWorld = invView * eyeCoords;
vec3 mouseRay = { rayWorld.x, rayWorld.y, rayWorld.z };

```

More details about the perspective matrix can be found here
> 0 votes

---
Tags: c++, raycasting
---


# Question
Title: Detect up and down slopes to switch between character animation
There's a player and a slope in my scene. I want the player to automatically switch to 'climbing down' animation when he's at the top of the slope and moving down and similarly switch to 'climbing up' when he's at the bottom and moving up. I'm using the default 'character controller'. I've managed to get the slope angle with 'Vector3.Angle(transform.forward, hit.normal)' and the 'climbing up' is working fine since the angle is \> 95 and that's the condition I stated. But when 'climbing down' the angle is not uniform and ranges from 30 - 140 and the condition I've stated is \< 70 which is not satisfied all the time and hence the animation switches from 'climbing down' to 'climbing up' and vice versa. How do I get the right slope angle to differentiate between up slope and down slope?

# Answer
> 1 votes
You can do it easily using the Dot Product between the slope normal and the transform forward vectors:

```
using UnityEngine;

public sealed class CharacterMotor : MonoBehaviour
{
    public CharacterController controller;
    public LayerMask collision;

    private void Update()
    {
        // This distance value works well for CharacterController.SlopeLimit = 45F
        const float distance = 0.2F;
        const float maxDistance = distance * 2F;

        var origin = transform.position + Vector3.up * distance;
        var isGroundCollision = Physics.Raycast(
            origin,
            direction: Vector3.down,
            out RaycastHit groundHit,
            maxDistance,
            collision,
            queryTriggerInteraction: QueryTriggerInteraction.Ignore
        );

        if (!isGroundCollision) return;

        var floorAngle = Vector3.Angle(groundHit.normal, Vector3.up);
        var isOverSlope = floorAngle > 0F;

        if (!isOverSlope ) return;

        var dot = Vector3.Dot(groundHit.normal, transform.forward);
        var isRunningUpwardSlope = dot < 0F;
        var isRunningDownwardSlope = dot > 0F;
    }
}

```

# Answer
> 0 votes
Because the system you are using is at least partially successful, I'd suggest there are two options here:

The intermittent problem is due to the capsule collider on the Player Controller and (I assume) picking the first collision hit in the list. You could try grabbing all the hits into an array and loop over them to find the one with the lowest, or highest, Y value - then use this with your existing normal check. The nature of the collider's shape can throw up a number of hits, and their order is not always guaranteed.

The second option, and the one I used when I wanted to alter walk speed based on slope, is to fire a ray down from a fixed point in front of the character, and use the difference in height between the player transform's Y and the ray hit's Y to determine the slope. This is more accurate as you are sampling a single point.

# Answer
> 0 votes
The problem seems to be the inaccuracy observed on 'climbing down'. This can be fixed using a better sampling of raycast result while calculating the slope. One such method is to try a sphere cast with some extra raycast and using statistics (mean, median, mode). This method is very well illustrated in the following posts-

1.http://thehiddensignal.com/unity-angle-of-sloped-ground-under-player/
2. https://roystanross.wordpress.com/2015/05/10/custom-character-controller-in-unity-part-6-ground-detection/

---
Tags: unity, animation
---


# Question
Title: Why not test every single edge during collision detection?
I'm a beginner so sorry if this is a stupid question

I'm trying to implement some collision detection and the most common type I see is SAT, which I believe has a time complexity of O((n+m)^2), where and n and m are the amount of vertices on each polygon.

However, why not turn every side into a line segment, and check if any of the segments are intersecting with the segments in the other polygon? The way I see it is there are going to be n\*m comparisons, and each comparison can be done in constant time, so it's faster than SAT and would work with concave polygons.

Again, sorry if this is a stupid question and thanks!

# Answer
> 0 votes
The method that you propose does not detect when one polygon is fully inside the other, and so no line segments intersect.

You can solve that with two point-in-polygon tests O(n) if all edge intersections come up negative.

But this proposed method would still be slower because the work needed to check if an edge crosses any of a list of other edges is actually *more* than the work needed to compare the dot product of that edge's normal against a list of vertices (2 multiplies and an add each, easy to vectorize). They both have the same O(n^2) time complexity for polygons containing `n` vertices, but the coefficients that big-O hides are smaller for conventional SAT since the inner loop is so dirt cheap.

---
Tags: collision-detection
---


# Question
Title: Cannot decide between using a MessageBus and entities for events in my ECS game
For example, let's say that the player walks into an enemy and in response, a chain of events should occur (such as: his score goes up, the enemy dies, a cinematic starts, etc.)

I see two "proper" ways of accomplishing this:

**Method 1:**

There exists a global message bus in the game. Any system can emit events to it, and any other system can listen for some events from it. For example, the system handling the players score would look like this:

```
messageBus.listen("playerhitsenemy", e => {
  score += e.monsterType;
});

```

and the collision system may look like this:

```
messageBus.emit("playerhitsenemy", { monsterType: 5 });

```

Similarly, other systems can listen for the same event, such that when something happens, the CPU *immediately* moves from processing the current system to the other system processing this event. That is, the `emit` call is basically just a list of callbacks that are immediately invoked and sent the message.

**Method 2:**

The second method, instead, is to encode events / messages as entities themselves. That is, when an event occurs (such as the player hitting something in the collision detection system), this would happen:

```
let newEntity = new Entity();
newEntity.components.push(new MessageComponent());
newEntity.components.push(new MessagePlayerHitsEnemyComponent(5));
entityAdmin.spawnNewEntitiy(newEntity);

```

That is, a new "message" entity is created, and it is given the generic `Message` component and the concrete event component type as well, `MessagePlayerHitsEnemy`.

Then, all systems interested in these messages would have something like this in their `execute` function:

```
for (let entity of entityAdmin.query(MessagePlayerHitsEnemyComponent) {
  let monsterType = entity.getComponent<MessagePlayerHitsEnemyComponent>();

  score += monsterType;
}

```

And then at the end of the frame there would be a system whose responsibility was deleting all messages, like so:

```
for (let entity of entityAdmin.query(MessageComponent) {
  entityAdmin.remove(entity);
}

```

---

I cannot decide which is better. The first method seems simpler and probably more efficient in Javascript, considering it's just immediately invoking all the requested functions. However, the second one seems more "correct", in each system is iteratively processed. That is, first the collision system runs in its entirety, then the scoring system, etc. There is no "jumping around" from system to system during execution. Each system processes everything in its entirety, and then the second system processes everything it's interested in, etc.

So, in essence, the first method seems simpler and more efficient, while the latter method seems more "correct", pure, verbose, debuggable, and extendable. Which one should I pick?

# Answer
My approach was to have a `PhysicsSystem` which works on entities that have a `ColliderComponent/PhysicsComponent/TransformComponent`, in turn, upon detecting collisions it creates a CollisionComponent for every entity that takes part in a collision. Then there could be followup systems in the chain that work on entities that have a `HealthComponent` and a `CollisionComponent` perhaps, or `DamageDealerComponent` and `CollisionComponent`. Essentially I just generate a component and ensure the sequence of systems is setup in a way where one system can generate entities for a later system.
> 3 votes

---
Tags: collision-detection, architecture, entity-system, component-based, entity
---


# Question
Title: In a multiplayer game developed using client server model with socket.io and node.js how can we describe the osi layers
What will the different layers in the stack look like in the osi model?

# Answer
> 2 votes
The OSI model is mostly a theoretical model. In practice, it tends to break apart as soon as you get below the standardized layers of the Internet protocols (below the transport layer). So this is really more of an academic question.

* HTTP(S) is generally considered an application level protocol, so we are already on the upmost layer of the protocol.
* WebSocket is another application-level protocol on top of HTTP, because each Websocket connection begins with a HTTP request that contains an "upgrade" header. Although some people might disagree and consider it a separate protocol from HTTP because it works very differently from HTTP once the header was sent.
* The netcode protocol of your specific game is yet another application-level protocol on top of Websocket. Which might or might not also have presentation and/or session functionality, depending on what it does in your game.

---
Tags: multiplayer, websocket
---


# Question
Title: How can I fit these isometric tiles into a TileMap?
I have downloaded this 2d isometric tileset : https://assetstore.unity.com/packages/2d/environments/cute-isometric-town-starter-pack-134286

But when I tried to create a map in Unity, I have this :

But in the tool "Tiled", I was able to do this :

But to do this in Tiled, I had to set tile size to 1024x720px.

How can I do the same thing in Unity ?

# Answer
> 4 votes
It appears that the width/height ratio of your tiles doesn't match that of your Grid component.

Go to the Grid component of your tilemap and set the cell size accordingly. When your tiles are 1024 x 720, then your cell size ratio also needs to have the same ratio. Setting those to 1024 and 720 will probably be far too big, because now a single tile is 1024 Unity units across. You certainly *could* work like that, but it is probably a bit unwieldy. But you can also set those to a much lower value as long as the ratio stays the same. For example 64 : 45 or 1 : 0.703125.

After you did that, you will probably notice that your tiles are either too small or too large to fill a cell properly. You can fix that by going to the import setting of the tileset image and adjust the "pixels per unit" setting to 1024 divided by the X-size of your grid.

---
Tags: unity, 2d, isometric
---


title: UI not scaling properly

text:
# Question
Title: UI not scaling properly
I'm trying to create an endless runner type game where once the player dies, a popup opens letting the user know that the player can be saved by watching an ad. This is how the popup looks in the game window (image on the left). There is some space between the popup and the background. One the right is the canvas data with UI mode set as scale with screen size and reference resolution. In the display(in the game view) I have selected 1920x1080 Portrait.

However when I run the game on my phone (nord 2001) the popup is getting clipped from the sides. When the UI scale mode is set as "Scale with Screen Size", shouldn't it look the same on all devices as it does in the game mode i.e there should be some gap between the popup and the background. Can someone please help me with this?

# Answer
> 2 votes
The OnePlus Nord AC2001 has a 2400 x 1080 display. This is significantly taller than the resolution you're previewing in the game view (20:9 vs 16:9)

Because you've configured your Canvas Scaler to "Match Width or Height", with a 50/50 blend between the two, anytime the game is running on a taller screen, Unity will uniformly scale up the UI to fill about 50% of that extra height. That means it ends up a little wider than you want.

If you want Unity to match the width instead, to keep the left and right margins in the exact proportions you expect, move the Canvas Scaler's slider all the way to the "Width" side. But this will mean that you'll tend to get larger vertical gaps on taller screens.

This turns out to be a hard problem: different aspect ratios need different layouts, and a simple scaling system can't always make all the changes you want automatically. You'll have to design for a range of resolutions using both the scaling features and the anchoring and dynamic layout features that the UI system gives you.

If you have trouble achieving this, try making a mock-up of what you want your UI to look like at different resolutions and aspect ratios, then ask for tips for how to set up your UI so that it adjusts itself that way.

---
Tags: unity, unity-ui, user-interface
---


# Question
Title: Wave function runs twice every time it is called
In my game, once the player enters the room I want to start running my wave script. It should run once, then once all the enemies are dead it should run again. But it's running twice, so it always spawns two waves instead of one.

```
void Update()
{
    StartCoroutine(wavecontrols());

    enemiesalive = GameObject.FindGameObjectsWithTag("enemy").Length +
    GameObject.FindGameObjectsWithTag("enemy2").Length;
}

void enemiesSpawn()
{
    if (canspawn == true)
    {
        for (int i = 0; i < waves[nextwave].amountofenemy1; i++)
        {
            Instantiate(enemy1, Spawners[Random.Range(0, Spawners.Length)].position, Quaternion.identity);
        }

        for (int i = 0; i < waves[nextwave].amountofenemybasic; i++)
        {
            Instantiate(basicenemy, Spawners[Random.Range(0, Spawners.Length)].position, Quaternion.identity);
        }

        canspawn = false;
        nextwave++;
    }
}

IEnumerator wavecontrols()
{
    enemiesSpawn();

    if (enemiesalive == 0 && passed == true)
    {
        canspawn = true;
    }
    yield break;
}

```

# Answer
> 1 votes
There is a bunch of things not really great. Lets start with your actual question, why the wave is spawning twice.

* You are starting `wavecontrols`
* `wavecontrols` starts `enemiesSpawn`, spawns enemies and sets canspawn to false
* `wavecontrols` next checks `enemiesalive` -\> which is still 0 at this point -\> sets canspawn to true again
* `enemiesalive` gets updated in Update
* Update calls `wavecontrols`, canspawn is true and second wave gets called

Thats the flow of your spawner and the reason for calling the double spawn. Now for the things that you might want to rework.

* calling `FindGameObjectsWithTag` in Update is not great. And there is no real need to do so. Your enemiesSpawn function knows how many enemies get spawned. And all you need to include in your spawned enemy is a small piece when it gets destroyed/ killed to decrease the counter.
* `wavecontrols` does not need to be started as a Coroutine, you can simply call it directly
* your enemiesSpawn is repeating itself. What if you have another three types of enemies? Or 5? If you repeat lines of code, that is a usually a sign that you can make it better

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


# Question
Title: Animation jumps to 0 position on all axes while using AnimationCurve on x
I am currently studying animation creation on runtime. Here is my code snippet where I am moving my cube x position to 2.

```
anim = GetComponent<Animation>();
AnimationCurve translateX= null;

translateX = AnimationCurve.Linear(0f, this.transform.position.x, 2f, 2f);
animationClip = new AnimationClip();
animationClip.legacy = true;
animationClip.SetCurve("", typeof(Transform), "localPosition.x", translateX);
anim.AddClip(animationClip, this.name);
anim.Play(this.name);

```

But the problem is every time I play my scene, my object position jumps to zero position.

Why it is happening? Like I am only animating the x position then, why are other axes changing?

# Answer
> 2 votes
It's not possible for the animation system to control only one axis of the position (or the rotation, by the way). That's because the position is one single value of type Vector3. It can only be set completely.

But there is a workaround: Make the animated object the child of an empty game-object. Use the parent to control the world-position of the whole object. Now the animator only animates the *local* position, while the *global* position is controlled by the parent.

# Answer
> 0 votes
If you don't want to change y and z axis then, you have to provide the same value of these axes. As @Philipp said we can not provide single axis in position or rotation.

```
animationClip.SetCurve("", typeof(Transform), "localPosition.x", translateX);
float defaultY = this.transform.position.y;
float defaultZ = this.transform.position.z;
animationClip.SetCurve("", typeof(Transform), "localPosition.y", AnimationCurve.Linear(0, defaultY, 2f, defaultY));
animationClip.SetCurve("", typeof(Transform), "localPosition.z", AnimationCurve.Linear(0, defaultZ, 2f, defaultZ));

```

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


# Question
Title: 2d isometric map disappeared when reopening Unity project
I closed my Unity project, came back the next day and opened it, but saw this :

Instead of this :

What should I do to recover the grid instead of having that pink area ?

# Answer
Ok, the pink tiles came from a Tile Palette which was not anymore in the project, erasing them with a tile from a Tile Palette which was still in the project solved that issue.
> 1 votes

---
Tags: unity, 2d, isometric
---


# Question
Title: How can I enforce single instancing for my HoloLens applications?
I am searching for a solution to avoid multiple instances of my application in HoloLens. How can I detect that there's one already running, and stop the new instance?

I am new to Unity and application development, I read that it's an OS problem (operative system) and it's not related to HoloLens? Does anyone have a solution?

# Answer
You can force Unity to run a single instance of your application by ticking `Force Single Instance` in `Edit > Project Settings > Player > Resolution and Presentation`
> 1 votes

---
Tags: unity, c#, vb.net, hololens
---


# Question
Title: Coding a left/right object movement C# script for android phones in unity
I have 2 spheres and a cube on screen.

I'm experimenting to make a 'left/right movement script' for the cube so that when I touch the left sphere, the cube moves left-wards and when I touch the right sphere, the cube moves right-wards.

I have 2 scripts. I have attached **SphereLeft.cs** to left sphere and **SphereRight.cs** to right sphere.

Any pointers on how to achieve this ?

# Answer
Here we are just one script, assign it to the cube ***TargetSlideControl.cs***

```
using UnityEngine;
using System.Collections;

public class TargetSlideControl : MonoBehaviour {

public int SPEED = 1;
public Transform leftTrigger;
public Transform rightTrigger;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    // If Mobile
    if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer){
         if(Input.touchCount > 0) {
           checkTouch(Input.GetTouch(0).position);
         }
     }else if(Application.platform == RuntimePlatform.WindowsEditor){ // Else if Desktop
         if(Input.GetMouseButton(0)) {
           checkTouch(Input.mousePosition);
         }
     }
}

private void checkTouch( Vector2 pos ) {
    Ray ray = Camera.main.ScreenPointToRay( pos );
    RaycastHit hit;
    if(Physics.Raycast(ray, out hit)){
        if(hit.collider.transform  == leftTrigger) {
            SlideLeft();
        } else if(hit.collider.transform  == rightTrigger){
            SlideRight();
        }
    }
 }

// Call Translate on this transform passing SPEED * Direction * deltaTime

public void SlideLeft() {
    this.transform.Translate( SPEED * Vector3.left * Time.deltaTime, Space.World );
}

public void SlideRight() {
    this.transform.Translate( SPEED * Vector3.right * Time.deltaTime, Space.World );
}
}

```

Assign the spheres in the editor to the TargetSlideControl script:

ENJOY!
> 1 votes

# Answer
# This is a simple guessing game

import random

# Generate a random number between 1 and 10

secret\_num = random.randint(1, 10)

# Ask the user to guess the number

guess = int(input("Guess a number between 1 and 10: "))

# Keep asking the user to guess until they get it right

while guess != secret\_num: if guess \< secret\_num: print("Too low, try again.") else: print("Too high, try again.") guess = int(input("Guess a number between 1 and 10: "))

# If they get it right, print a congratulations message

print("You got it! The secret number was", secret\_num)
> -2 votes

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


# Question
Title: Best moment to trigger sounds in 2D games
As a test project I am creating a 2D tower deffense game in Godot (C#). My question is about best practices in the industry on how to manage sound effects.

One of the enemies is represented by an Orc that is an SpriteAnimation with different animations like idle, walk, run or attack. Right now, after falling from sky, the enemy is "running" to the tower until there's a collision with it and then it starts the "attack" animation which is simply a hammer hit. My question is about the sound associated to the hit, should it be played when the animation ends? is there any other practice over there to handle this?

# Answer
The general rule of thumb is not to annoy the player with sounds. That's why in tower defense games enemy characters don't have walking sounds(just imagine the ammount of noise the army would create). About your question. I would play the sound when the collision had happened. This way the player will know that the orc is braking/broke the tower. To implement this try raising an event when collision happens, in the godot case try using signals(https://godotengine.org/article/csharp-ios-signals-events).
> 1 votes

---
Tags: 2d, game-design, godot, sound, sound-effects
---


# Question
Title: Porting Plugins from UE5.0 to UE5.1 source build causes DLL Registration Errors
I built UE5.1-Main from source successfully. I'm trying to port my UE5 marketplace plugins, but when I launch the editor I get these errors for all my ported plugins.

I suspect it might have something to do with .NET6.0 SDK (which I had to install to build the source). Maybe I installed it incorrectly. Or perhaps I'm missing some other visual studio component. I followed this guide to get it set up using Visual Studio Community 2019.

Any ideas about what's going on here and how to fix it?

# Answer
I had the same problem when trying to compile `BlueprintAssist` in `Engine/Plugin/Marketplace`; this used to work in UE4, but it's not working for me in UE5.

Everything started working when I moved the plugin into `Game/Plugins`. I'd try moving it if you can.
> 2 votes

---
Tags: unreal-4, unreal, .net, unreal-5, source-code
---


# Question
Title: How to make backface culling work correctly in both orthographic and perspective projection?
I have a software renderer that I've been building. I just implemented backface culling with the Go code below.

This works with Perspective Projection. But I plan to use orthographic projection. When switching to orthographic projection, the triangles that should be culled are culled longer than they should be.

I'm trying to figure out if I have a bug in my code or if I'm just not taking into account the projection.

My pipeline is basically:

1. Multiply each vertex by the world matrix
2. Backface cull triangles with the code below
3. Multiply each remaining vertex by the projection matrix

I've seen something about projecting *before* culling. I tried that though and it didn't help.

Is there something I'm not calculating to compensate for orthographic projection?

Perspective Projection (correct)

Orthographic Projection (incorrect)

```
// Culling logic
a, b, c := vertices[0], vertices[1], vertices[2]
ab := b.Sub(a)
ac := c.Sub(a)

normal := ab.Cross(ac).Normalize()
cameraRay := cameraPosition.Sub(a)

visibility := normal.Dot(cameraRay)
if visibility < 0.0 {
    // don't render this triangle
}

```

# Answer
> 19 votes
Backface culling is not done based on normals. You can backface cull even meshes that have no normal information.

Backface culling is done using the winding order of the vertices' post-projection positions. That is, as you trace the shape of the triangle on the screen in the order the vertices were given, do you end up travelling around its perimeter clockwise or counter-clockwise?

```
sign = ab.x*ac.y - ac.x*ab.y;

```

The sign will be positive for faces wound in one direction, and negative for faces wound in the other direction.

This is similar to the cross product you're using to compute the normal, but notice that it uses only information in the image plane, no depth (z), and is insensitive to the position of the camera.

# Answer
> 21 votes
The reason that your culling only works with perspective projection is that you are checking the angle (via dot product) between *the ray from the camera position to the object* and the triangle's normal. This works perfectly with perspective projection, but it's the wrong ray to compare for orthographic.

In general, the ray that you should compare against the triangle's normal (if you want to do it this way and not via winding order) is the ray which *occupies a single point on screen* — the ray which is oriented in the direction which the projection, whatever it is, flattens out of existence.

For perspective projection, all of those rays intersect at a point, typically considered the camera position, and you're correctly computing the relevant ray.

But for an orthographic projection, all of those rays *are parallel* and do not intersect.

(In a sense, an orthographic camera *does not have a unique point* which can be counted as its position; rather, it has a rectangle corresponding to the viewport. The point you consider its position only matters for what happens if you rotate the camera; without a difference in rotation, the relative position of a projected point to another projected point is always the same. Choosing a different center point just translates/crops the whole image.)

If you want to implement culling in the way you currently have working for perspective, but specifically for an orthographic projection, then compute the vector which is the camera's *forward direction* (and is the same regardless of where the triangle is on the screen), and use that in the dot product with the triangle normal. The camera's position will not be used — only its rotation.

---
Tags: 3d, rendering, projection, culling, go
---


# Question
Title: How do I design a "Chores" or "Errands" system?
I have a number of entities running around in my game, and I am running into a headache trying to design and implement a system for them to both generate and assign the tasks. More than anything else, I think I'm running into a vocabulary issue, as it's very hard to research the system I am trying to design. At any rate, here's the terminology that *I'm* using.

**Entity**

Hopefully self-explanatory

**Chore / Errand**

Something that an Entity can perform in game, such as "move these crates from A to B", or, "Perform Y at building Z until X". Chores have priority (some are more important), exclusivity (only one entity can be performing a specific chore), and (potentially) requirements (only entities with Forklift certification can perform this job).

This question has an excellent example, despite being unrelated to my personal difficulties.

---

The main points of concern for me are Chore generation and assignation. In both instances, can see a case for either a single centralized hub which can respond to a "getNextTask" function (such as Prison Architect's "Jobs" list), or an event-based, decentralized approach where an entity sends a "LookingForWork" event, and the individual chores themselves respond as available (or not!) depending on the event parameters.

This gets geometrically more complex when you start to consider that tasks can be interrupted, paused, resumed, or cancelled.

This is (clearly) not a novel problem space, but I'm not sure how to further approach it. What are the advantages or disadvantages of the centralized or decentralized approach -- and are there any other common possibilities that I've yet to think of or encounter?

# Answer
> 0 votes
Centralized lists are a timesaver - instead of querrying each jobgiver/workdoer you get them registered for a quick access/sort/filter.

In that light, I'd frame your choice a bit differently - "**jobs list** vs. **workers list**".

From that, having both lists, you can naturally evolve into a "matchmaking" system, that will pick best jobs for most suitable workers (e.g. with Hungarian Algorithm that does optimized matching). Simplest approach is - if you have more jobs that workers, let workers pick jobs they prefer. Or vice versa.

---
Tags: architecture, ai, entity
---