# Question
Title: How can I project a 3D point onto a 3D line?
Let's say I have a line defined by two points, `A` and `B`, both in the form `(x, y, z)`. These points represent a line in 3D space.

I also have a point `P`, defined in the same format, that isn't on the line.

How would I calculate the projection of that point on to the line? I'm aware of how to do this in 2D but 3D seems to have bugger all resources on it.

# Answer
> 44 votes
You simply need to project vector `AP` onto vector `AB`, then add the resulting vector to point `A`.

Here is one way to compute it:

```
A + dot(AP,AB) / dot(AB,AB) * AB

```

This formula will work in 2D and in 3D. In fact it works in all dimensions.

# Answer
> 7 votes
Here's a fast and easy way to do it in python:

```
from numpy import *
def ClosestPointOnLine(a, b, p):
    ap = p-a
    ab = b-a
    result = a + dot(ap,ab)/dot(ab,ab) * ab
    return result

```

Use floats; If your vectors contain integers the division will be an integer division, and the results will be incorrect.

# Answer
> 2 votes
Just for an explanation about the formula from Sam Hocevar:

1. If A,B are on the line, then the vector

$$\vec{u} = \vec{AB} / \left\\|\vec{AB}\right\\| $$

is the unit vector for this line (don't forget that \\$\left\\|\vec{AB}\right\\| = \sqrt {\vec{AB} \cdot \vec{AB}} \\$ or respectively \\$\vec{AB} \cdot \vec{AB} = \left\\|\vec{AB}\right\\|^2\\$).

The line equation follows:

$$k \cdot{\vec{u}} + A $$ for any \\$k\\$ scalar.

Then when projecting P on this line, the projected point \\$I\\$ is defined as perpendicular to the line's unit vector, that is:

$$ \vec{IP} \cdot \vec{u} = 0 $$ and $$ I = \vec{u} \cdot \left\\|\vec{AI}\right\\| + A $$

Since projecting P on the line is the dot product of \\$\vec{AP}\\$ and \\$\vec{AB}\\$, we can compute:

$$ \left\\|\vec{AI}\right\\| = \vec{AP} \cdot \vec{AB} / \left\\|\vec{AB}\right\\| $$

since \\$\vec{AP} = \vec{AI} + \vec{IP}\\$ and \\$\vec{IP} \cdot \vec{u} = \vec{IP} \cdot \vec{AB} = 0\\$, then:

$$ \vec{AP} \cdot \vec{AB} = \vec{AI} \cdot \vec{AB}=\vec{AI}\cdot\vec{u} \*\left\\|\vec{AB}\right\\| = \left\\|\vec{AI}\right\\| * \left\\|\vec{AB}\right\\|$$

That means that only the colinear component of \\$\vec{AP}\\$ to \\$\vec{AB}\\$ is participating to the scalar result

Which finally gives:

$$ \begin{matrix} I\_{x} \\ I\_{y} \\ I\_{z} \end{matrix} = \begin{matrix} A\_{x} \\ A\_{y} \\ A\_{z} \end{matrix} + \begin{pmatrix} P\_{x} - A\_{x} \\ P\_{y} - A\_{y} \\ P\_{z} - A\_{z} \end{pmatrix} \cdot \begin{pmatrix} B\_{x} - A\_{x} \\ B\_{y} - A\_{y} \\ B\_{z} - A\_{z} \end{pmatrix} \cdot \begin{pmatrix} u\_{x} \\ u\_{y} \\ u\_{z} \end{pmatrix} / \left\\|\vec{AB}\right\\|$$

This is the formula from Sam above.

# Answer
> 0 votes
on this one (i cannot cooment)

```
    ap = p-a
    ab = b-a
    result = a + dot(ap,ab)/dot(ab,ab) * ab
    return result

```

If you first make the "versor" of ab you do not need dot(ab,ab) right? or you just do the normal somehow you can rewrite as:

```
    ap = p-a
    ab = normal(b-a)
    result = a + dot(ap,ab) * ab
    return result

```

(I learned it with versors (normalized vectors) so was kind of weird.

---
Tags: mathematics, geometry
---


title: Get object rotation around the x axis

text:
# Question
Title: Get object rotation around the x axis
I have an object which can be rotated at 0, 90, 180, 270 degrees. I am using this to get the rotation data:

```
transform.eulerAngles.x

```

However that code keeps ignoring 180 degrees and instead shows 0 or some weird calculation which is basically zero (smth like -93+2323232-4)

I have read about quaternions, eulers and unity rotations in general and every time I curse my life when I have to work with unity rotations...

Is there any human readable and efficient/easy way to get the exact rotation the object has ? Or at least to get these values from 0 to 360.

# Answer
Remember, Euler angles are a fiction, made for ease of data input in the scene editor. They're not stored under the hood, so when you read an Euler angle triplet, it's converted on the fly from the actual stored quaternion representation.

The quaternion will always give you consistent behaviour to calculate with - that's why we use them. The conversion from an orientation to Euler angles is arbitrary - many different Euler angle triplets correspond to the same orientation, and the engine has to pick wrap-around points somewhere, quite likely not where you want them.

So it's best to *never* use `.eulerAngles` as the input to a calculation. Treat this field as write-only. Never read with an aim to modify the value or make decisions based on the value, or you are extremely liable to make a mistake.

If you have an object that you only ever rotate around the x axis, you can compute its rotation about that axis by checking which direction its `.forward` vector is pointing:

```
float GetXDegrees(this Transform t) {
    // Get the angle about the world x axis in range -pi to +pi,
    // with 0 corresponding to a 180 degree rotation.
    var radians = Mathf.Atan2(t.forward.y, -t.forward.z);

    // Map to range from 0 to 360 degrees,
    // with 0 corresponding to no rotation.
    return 180 + radians * Mathf.Rad2Deg;
}

```
> 1 votes

---
Tags: unity, rotation, quaternion, euler-angles
---


# Question
Title: How to change quaternion when flipping X axis?
For a given animation with the set of 3D coordinates of every joint and corresponding global rotations quaternions `Q(X, Y, Z, W)` in right-hand coordinates (Y-up, X-left, Z-forward) - pic. I want to change axis X to be consistent with Unity (Y-up, X-right, Z-forward).

For coordinates it is obvoius: `X' = -X` and works as expected.

For rotations in quaternions assign I probed different options from other sources:

* `X, -Y, -Z, W`
* `-X, Y, Z, W`
* `-X, Y, Z, -W`

So, what math behind flipping X axis and how can I achieve this transformation?

# Answer
`X, -Y, -Z, W` \<-- This one is correct.

First you replace the axis you have (X) with the axis you want (-X), giving you:

`-X, Y, Z, W`

Then, since you've flipped an odd number of axes, you're in a mirror image universe with reversed handedness, so the sign of the angle needs to change too. That means negating `X`, `Y`, and `Z`, giving the final result:

`X, -Y, -Z, W`

I've shown these steps in a few prior answers, so remember to do a search first to find solutions even faster than writing a post and waiting for a reply.
> 1 votes

---
Tags: unity, 3d, mathematics, animation, quaternion
---


# Question
Title: Splitting large 3D world in additively-loaded Scenes vs using Addressable Prefabs or Bundles
I'm working on a 3D game with a large open world. It will naturally need to stream chunks. When you look at existing streaming solutions in the Asset Store, you can see that their approach is building the chunks as Scenes, and then additively load them.

That's fine, but in my mind it seems more logical to create and load the chunks as Addressable Prefabs, or perhaps, as individual AssetBundles. Yet, those assets seem to have been quite deliberate in this design decision. I've tried asking their developers, but their answers have been vaguely secretive as if there's some business logic to protect (e.g. "bundles have limitations").

I have come across this question, where the asker appears to be almost in the same situation: Unity prefab object limitations \- however, they seem to be more concerned about the performance impact or the complexity of having thousands of objects inside a prefab (I don't believe this is an issue - to me a scene is virtually a prefab, except it has lightmapping features).

---

What are the technical differences (if any) between splitting the 3D open world into additively-loaded Scenes, as opposed to splitting the world into Addressable prefabs / AssetBundles?

As mentioned, lightmapping is the only notable difference that comes to my mind. Other than that, is there another technical reason developers appear to deliberately go for additive scene loading that I'm missing?

# Answer
> 2 votes
You can preload scenes, but you cannot preload prefabs. If you are streaming chunks, it will be very useful to preload the chunks you expect to load, and then finalize the load when you are ready. Or unload them if you end up not needing them.

Technically, you can get hacky, and preload prefabs. But that's gross.

Here are some more details on scene preloading: Preload scene in unity

---
Tags: unity, 3d, optimization, streaming-assets
---


# Question
Title: How to rotate parent object to align child rotation with a separate game object?
I have attached two images with the desired start and end positions.

The Brown Circle is the target rotation. The Orange Square is the parent (the black dot is the pivot point) and the Blue Rounded Square is the child.

How would I calculate the rotation of the parent to align the child to the target rotation?

# Answer
> 0 votes
Assuming you have a bearing angle for each object relative to its parent, this is just subtraction.

We want:

```
parent_angle + child_angle = target_angle

parent_angle = target_angle - child_angle

```

So in your example, the child is rotated about 45 degrees clockwise from its parent - call that -45 - and the target is unrotated at 0 degrees, so that gives:

```
parent_angle = 0 - (-45)
             = +45

```

So the parent needs to be rotated 45 degrees counter-clockwise to compensate for the child's rotation and match it to the target.

This expression can wrap around to values outside the -180 to 180 or 0 to 360 or -pi to pi etc. range you might be using, but you can wrap the result with an angle difference function, if that matters for your use case. Prior Q&A covers how to write such a function, if your math library does not offer one built-in.

# Answer
> 0 votes
I think this might be one of those things that seems trickier than it really is. Since rotations are rigid transformations of space, all vectors are affected equally no matter where in the plane they are. What that means is that we can completely ignore the fact that the pivot point is the parent position, and just think about how much the child needs to rotate.

And so, all you need to do is find the angle between the current orientation and the desired one. For example, the angle between the child's horizontal vector and the target's horizontal vector. You then rotate the parent by that amount, and done!

An important note is that you need to express both vectors in the same coordinate system. So, if the child is expressed in the local space of its parent, you might need to use a transformation matrix or something. The exact steps will of course depend on how all this information is made available in whatever tool you are using.

---
Tags: rotation, trigonometry
---


# Question
Title: Adding second light hides the first on iOS unless quality is set to high
When I add a light in the scene then the light will show on the ground, but when I add a second light, neither of them show on the ground.

One light:

Add second light:

My light is a spot light, and it's not working on the iOS device, but the PC is working fine.

I found this is related to quality settings: when I change to high, it shows both lights.

Is there a way to show two lights while using medium quality?

# Answer
> 0 votes
Renderer - pixelLightCount , Medium is 1 and if you want more light show on the ground then set the number to more than one.

---
Tags: unity, lighting, ios
---


title: Unity Snap to grid not exact

text:
# Question
Title: Unity Snap to grid not exact
I just noticed that unities snap-to-grid feature results in a strange behavior. The results are not precise. My geometry is comprised of 32x32 pieces. They appear to snap fine to the grid, but when I look at the location at the top right, it does not show a correct increment of units. There's evidently some measure of rounding happening. Here's a picture:

Does anyone know why unity's snap-to-grid feature isn't precise? I can get past this from a game dev standpoint, because movement in my game is not going to be grid based. However, I would really like the results of snap to grid to be more precise.

Thanks.

# Answer
> 1 votes
I was having a similar problem with a grid of 0.5 and I found out that it's a problem with the tiny input field for the grid settings. When I try to enter 0.5, it actually puts 0.50001 (this is because it interprets my initial zero as my desired input, when is an impossible grid division, so it defaults to 0.00001) then typing the .5 after the zero will replace the first zero after the point with 5, resulting in 0.50001, however, the input field is so small that the tiny one at the end of the number was cut off, so I didn't see it, and I didn't think much of the two zeroes after the 5 which I could see.

I'm not sure if you're having the same problem since you're using a 32 grid, but maybe there is just a hidden decimal back there. I hope this can help someone.

---
Tags: grid
---


# Question
Title: Unreal Engine 5 does not use shared VRAM
I have a HP Pavilion laptop with an integrated Intel Iris GPU, as well as a dedicated Nvidia Geforce MX 450. The Nvidia has a dedicated 2 GB VRAM, and the the two cards share an additional 16 GB of memory. Unreal Editor only detects the 2 GB, and claims being overbudget while using just 3 GB of video memory. This makes the editor borderline unusable, with at most 10 FPS. The computer has an Intel Core i5 with 32 GB RAM, so these are not an issue. Is there any way to make UE5 use all available resources?

# Answer
"Shared" video RAM is usually most relevant for integrated GPUs, which don't have their own dedicated memory. Ideally, your dedicated GPU should not need to access shared memory, because shared memory is very slow and terrible for performance. In particular, the MX 450 doesn't support shared memory (refer to spec table here).

I haven't worked with Unreal, but it sounds like the engine is saying that you are using all 2GB of dedicated VRAM + 1GB of additional memory that is stored in system RAM and probably has to be swapped back and forth between system RAM and the GPU. You might be able to fix this issue by adjusting your texture streaming settings; a web search for 'unreal memory overbudget' seems to return many relevant results. However, for the best long-term results, you should probably start saving up for a new laptop. The MX450 is an entry-level GPU from two years ago and 2GB of VRAM is pretty skimpy by today's standards.
> 2 votes

---
Tags: performance, unreal, unreal-5
---


# Question
Title: Eliminate bouncing when switching/sticking to a different surface
I am following this tutorial to make a `KinematicBody2D` align to the surfaces below it.

When switching from one surface to another, the character bounces until it corrects/aligns its rotation, as shown here:

How can I eliminate the bouncing?

I've uploaded a minimal version of the project on GitHub.

The project setup looks like this:

And this is the player script:

```
extends KinematicBody2D

export (int) var speed = 600
export (int) var jump_speed = -600
export (int) var gravity = 1000

var velocity := Vector2.ZERO

export (float, 0, 1.0) var friction = 0.1
export (float, 0, 1.0) var acceleration = 0.25

var last_collission = null;

func get_input():
    var dir = 0
    if Input.is_action_pressed("ui_right"):
        dir = 1
        $RightRay.enabled = true
        $LeftRay.enabled = false
    if Input.is_action_pressed("ui_left"):
        dir = -1
        $RightRay.enabled = false
        $LeftRay.enabled = true
    if dir != 0:
        velocity.x = lerp(velocity.x, dir * speed, acceleration)
    else:
        if !is_jumping:
            $RightRay.enabled = false
            $LeftRay.enabled = false
        velocity.x = lerp(velocity.x, 0, friction)

var is_jumping = false
func _physics_process(delta):
    get_input()
    velocity.y += gravity * delta
    var snap = transform.y * 128 if !is_jumping else Vector2.ZERO
    velocity = move_and_slide_with_snap(velocity.rotated(rotation),
                    snap, -transform.y, true, 4, PI/3)
#   velocity = velocity.linear_interpolate(velocity.rotated(-rotation), 0.8)
    velocity = velocity.rotated(-rotation)

    if is_on_floor():
#       velocity.x += speed * delta
        if !is_jumping :
            rotation = get_floor_normal().angle()  + PI/2

        is_jumping = false

        if Input.is_action_just_pressed("ui_accept"):
            is_jumping = true
            velocity.y = jump_speed
            $RightRay.enabled = true
            $LeftRay.enabled = true

    if  $RightRay.is_colliding():
        rotation =  $RightRay.get_collision_normal().angle() + PI/2
        $RightRay.enabled = false
        $LeftRay.enabled = false

    if  $LeftRay.is_colliding():
        rotation =  $LeftRay.get_collision_normal().angle() + PI/2
        $RightRay.enabled = false
        $LeftRay.enabled = false

```

# Answer
> 4 votes
The problem is that you are using `velocity` as the node's local velocity instead of the global velocity. That is to say, the reference system of the velocity is the local coordinate system of the node. That is, the velocity direction will be affected by the node's *rotation*:

```
velocity = move_and_slide_with_snap(velocity.rotated(rotation),snap, -transform.y, true, 4, PI/3)
velocity = velocity.rotated(-rotation)

```

This makes it easy to switch between different gravity reference systems, but at the moment of switching, the speed also rotates, which leads to "bouncing".

The solution depends on the effect you want. Sometimes we think that a certain motion phenomenon is "correct" because it more or less conforms to the motion law of the real world: objects have inertia. Switching the gravity reference frame is a pure game mechanism. So I think of two solutions: clear the speed and retain the speed.

Clear the speed:

```
if  $RightRay.is_colliding():
    rotation =  $RightRay.get_collision_normal().angle() + PI/2
    velocity = Vector2.ZERO
    $RightRay.enabled = false
    $LeftRay.enabled = false

if  $LeftRay.is_colliding():
    rotation =  $LeftRay.get_collision_normal().angle() + PI/2
    velocity = Vector2.ZERO
    $RightRay.enabled = false
    $LeftRay.enabled = false

```

Retain the speed:

```
if  $RightRay.is_colliding():
    var rotation_pre = rotation
    rotation =  $RightRay.get_collision_normal().angle() + PI/2
    velocity = velocity.rotated(rotation_pre-rotation)
    $RightRay.enabled = false
    $LeftRay.enabled = false

if  $LeftRay.is_colliding():
    var rotation_pre = rotation
    rotation =  $LeftRay.get_collision_normal().angle() + PI/2
    velocity = velocity.rotated(rotation_pre-rotation)
    $RightRay.enabled = false
    $LeftRay.enabled = false

```

Result:

---
Tags: 2d, physics, godot
---


title: Rust lang and Cheaters

text:
# Question
Title: Rust lang and Cheaters
So I started to learn Rust for personal usage, i am Back-end Node.js dev originally.

And I see that people often say Rust is a very secure solution because of memory management. In theory games/engines written in Rust could be a problem to cheaters?

I don't have a big knowledge of how people make cheats for games. I just guessing that it might be because somehow you can change Heap or something like that.

I have a few ideas for my first future game and want to make it secure without doing it fully server-side.

# Answer
When people claim "Rust is secure", then what they mean is that Rust makes it very difficult for developers to create bugs which could result in security vulnerabilities like buffer overflows or use-after-free. Those are the kind of vulnerabilities which can be exploited by attackers who send malicious files or network messages in order to attack the systems of other people.

But those aren't the vulnerabilities cheaters use. They are attacking *their own* system, so they have no need for exploits like that.

Cheaters use techniques like:

* Patching the game executable
* Injecting code into the game executable by replacing DLL files
* Replacing assets
* Reading and changing process memory
* Simulating inputs

Rust does nothing which makes any of that any easier or harder to do.

One argument you *could* make is that Rust is relatively new, so the tools to reverse-engineer applications written in Rust are less mature than for languages like, say, C++ or C#. But that's a security-by-obscurity argument which can easily change when people start building those tools.

So tl;dr: No, using Rust does not prevent any cheating.
> 5 votes

---
Tags: anti-cheat, rust
---


# Question
Title: For what to use PlayFab Player Data (Title), and Player Data (Publisher)?
I started using PlayFab. Could someone help me and explain with small example for what to use Player Data (Title), and Player Data (Publisher), and for what not to use?

# Answer
First, it might be good to clarify the difference between player data & player publisher data:

> **Player data** is player information that is specific to a game title. It should be used for title-specific information - such as saving your player's position in a dungeon, or other game-specific data.
>
> **Player *Publisher* data** is data associated with the player account, as opposed to the player account plus the title. It is used to save information about a player relevant to all titles in your studio (which may also contain title-specific information, for purposes of cross-title rewards).

And as noted later on:

> They are both dictionaries mapping a string to a JSON blob (or other arbitrary string value).

Based on your question usage, it *seems* like you are asking about **player data** called `title` & `publisher`. Based on the documentation, that means for some game XYZ, you would use those mappings to store the title for XYZ and the publisher for XYZ. Sometimes these are referred to in the documentation as Key/Value Pairs or KVPs.

The definition for player data says it hold game title specific information such as the player's position. But there could be more than one game that uses player position. As mentioned here in the documentation, the title establishes the current scope, which is to say makes sure that you are referring to the data for the intended game.

That same documentation also explains that the publisher field is used for managing account data across several titles. For example, if a publisher has multiple games, they might want to encourage players of one title to purchase & play your other titles. In that case you could grant a reward for playing multiple titles. By consistently using the publisher KVP, you can more easily query for the necessary information to see if a reward should be given. The documentation also gives a link to an example project using simple in-game cross promotion where players get rewarded for participating in more than one of your games.
> 1 votes

---
Tags: playfab
---


# Question
Title: Efficient calculation of billboard sprite transformations
I'm currently adding a billboard mode to animated sprites and static sprites in my 3D engine.

The code below works fine, but I want to know if a more optimized solution exists. I've heard about another method using the transpose the view matrix, but this make some weird things in my case.

```
getModelMatrix() {
  let matrix = Utils.MAT4_IDENTITY();
  matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_TRANSLATE(this.position[0], this.position[1], this.position[2]));

  if (this.billboardMode) {
    let viewMat = view.getCameraViewMatrix();
    matrix = Utils.MAT4_MULTIPLY(matrix, view.getCameraMatrix()); // used to cancel the view camera matrix multiplication
    matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_TRANSLATE(viewMat[12], viewMat[13], viewMat[14])); // but keep position !

    // or just do that, but not working
    // matrix = Utils.MAT4_MULTIPLY(matrix, transpose(view.getCameraViewMatrix()));
  }

  matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_ROTATE_Y(this.rotation[1]));
  matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_ROTATE_X(this.rotation[0])); // y -> x -> z
  matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_ROTATE_Z(this.rotation[2]));
  matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_SCALE(this.scale[0], this.scale[1], this.scale[2]));
  matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_SCALE(1 / this.pixelsPerUnit, 1 / this.pixelsPerUnit, 0));
  matrix = Utils.MAT4_MULTIPLY(matrix, Utils.MAT4_TRANSLATE(-this.offset[0], -this.offset[1], 0));
  return matrix;
}

```

What is the common way to transform a sprite to billboard ?

# Answer
You don't actually need to transform the sprite in world space at all. You can project the position of the sprite into view space (with the view matrix), and then generate the corner vertex positions in view-space directly (simply by setting their xy coordinates). The units will be the same as those in world space (e.g. meters). You can apply any scaling/rotation you need in this conveniently view-aligned coordinate system, and then simply apply the usual projection matrix to the resulting vertices as you would with any other model.
> 1 votes

---
Tags: 3d, mathematics, javascript, matrix, optimization
---


title: Creating a countdown Timer in Unity

text:
# Question
Title: Creating a countdown Timer in Unity
I want to create a countdown timer in a Unity game I am creating. Up until now my game was running for a specific time but I was using `InvokeRepeating` to end the game after the set time.

But now I want to display the time left in a GUI text. One approach could be to use `InvokeRepeating` again but this time call it every second to decrement the timer. With this approach though it would mean do extra calculations for when a minute passes in order to display time appropriately and not just display the whole time in seconds.

Is there a different approach? Does Unity have any timers built in? Also which is the more efficient method?

# Answer
> 7 votes
Alternatively, you could use System.Timers.Timer which is probably the most performant of any solution. The following example shows a countdown for 100 seconds.

```
System.Timers.Timer LeTimer;
int BoomDown = 100;
void Start ()
{
    //Initialize timer with 1 second intervals
    LeTimer = new System.Timers.Timer (1000);
    LeTimer.Elapsed +=
        //This function decreases BoomDown every second
        (object sender, System.Timers.ElapsedEventArgs e) => BoomDown--;
}

void Update ()
{
    //When BoomDown reaches 0, BOOM!
    if (BoomDown <= 0)
        Debug.Log ("Boom!");
}

```

# Answer
> 3 votes
Coroutines are you friend I think on this one...

http://docs.unity3d.com/Manual/Coroutines.html

Here is an example:

```
void Start () {
    StartCoroutine ("Countdown", 10);
}

private IEnumerator Countdown(int time){
    while(time>0){
        Debug.Log(time--);
        yield return new WaitForSeconds(1);
    }
    Debug.Log("Countdown Complete!");
}

```

# Answer
> 1 votes
The code below might look complicated but once you understand it, you will be able to see its power of `reusablity`. (it's kind of `countup` but further down you will understand how to make it `countdown` if you understand how the code works)

```
public IEnumerator Count(
    float targetTime,
    System.Action<float> receiveTimeElapsed = null,
    System.Func<bool> actionCondition = null,
    System.Action conditionalAction = null,
    System.Action onCountStart = null,
    System.Action onCountEnd = null)
{
    onCountStart?.Invoke();

    float timeElapsed = 0f;
    receiveTimeElapsed?.Invoke(timeElapsed);

    while (timeElapsed < targetTime)
    {
        if (actionCondition != null && actionCondition.Invoke())
            conditionalAction?.Invoke();

        yield return null;

        timeElapsed += Time.deltaTime;

        receiveTimeElapsed?.Invoke(timeElapsed);
    }

    if (actionCondition != null && actionCondition.Invoke())
        conditionalAction?.Invoke();

    onCountEnd?.Invoke();
}

private float _timeElapsed;
private int _count;

private void Awake()
{
    this.StartCoroutine(
        this.Count(
            5f,
            (timeElapsed) =>
            {
                this._timeElapsed = timeElapsed;
                Debug.Log("Time Elapsed: " + this._timeElapsed);
            },
            () => { return this._timeElapsed >= (this._count + 1); },
            () =>
            {
                this._count++;

                Debug.Log("Countdown: " + this._count);
            },
            () => { Debug.Log("Countdown: " + this._count); },
            () => { Debug.Log("On countdown end"); }
        )
    );
}

```

If you think that it's too much or you may not need all this checking for null. To simplify the method you could create a similar methods that will do the same but without some actions.

But I would optimize only when it hits the performance, though, I like early optimization. This one is not the case as it's not intended to be used 1000000 times per frame. As well as removing null checks and some actions would be a micro-optimization.

Also you can always add more actions, for while loop condition check and for the way time elapsing is calculated.

For example, add `getElapsingValue`:

```
public IEnumerator Count(
    float targetTime,
    System.Func<float> getElapsingValue,
    System.Action<float> receiveTimeElapsed = null,
    System.Func<bool> actionCondition = null,
    System.Action conditionalAction = null,
    System.Action onCountStart = null,
    System.Action onCountEnd = null)
{
    onCountStart?.Invoke();

    float timeElapsed = 0f;
    receiveTimeElapsed?.Invoke(timeElapsed);

    while (timeElapsed < targetTime) // You want to add func here to make it more scalable.
    {
        if (actionCondition != null && actionCondition.Invoke())
            conditionalAction?.Invoke();

        yield return null;

        timeElapsed += getElapsingValue.Invoke();

        receiveTimeElapsed?.Invoke(timeElapsed);
    }

    if (actionCondition != null && actionCondition.Invoke())
        conditionalAction?.Invoke();

    onCountEnd?.Invoke();
}

private float _timeElapsed;
private int _count;

private void Awake()
{
    this.StartCoroutine(
        this.Count(
            5f,
            () => { return Time.deltaTime; },
            (timeElapsed) =>
            {
                this._timeElapsed = timeElapsed;
                Debug.Log("Time Elapsed: " + this._timeElapsed);
            },
            () => { return this._timeElapsed >= (this._count + 1); },
            () =>
            {
                this._count++;

                Debug.Log("Countdown: " + this._count);
            },
            () => { Debug.Log("Countdown: " + this._count); },
            () => { Debug.Log("On countdown end"); }
        )
    );
}

```

To actually take `countdown` value you need to edit the method. Or you could simply do this `this._countdown - this._count` which will give you the desired value anyway.

# Answer
> 1 votes
This seemed a simple solution: you can use st.Reset() etc as you need in your own code.

```
[SerializeField] private TextMeshProUGUI countDownDisplay;
Stopwatch st = new Stopwatch();

void SomeEvent() {
    st.Start();
}

void Update()
{
    if (st.IsRunning)
    {
        int secondsUntilDestructSequence = 5;
        int elaspedSeconds = Mathf.RoundToInt((st.ElapsedMilliseconds / 1000) % 60f);
        int secondsRemaining = secondsUntilDestructSequence - elaspedSeconds;
        countDownDisplay.text = "Countdown remaining: " + secondsRemaining;
        if (secondsRemaining==0) Debug.Log("Game Over");
    }
}

```

# Answer
> 0 votes
```
[SerializeField] private Text _textTimer;

[SerializeField] private sbyte _seconds;
[SerializeField] private sbyte _minutes;
[SerializeField] private sbyte _hours;

// Start is called before the first frame update
void Start()
{
    StartCoroutine(Timer());
}

IEnumerator Timer()
{
    while(true)
    {
        _seconds--;

        if(_seconds < 0)
        {
            _seconds += 60;
            _minutes--;
        }

        if (_minutes < 0)
        {
            _minutes += 60;
            _hours--;
        }

        _textTimer.text = $"{_hours:D2}:{_minutes:D2}:{_seconds:D2}";

        if (_seconds == 0 && _minutes == 0 && _hours == 0)
            StopAllCoroutines();

        yield return new WaitForSeconds(1);
    }
}

```

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


# Question
Title: How to create a slideshow of Images in 2D game without pressing buttons
I want to make a slide of images that change automatically by a timer without pressing any button for example every 5 seconds the image changes to another one. I have a script but it only changes them when pressing a button I looked everywhere but I found no info about how to do it with time instead of sliding buttons.

this is the script I'm using now:

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

public class Slidescript : MonoBehaviour
{
    //All _slides in the project, minus the _fadeSlide
    [SerializeField]
    private List<Transform> _slides = default;

    //The panel that overlays all _slides and changes from clear to black
    [SerializeField]
    private Image _fadeSlide = default;

    [Header("Config Values")]
    [SerializeField, Tooltip("The duration (in seconds) over which the fade slide will fade in / out")]
    private float _fadeDuration = 0.75f;

    [SerializeField, Tooltip("All key codes that will move to the next slide if pressed")]
    private KeyCode[] _nextSlideKeyCodes = {
        KeyCode.D,
        KeyCode.RightArrow,
        KeyCode.Space
    };

    [SerializeField, Tooltip("All key codes that will move to the previous slide if pressed")]
    private KeyCode[] _previousSlideKeyCodes = {
        KeyCode.A,
        KeyCode.LeftArrow,
    };

    //The slide we're currently viewing
    private int _currentSlide = -1;

    // Whether the fade slide is currently fading
    private bool _isTransitioning = false;

    private void Start()
    {
        // Set our fade to black slide to black so that the audience can not see the first slide
        _fadeSlide.color = Color.black;
    }

    public void Update()
    {
        //Check for arrow keys/space bar down so we can fade the fadePanel accordingly
        ListenForInput();
    }

    private void ListenForInput()
    {
        // Ignore input if we're in the middle of a transition
        if (_isTransitioning)
        {
            return;
        }

        //If we strike the space bar or right arrow key, proceed to the next slide
        if (_nextSlideKeyCodes.Any(Input.GetKeyDown))
        {
            NextSlide();
        }

        //If we strike the left arrow key, return to the previous slide
        if (_previousSlideKeyCodes.Any(Input.GetKeyDown))
        {
            PreviousSlide();
        }

        //If we strike the Esc key, quit the application
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
    }

    private void NextSlide()
    {
        //If we're on the very last slide already..
        if (_currentSlide == _slides.Count - 1)
        {
            // Exit early
            return;
        }

        //Increment the slide count
        _currentSlide++;

        // Transition to the next slide
        StartCoroutine(SlideTransition());
    }

    private IEnumerator SlideTransition()
    {
        // Mark our fading slide as currently fading
        _isTransitioning = true;

        // Fade to black
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.black));

        // Set only our current slide active - and all others inactive
        _slides.ForEach(slide => slide.gameObject.SetActive(_slides.IndexOf(slide) == _currentSlide));

        // Fade to clear
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.clear));

        // Mark our fading slide as no longer fading
        _isTransitioning = false;
    }

    private void PreviousSlide()
    {
        //If the current slide is the very first slide, ignore the rest of this method
        if (_currentSlide == 0)
        {
            return;
        }

        //Decrement the current slide
        _currentSlide--;

        // Transition to the previous slide
        StartCoroutine(SlideTransition());
    }

    private IEnumerator FadeToTargetColor(Color targetColor)
    {
        // The total amount of seconds that has elapsed since the start of our lerp sequence
        float elapsedTime = 0.0f;

        // The color of our fade panel at the start of the lerp sequence
        Color startColor = _fadeSlide.color;

        // While we haven't reached the end of the lerp sequence..
        while (elapsedTime < _fadeDuration)
        {
            // Increase our elapsed time
            elapsedTime += Time.deltaTime;

            // Perform a lerp to our target color
            _fadeSlide.color = Color.Lerp(startColor, targetColor, elapsedTime / _fadeDuration);

            // Wait for the next frame
            yield return null;
        }
    }
}

```

# Answer
You can use a Coroutine with WaitForSeconds to create a timer:

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

public class Slidescript : MonoBehaviour
{
    //All _slides in the project, minus the _fadeSlide
    [SerializeField]
    private List<Transform> _slides = default;

    //The panel that overlays all _slides and changes from clear to black
    [SerializeField]
    private Image _fadeSlide = default;

    [Header("Config Values")]
    [SerializeField, Tooltip("The duration (in seconds) over which the fade slide will fade in / out")]
    private float _fadeDuration = 0.75f;
    [Header("Config Values")]
    [SerializeField, Tooltip("The duration (in seconds) over switch silde")]
    private float _switchDuration = 1.6f;
    //The slide we're currently viewing
    private int _currentSlide = -1;

    // Whether the fade slide is currently fading
    private IEnumerator Start()
    {
        // Set our fade to black slide to black so that the audience can not see the first slide
        _fadeSlide.color = Color.black;
        while (true)
        {
            _currentSlide++;
            _currentSlide = _currentSlide % _slides.Count;

            // Transition to the next slide
            StartCoroutine(SlideTransition());
            yield return new WaitForSeconds(_switchDuration);
        }
    }

    private IEnumerator SlideTransition()
    {
        // Fade to black
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.black));

        // Set only our current slide active - and all others inactive
        _slides.ForEach(slide => slide.gameObject.SetActive(_slides.IndexOf(slide) == _currentSlide));

        // Fade to clear
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.clear));
    }

    private IEnumerator FadeToTargetColor(Color targetColor)
    {
        // The total amount of seconds that has elapsed since the start of our lerp sequence
        float elapsedTime = 0.0f;

        // The color of our fade panel at the start of the lerp sequence
        Color startColor = _fadeSlide.color;

        // While we haven't reached the end of the lerp sequence..
        while (elapsedTime < _fadeDuration)
        {
            // Increase our elapsed time
            elapsedTime += Time.deltaTime;

            // Perform a lerp to our target color
            _fadeSlide.color = Color.Lerp(startColor, targetColor, elapsedTime / _fadeDuration);

            // Wait for the next frame
            yield return null;
        }
    }
}

```
> 0 votes

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


title: How to count polygons in Unity?

text:
# Question
Title: How to count polygons in Unity?
The Rendering Stats (profiler) only shows tris and verts. But everyone keeps using the term polygon which doesn't exist in Unity's terminology.

How can I get the polycount of my Unity scene?

# Answer
"tris" is short for "triangle" which in the context of 3d rendering is usually synonymous with "polygon".

According to mathematicians, polygons are two-dimensional shapes with **any** numbers of vertices (or 3 **or more** vertices, according to some definitions). And some 3d modeling tools even allow you to create polygons with more than 3 vertices. But when those get rendered by a 3d engine, any polygons with more than 3 vertices get broken up into triangles. This usually happens long before the geometry data gets to the rendering pipeline.

So when we are talking about "polygon count" in the context of 3d rendering, then what we **actually** mean is "triangle count". But "polygon" sounds way cooler, so the term sticks despite being slightly inaccurate.
> 2 votes

---
Tags: unity, 3d-modeling, performance-budgeting
---


# Question
Title: Canvas element active by default even though it's set to inactive in the script
The pause menu is getting shown by default when I click the play button, even though the `GameIsPaused` boolean is set to false. I don't know if it's the fault of how I referenced it in the engine itself or how the script is written.

Here's how I referenced it in Unity:

And here's my code:

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

public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;
    public GameObject pauseMenuUI;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (!GameIsPaused)
            {
                Pause();
            }
            else
            {
                Resume();
            }
        }
    }

    public void Resume()
    {
        pauseMenuUI.SetActive(false);
        GameIsPaused = false;
        Time.timeScale = 1f;
    }
    void Pause()
    {
        pauseMenuUI.SetActive(true);
        GameIsPaused = true;
        Time.timeScale = 0f;
    }
    public void LoadMenu()
    {
        Debug.Log("Loading Game...");
        SceneManager.LoadScene("MainMenu");
    }
    public void QuitGame()
    {
        Debug.Log("Quitting Game...");
        Application.Quit();
    }
}

```

# Answer
Your code that toggles the pause menu active state runs only when the `Esc` key is pressed.

Did you mean to also run similar code in `Start()` to set the initial state of the menu when this script loads, something like...

```
void Start() {
    if (GameIsPaused)
    {
        Pause();
    }
    else
    {
        Resume();
    }
}

```

?
> 0 votes

# Answer
I solved this problem by just disabling the PauseMenu just like this
> 0 votes

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


# Question
Title: r/l/b/t parameters in orthographic projection?
I am trying to implement following:

What are the `l r b t` *units*? I understood that `r-l=` is just `screen_width`, however is not clear: is it for ex: `l=-400` and `r=+400` for a screen width 800 pixels? I believe so, because that's what we see on the picture below (origin is in the middle):

However, plugging `l=-400` and `r=+400` into *ortho* matrix provided above, we have zero: `r+l = 0`. Same obivously goes for `t+b` when `t=+400` and `b=-400`.

Am I taking wrong numbers, or is it just zero and that's it?

# Answer
> 1 votes
These values are measurements in **world space** \- the coordinate space you're using to position objects in your scene. This is the same unit used in view space, the frame of reference of the camera, since the view matrix is just a rotation and translation, and does not apply any scaling.

So let's say you've set up your game where 1 world unit = 1 meter, and you have a level that's 5m tall, and you want to fit the whole level vertically into however many pixels there are along the height of your screen/window. Then `t = 2.5` and `b = -2.5` so that `t - b = 5`, covering the full height you want, and `t + b = 0` \- no vertical shift, so the part of the scene directly in front of the camera stays in the center of the screen.

Once you've transformed your objects into view space, an object at the very top of the camera's view will be at `y = 2.5` \- multiplying it by this orthographic projection matrix gets you `y' = 1`. Similarly, an object at the very bottom will be at `y = -2.5`, and after multiplying by the projection matrix you get `y' = -1`. This transformed position is in **normalized device coordinates**: a coordinate system that ranges from -1 to +1 from left to right/bottom to top across the window's bounds, and from the near plane to the far plane depth. The standard -1/+1 bounds make it easy to do clipping math in the next stage of the graphics pipeline.

Because pixel values don't occur anywhere in this formula, you can run the same projection code for a window or viewport of any size, and the rasterization will automatically scale the view of the scene to fit the output. You do need to match the aspect ratio of your `(r-l)/(t-b)` to the aspect ratio of the destination to avoid squashing though. And this automatic scaling works fine for mesh geometry, but does not do anything clever for textures, so if you want "pixel perfect" sprites and UI images, you need to take extra steps to adjust their positions/sizes/contents depending on the output resolution.

---
Tags: opengl, mathematics, graphics
---


# Question
Title: What would be a good approach to create an abstraction for a game object without textures?
I am practically pretty new to OpenGL development and right now doing some research in Java with LWJGL. But it's really not a question about Java or C++ (GLFW, etc.). It is about OpenGL \> 3 api.

Raw circumstances: I want to create a game (using LWJGL), that is kind of a tile based game, but right now i don't want to use textures. I just need colored squares. The squares can be of any size (depending on the zoom level). But they are just colored with one color, no texture.

What I need is defining **objects** that have **size**, **position**, and **color** (from a visual point of view).

I would like to have a class (sth. like `Model` or `VertexArray` or `...`) that I can feed with vertex data and an array of indices. The class itself provides a `constructor` and a `render` method that take care of all the OpenGL internals (eg. binding buffers, enable vertex attrib arrays, ... and finally doing the `glDrawElements(GL_TRIANGLES, this.count, GL_UNSIGNED_BYTE, 0);` or similar).

Now I am a bit confused about Shaders (as I am a beginner and my needs are basic, it's just the **Vertex** and **Fragment** shaders).

From what I have read, seen and heard, I learned the following.

1. I can provide the shader program (vertex and fragment) a buffer containing information. With **locations** I can put in geometric data (x, y, z) as well as coloring info (r, g, b, a) and (I think) anything else I need. The vertex shader will *consume* the data it needs and *pass thru* the data it is not interested in (eg. color). The Fragment shader is the next element in OpenGL's rendering pipeline, which will get the color as an input, if defined in the shader program itself. So it will be able to color each pixel in the according color.
2. I can provide the shader program a buffer with just information about geometric positions. I don't want to put in colors into the buffer which is bound and consumed by the shader(s). I want to provide / change the color via **uniforms**.

For me it feels more natural to generate vertex array objects based on pure geometric data and change the color by setting uniforms with values that change while updating my game state.

Which one would be the preferred way of achieving this. Or am I on a wrong path?

While I am asking this, I feel that I don't understand the concepts of uniforms and even putting data into buffers, that are present to shaders like *magic*.

**Edit:** (thanks to @DMGregory) I just don't know what is the difference in performance or in developer-friendly-wise between defining the squares' colors via uniforms and via buffer data.

Is it just "Many roads lead to Rome" or ...?

# Answer
You say you don't want to use textures *right now*, but as texturing is done via uniforms, and square colorings are only temporary substitutes for textures, then using uniforms for coloring is an intuitive and natural decision.

On the other hand, texturing brings with it texture coordinates that are passed as yet another attribute. Thus coloring can instead be thought of as a substitute for texture coordinates instead.

Therefore both options are fine if you ask me.

Via the uniform approach you'll have to perform split your draw calls across colors since uniforms are constant per draw calls, but as this is something you'll have to do for textures anyway, this isn't a problem. Furthermore, if you use a texture atlas (basically synonymous with sprite sheet), this again ceases to be a problem, because you can batch all your tiles and draw them at once using the same texture internally.

Either way you'll have things roughly the same number of things to change when/if you switch to textures, so I wouldn't think about it too much.
> 0 votes

---
Tags: opengl, shaders
---


# Question
Title: Flipping a sprite with SpriteRenderer.flipx when the pivot is not centered
My sprite has a pivot in the bottom left so that it snaps on the grid. Flipping the sprite with flipX almost works, but the sprite also shifts one quare to the left/right when flipping.

**Gif of behaviour:**

As you can see, the sprite flips, but shifts in an odd way due to the pivot point.

This is solved by moving the pivot to bottom center, but then the sprite has some weird collision with the tilemap collider.

**Gif of behaviour:**

Tilemap collider image:

As you can see, the character gets "stuck" or "caught" on the squares.

Here is the code:

```
Rigidbody2D rb;
Animator ani;
SpriteRenderer sr;

public float speed;
public float stationaryThreshold;

private float direction = 0f;
private float squaredStationaryThreshold;

private bool isGrounded = false;

void Awake()
{
    squaredStationaryThreshold = stationaryThreshold * stationaryThreshold;
}

void Start()
{
    rb = GetComponent<Rigidbody2D>();
    ani = GetComponent<Animator>();
    sr = GetComponent<SpriteRenderer>();
}

void Update()
{
    direction = Input.GetAxisRaw("Horizontal");

    if (direction > 0f)
    {
        rb.velocity = new Vector2(direction * speed, rb.velocity.y);
        if (rb.velocity.sqrMagnitude > squaredStationaryThreshold)
        {
            sr.flipX = true;
            ani.SetTrigger("Walk");
        }
    }
    else if (direction < 0f)
    {
        rb.velocity = new Vector2(direction * speed, rb.velocity.y);
        if (rb.velocity.sqrMagnitude > squaredStationaryThreshold)
        {
            sr.flipX = false;
            ani.SetTrigger("Walk");
        }
    }
    else
    {
        rb.velocity = new Vector2(0, rb.velocity.y);
        ani.SetTrigger("Idle");
    }

```

# Answer
> 2 votes
Try adding a Composite Collider 2D component on your Tilemap gameobject. Set **Used By Composite** checkbox to true in your "Tilemap Collider 2D" component. Composite Collider 2D also comes with a Rigidbody 2D, make sure to set the Rigidbody 2D's Body Type to either Static or Kinematic.

The Composite Collider 2D will combine each adjacent tile's collider into one combined collider, so you won't have to deal with individual collider's edges.

# Answer
> 1 votes
Instead, flip your sprite, change the `Transform.localScale` from `(1,1,1)` to `(-1,1,1)` and viceversa

I was to use `sprite.flip` but then I realized changing the scale is more useful and straightforward because you can flip all the other parts/sub-parts of the Game Object (equipment, UI elements, collision, particles).

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


# Question
Title: What should I be aware if I use [SerializeField] to pass GameObjects?
In Unity, I am trying to disable a Game Object in the scene by passing it through SerializeField. I have read elsewhere that this was previously not possible and is inadvisable, but I seem to be able to do it now. What are the problems with doing this?

# Answer
If you have something like...

```
[SerializeField] GameObject myObject;

```

...then this is a `private` variable that's been flagged to be processed by Unity's serializer - the system that records information about an instance that needs to be saved in a scene or asset file, and populated when that scene or asset is loaded (deserialized). This is also the system that Unity uses to draw the Inspector interface for editing your object.

The upshot is that you can assign a value to this field in the Inspector, and that value will be saved so that it persists into the running game, or between runs of the editor so you don't lose any work.

So far this is just like what you get if you marked the variable `public` instead (since `public` fields are serialized by default - unless you use the `[System.NonSerialized]` attribute to exclude them), but with one major difference: a `public` field can be read and changed by any other script that can get a reference to this instance. In contrast, a `private` field can only be read or changed by code inside the same class (or struct).

This is a form of information hiding and encapsulation, making it so that most of the code in your project doesn't know this variable exists.

Why would we want to hide information? Lots of ink has been spilled on this, but in short:

* **It reduces the surface area for bugs**. If under some circumstance this variable gets an invalid or inappropriate value assigned to it, causing a problem in your game, you want to be able to quickly identify the code that assigned that bad value.

If the variable is `private`, you have only a small amount of code to search - typically just one file.

If the variable is `public`, then the bad value might conceivably have come from *anywhere* in your project, so it can be more complex to reason about what's happening to it.
* **It makes the interface to this type simpler**. When you're in another script that's trying to use this type, and you type its name or the name of an instance, auto-complete will give you a list of all the *public* members of the type. If the type is complicated, with lots of `public` members, then it can be harder to find the one you want - especially if you're unfamiliar with it. You might take a guess at which member you wanted and get it wrong, because there was a better way hiding in all that noise.

By contrast, if we make `private` anything that external code shouldn't use directly, leaving just a few `public` members tailored to the intended use of this type, you make it very easy for even a naive coder to find the right members for what they want to do (say a junior team member, or even yourself in 6 months after you've forgotten how you coded this type to work). This helps the team work more efficiently, understand the system more clearly, and make fewer mistakes.
* **It lets you maintain "invariants"**. These are rules for what should always be true about the state of your game and its internal data, like "the items in the `targets` list are always sorted in order of priority" or "whenever the enemy is in 'attack' mode, its `target` variable is non-null". Having clear invariants makes your code easier to reason about, reduces bugs, and saves doing redundant checks to be sure you're working with valid state.

If a field is `public` though, it's impossible to enforce an invariant that involves it. Other code could set it to some arbitrary value that violates the rules, allowing bugs to creep in.
* **It makes it easier to refactor code down the line**. If later on, you decide that your platformer controller should expose inspector parameters for `jumpHeight` and `timeToPeak`, not `jumpSpeed` and `jumpGravity`, but those fields you're replacing were `public`, you might find code in other parts of your project is depending on them - so you have more code to alter to make this change, and again more chance to introduce bugs.

By making these variables `private` from the start, you enforce some discipline about what's allowed to read from them, making it less likely that you create a tangled knot of dependencies that's tough to refactor later. Now the only references to these variables should be confined to one class, where it's much easier to make the change without introducing new bugs. If other scripts are reading them, they're doing so via getter methods, and you can just modify those methods to return a compatible value, even though the internal implementation has changed, and the consuming scripts are none the wiser.

This discipline isn't free - it takes effort to maintain clean separations when adding extra dependencies would make for a quicker shortcut. So that is something to weigh here - considering the full lifecycle of this script and how long you need to be maintaining it / how much is likely to change in future - you could end up adding complexity to enforce this principle in a script that's ultimately thrown away without that effort paying off in future maintenance.
* For the case of `[SerializeField]`, **it gives a strong hint to the human reader about how the field is meant to be used**. If a variable is `public`, one might assume other scripts are meant to populate it. `[SerializeField]` (especially in the absence of `[HideInInspector]`) says "this is probably a designer tuning parameter set in the Inspector". When those hints are accurate, it's quicker for a reader to gain a clear understanding of the code.

So for this reason, hiding information by avoiding `public` where possible is generally considered a good practice in software engineering.

In contrast to the advice you've seen saying it's "inadvisable", I'd argue that changing `public` fields to `[SerializeField]` where possible is an improvement to encapsulation.

But it can also be a bit frustrating - particularly in early prototyping when everything is in flux. You might not be able to accurately predict what fields you or your team members will need access to from other scripts. If *everything* is `private`, coders will have to keep jumping into other files to make things `public` or add getter/setter methods just to get on with their work - something that can cause friction within the team. I alluded to this in the section on refactoring above - making a cleanly engineered interface is more work than just slapping `public` everywhere, even if the hope is it will pay off in faster development/fewer bugs in the long run. It's also a bit less conventional, and can confuse more junior coders who are used to just using `public`.

So, I wouldn't advise doing a global find-and-replace in your project or anything like that! But if you have variables that are purely for inspector configuration - especially if they're set once, and used only within the script itself, `[SerializeFiled]` is a great way to express that intention and reduce `public` clutter.

You can also use this auto-property variant, which still offers good encapsulation and defense of invariants, while making the field visible and read-only for other scripts to make decisions about:

```
[field:SerializeField]
public GameObject myObject { get; private set; }

```

This way the field appears in the Inspector and can be read by other scripts, but it can be written to only inside this script itself.
> 4 votes

# Answer
In general there is no problem in that. But it could be. Problems could be local or at architecture level.

**local** if this GameObject is doing something critical and you just disable in the middle of something (its scripts, other sub Game Objects, physics, collision, etc.)

**architecture** If another part of the game is using that GameObject you want to disable, then you will most probably generate an error. So keep in mind to always check its status before using it
> 0 votes

---
Tags: unity
---


# Question
Title: How to make a text-based game with timer systems
This is an interesting question I have, so I ask you to hear me out. No, I'm not just going to ask "how do I do this" and hope someone will give me code.

I've been programming for a long time and am beginning work on a side-project, a text-based game.

Without going into details, the game needs commands (a `Console.ReadLine()` sort of situation) but also needs timer-based systems (say, for instance, decreasing a variable `energy` every 10 seconds)

I've racked my brain about how to accomplish this, but came up empty handed.

My best guess is using asynchronous functions but I don't fully understand those and they don't seem like they will accomplish what I'm after.

TL;DR I want to be able to use `Console.ReadLine()` and also increase/decrease a variable every `n` milliseconds (even while waiting for the console input).

I think threading might be *a* way to do it, but that seems excessive for a \[relatively\] simple usecase.

Can anyone provide insight about how to accomplish this?

Thanks in advance.

EDIT: Ideally this would be a general answer that could apply to running *any* time consuming task in the background, while keeping the console available to read lines, print output, etc.

# Answer
> 2 votes
In a standard engine, `dt` represents the time in milliseconds since the last frame. In a text adventure, `dt` can represent the passage of time since the last command. The game loop should run as follows:

1. Record the current time in milliseconds as `start`.
2. Wait for user input.
3. Record the current time as `end`.
4. Calculate `dt = end - start` as your delta time.
5. Process all in-game actors and timers using this `dt`.
6. Process user's input.

It is critical that the user's input is processed after the game has ticked, otherwise the user can interact with things that have already expired (like shining a flashlight that has burned out, or cooking a hotdog over an extinguished fire).

An example in C#:

using System;
using System.Diagnostics;
using System.Collections.Generic;

public abstract class Actor {
    public abstract void Tick(long dt);
}

public class Campfire : Actor {
    private long life = 10 * 1000;

    public override void Tick(long dt) {
        life = Math.Max(0, life - dt);

        if (life > 5 * 1000) {
            Console.WriteLine("Your campfire is burning brightly.");
        } else if (life > 0) {
            Console.WriteLine("Your campfire is running low.");
        } else {
            Console.WriteLine("Your campfire burned out.");
        }
    }
}

public class Program {
    public static void Main(string[] args){
        var actors = new List<Actor>();
        actors.Add(new Campfire());

        Console.WriteLine("You stand in front of a campfire.");
        while (true) {
            // Fetch time and user input.
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            string command = Console.ReadLine();

            // Advance simulation.
            long dt = stopwatch.ElapsedMilliseconds;
            foreach (var actor in actors) {
                actor.Tick(dt);
            }

            Console.WriteLine("Command: " + command);
        }
    }
}```

# Answer
> 2 votes
You can try adapting main loops from graphical video games.

Have your main loop run as often as your logic rate. At each iteration, test if you have received any input from the terminal. I do not know C#, but I found `Console.KeyAvailable`. Using this should be simple if your user input is line-buffered. If not, you'll have to buffer it yourself and react to it only once you receive a valid, full command.

Most text-based video games have a very fixed-function, procedural design, but such a loop will make it friendlier and easier to data-oriented designs instead. This will turn your game into a big state machine that loads the "plot" and scenes from some externally-defined data, rather than being embedded within the code. In other words, an engine.

This is how I would do it, were I building a text-based game from scratch. If this is too big a change for your already existing project, then threading is probably your next best option. One thread could handle user input, while the other performs asynchronous events. However you will need to update the rest of your code to prevent race conditions.

# Answer
> 0 votes
Speaking more to the ***any* time consuming task** part, one way is a time slice treatment. Where you a) limit the process to a fixed amount of time; b) when the threshold is reached push the process state onto a stack; c) then the next opportunity pop its state and give it another time slice.

Since I'm experimenting in Go goroutines, I use a context with Timeout on the group Wait. With the hope of preventing tasks from running away as a collection. Then I use a Ticker individually, to avoid one task from "starving" its siblings.

---
Tags: c#, input, async
---


title: Mode7 transformations

text:
# Question
Title: Mode7 transformations
I've been studying mode7 from the SNES, and looking how to build it myself in C++.

I've found plenty of examples in SDL for rendering stuff like Mariokart levels, where the mode7 effect is applied by 'hovering' over a picture.

What I'm wondering is, is how difficult it would be to apply transformations like shown in this gif from 7th Saga: starting with a normal, top-down view on a image and then rotating, zooming and ending up in the 'mariokart-like' perspective.

Is this worthwile to build manually in pixel-by-pixel transformations, or should I be making this in a true 3D environment like OpenGL?

Or Maybe some kind of in-between solution, where I use SDL to transform/rotate textures, and then use manual pixel manipulation?

For reference, this is a project I've been studying for Mode7: https://github.com/jmermar/Mode7-SDL

# Answer
Using full 3D, it's pretty easy. You're simply moving & rotating the camera relative to a textured quad or flat mesh.

Using pixels only, it's more challenging. The mapping formula is available on Wikipedia:

> Mode 7 graphics are generated for each pixel by mapping screen coordinate \\$r\\$ to background coordinate \\$r'\\$ using an affine transformation and sampling the corresponding background color. The 2D affine transformation is specified for each scanline by 6 parameters; \\$a,b,c, d\\$ define the matrix \\$M\\$, while \\$x\_0\\$ and \\$y\_0\\$ define the vector \\$r\_0\\$ locates the origin of the matrix transformation and is related to a translation vector. Specifically, screen coordinate \\$r\\$is translated to the origin coordinate system, the matrix is applied, and the result is translated back to the original coordinate system to obtain \\$r'\\$. In 2D matrix notation, this is written as: $$r'=M(r-r\_0)+r\_0 \\ \begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} a & b \\ c & d \end{bmatrix} ( \begin{bmatrix} x \\ y \end{bmatrix} - \begin{bmatrix} x\_0 \\ y\_0 \end{bmatrix}) + \begin{bmatrix} x\_0 \\ y\_0 \end{bmatrix} $$ All arithmetic is carried out on 16-bit signed fixed point numbers, while all offsets are limited to 13 bits. The radix point is between bits 7 and 8.

If you're looking at the historical, pixel manipulation method, it's worth mentioning that the original implementation had some rounding errors that resulted in visual artifacts - the output looked somewhat blocky & had visual artifacts:

The above was taken from this video clip.

As to which approach you should use - only you can answer that. That depends on your time, interest, skills, constraints and other things not covered in the question & beyond the scope of GDSE recommendations. My advice would be to consider the pros & cons of those factors & choose accordingly.
> 1 votes

---
Tags: c++
---


title: Can I purchase Xbox One XDK in 2022?

text:
# Question
Title: Can I purchase Xbox One XDK in 2022?
My gf has an Xbox One, and I wanted to surprise her with a custom Xbox One game.

1. Are XDKs still being retailed?
2. How much do you estimate the cost?
3. How old do you have to be to purchase one?

I'd prefer not use any Homebrew, because I don't want to make her install a bunch of tools she'll never need to use again.

# Answer
The official "developer kits" are not for sale to anyone without an approved Publisher License Agreement or who are onboarded to the ID@Xbox program.

You *can*, however, make use of **Developer Mode** on a retail Xbox One or Xbox Series X|S. This allows you to write DirectX 11 or DirectX12 UWP x64 native applications using Visual Studio Community, Unity3D, or a few other engines.

See Microsoft Docs and this blog post.
> 1 votes

---
Tags: directx, console, xbox
---


# Question
Title: Hiding objects from the player when working with RenderTextures
I am currently working on a game that has monitors showing the player different elements such as texts, images and numbers. My plan for this is to use Unity's `RenderTextures`.

However, when creating the elements that the camera should put on the `RenderTextures`, they also exist in the scene.

What is the best way to hide them from the player? (Putting them far away or below the ground is not an option in my case).

Is there a way to put them in an entirely different scene for example?

# Answer
> 1 votes
Use layers.

By setting a culling mask on the player's camera, you can ensure it does not see the layers containing objects you want to hide.

By unchecking layer interactions in the physics collision matrix, you can ensure that the hidden objects won't process collisions with objects on other layers, so they'll just ghost through each other without sending `OnCollisionEnter` messages and the like.

You can also use layer masks to exclude these layers from your raycasts or other physics queries.

Together, these features effectively put those objects in an unseen parallels universe, even if they are close by in coordinates.

You'll want to avoid moving objects *too* far away from the origin, due to limited floating point precision.

You can also put these objects in a separate scene file for ease of editing them in isolation, and use additive scene loading to load that scene and others at the same time. This does not automatically separate them for rendering and physics interactions, so you still need to use layers as described above.

---
Tags: unity, rendertexture
---


# Question
Title: Is there any performance difference between Draw() and DrawInstanced(1)?
The background of the question is, does it make sense to introduce an `if` case when drawing a mesh for whether there is instancing or not?

This is using DirectX 11 with SharpDX in the Stride game engine:

Pseudo-code:

```
if (mesh.InstanceCount > 1)
    commandList.DrawInstanced(mesh.DrawCount, mesh.InstanceCount);
else
    commandList.Draw(mesh.DrawCount);

```

Or is it equivalent to just calling `DrawInstanced()` in any case?

# Answer
While you can bench this yourself, it may be worth noting that in the new APIs (Vulkan, D3D12), *there are no non-instanced draw calls*. Every draw call is instanced, and you specify a number of instances of 1 if you require non-instanced drawing.

This suggests that at a hardware or driver level, and with sufficiently modern components, there is no difference. With older components it may still be worth implementing a dedicated non-instanced path.
> 2 votes

---
Tags: directx, performance, sharpdx, instancing, stride
---


# Question
Title: How does condition 5 of the Open Font License apply to using a font in my game/engine?
For my game-engine I have created an debug-console I use for more complex operations and tests, logging, etc.

When looking for a good & clean font I considered using Google Fonts. Many if not all fonts on there are licensed under the Open Font License1, which seems to be the real deal.

Yet when reading the license I got confused if condition 5 also applies to videogames/engines:

> 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license **does not apply to any document created using the Font Software**.

**emphasis** mine

So, *how does this condition translate to me using it for my engine/game*? And how would I go about properly attributing?

1Link to the license definition: http://scripts.sil.org/cms/scripts/page.php?site\_id=nrsi&id=OFL

# Answer
The intent of Condition #5 of the Open Font License seems to simply be to clarify the following:

1. You do need to provide this license alongside your usage of the font, but
2. This license applies *just* to the font, and doesn't affect whatever you're using the font to produce.

In other words, the license is clarifying that it is not a viral license such as the GPL.

It's written assuming you're creating something classical like a written document since that would be the most ordinary use case. However in a non-classical production like a game, we could reasonably interpret that the “document” just covers wherever you're using the font inside the gam. It may even be interpreted as the game itself! But since the point of the clause is to clarify that it's not affecting any of that, how much is counted as the “document” would be mostly academic.

So it should be safe to use these fonts in a game — they're not exclusively limited to plain documents.

Proper attribution is specified per condition 2 of the Open Font License:

> 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.

This gives you plenty of room for how to provide attribution. There's two main options games go for:

1. If your users can access the game's files (e.g. it's not a console game), then you can distribute the license as a plain text file within your game files. If you've just got one or two OFL fonts, you might include it as `foo-license.txt` where “foo” is the font name. If you have *many* OFL fonts, just include one `open-font-license.txt`, and insert some lines at the top clarifying that the license text that follows applies to a specific set of fonts used within your game (and list the names of those fonts).
2. Alternately, many games include a *Boring Legal Stuff* section. This section is stuffed somewhere users won't find it unless they're looking for it, such as a the end of the About or Help area. It generally lists all the licenses involved in the game's production in a single endlessly scrolling text box, since that's technically sufficient to satisfy licensing requirements. You can reproduce the OFL license text in here and indicate which OFL fonts you've used that it covers.

Before releasing your game to the public for sale, it would be standard procedure to visit a lawyer to make sure you're doing things safely and legally. It would be appropriate to check with that lawyer that the above is sufficient just to cross your t's and dot your i's.
> 6 votes

# Answer
The Open Font FAQ Update 6 (current at the time I write this answer) has some good information on this, but nothing definitive. The license mainly describes the intention of using fonts covered by the license in documents or as a basis for creating new fonts. Information about using fonts in software is barely addressed, though there are snippets in the FAQ that can be pieced together to form a cohesive answer.

As I understand, the intention of the Open Font License is to:

* notify that the font is free to use
* ensure the font author is acknowledged for their effort whenever the font is used
* that the font license is acknowledged whenever the font is used
    + this is especially applicable when the font is used when creating new fonts; the license must be perpetuated in the new font.

As far as using Open Font License fonts in software (i.e. games in this context), I gather what I feel is the appropriate reasoning below from the FAQ below:

Question 1.4 specifically refers to using the font (original or modified) in a (sellable) game. They define this as "bundling" the font in software, and list several examples of software it applies to.

Question 1.19 talks about the "grey area" of acknowledgement. It clarifies the intent of acknowledgement as being a way to show goodwill; that you have benefitted from the font author's work (but not in a way that means the author has endorsed your game).

Question 1.20 contains the most appropriate information about bundling the font in software. The answer to 1.20 is so on-point that I'm going to quote it here in it's entirety:

> If you bundle a font under the OFL with your mobile app you must comply with the terms of the license. At a minimum you must include the copyright statement, the license notice and the license text. A mention of this information in your About box or Changelog, with a link to where the font package is from, is good practice, and the extra space needed to carry these items is very small. You do not, however, need to include the full contents of the font package - only the fonts you use and the copyright and license that apply to them. For example, if you only use the regular weight in your app, you do not need to include the italic and bold versions.

Note that the question specifically targets a "small app for mobile platforms", however given the way Question 1.4 is written I believe it is applicable to all software the bundles the font. As such, if your software (game) contains a font covered by the Open Font License and is distributed on a web/mobile/desktop digital platform (i.e. pretty much anywhere you can distribute your game software, whether you are selling it or not) I believe this question applies to you.

# Satisfying the OFL License in a game

Given the above information from the FAQ, I believe that games using fonts covered by the Open Font License must, somewhere in the game that a user can see, provide 3 things for each such font:

* the copyright statement
* the license notice
* the license text

This is your acknowledgement for using the font.

The FAQ recommends using the About box or Changelog, but if you don't have these things in your game you'll have to design somewhere a user can view your acknowledgement(s) of each such font you use, including these 3 things.

* For games on an operating system where the user can view text files you include in your distribution, putting the acknowledgement in one or more text files that will cover the license requirements.
* If the user can only access your running game, you'll need to put your acknowledgements somewhere in the GUI where the user can see it.

Please note that I'm not a lawyer, but in my experience working with licenses in software (which is quite a lot — I've been doing this for decades) if you can show how you've satisfied the license agreement then you're covered. The Open Font License is mainly concerned with ensuring you don't profit directly from the font author's work. If you acknowledge each font with these 3 details from the FAQ where the user can see it then you should legally be covered. When in doubt, show more information.
> 2 votes

---
Tags: fonts, licensing
---


# Question
Title: Pathfinding to find the route to nearest resource in 2D grid
The setting is a game in a 2D gridlike labyrinth/maze. I'm looking at pathfinding algorithms such as A\* and Dijkstra. I can't figure out how to have my game characters find the nearest resources. All the info I found regarding pathfinding deal with reaching a goal node. However, there are many potential goals so how do I find the path to the nearest resource? At first I thought running pathfinding for each potential goal, but that seems too time consuming (for 4-5 characters with 50 resource nodes). The characters are all competing for the resources so getting there fast is priority.

I understand that Dijkstra solves the distances to *all* nodes in the grid- so I think the solution lies there, but still the examples I found still require a goal node. So I'm confused how to distill paths from the node calculation.

Can someone explain how to handle pathfinding where finding the nearest goalnode is part of the problem?

---

**Edit:**

The solution I ended up using is this: As mentioned by *ali ahmadi* in the comments below, it proved quick enough to do a distance search on the potential goals and then do a A\* pathfinding to that goal.

It does not answer the question exactly, but the AI players mimic the human player behaviour close enough which is fine for my game. I might get back to this when I need the AI to be more brutal...

# Answer
modify a\* considering goal as a set of points instead of a single point. If the euristic function is the distance, the each step of a\* chose the path that minimize the closest point distance. Check also this
> 1 votes

# Answer
here you go, here is a implantation of the A\* in Action script 3, i wrote this a few years ago, there are a few things such as grid, grid view and node classes that i'm using which really don't have anything to do with the A\* algorithm itself, and are all used for the graphic and visual side of the work, still if you are interested i can put them here so you can use them,
please read the codes very carefully, **this class, finds the nearest and shortest path inside a grid!** exactly what you need, so spend sometime reading it and if you still have problem understanding it, ask and i will help you.

```
package
{

    public class AStar
    {
        private var _open: Array;
        private var _closed: Array;
        private var _startNode: Node;
        private var _endNode: Node;
        private var _grid: Grid;
        private var _path: Array;
        //private var _heuristic: Function = manhattan;
        //private var _heuristic: Function = euclidian;
        private var _heuristic: Function = diagonal;
        private var _straightCost: Number = 1.0;
        private var _diagCost: Number = Math.SQRT2;

        public function AStar()
        {

        }

        public function findPath(grid: Grid):Boolean
        {
            _grid = grid;
            _open = new Array();
            _closed = new Array();
            _startNode = _grid.startNode;
            _endNode = _grid.endNode;

            _startNode.g = 0;
            _startNode.h = _heuristic(_startNode);
            _startNode.f = _startNode.g + _startNode.h;

            return search();
        }

        public function search():Boolean
        {
            var node: Node = _startNode;
            while (node != _endNode)
            {
                var startX: int = Math.max(0, node.x - 1);
                var endX: int = Math.min(_grid.numCols - 1, node.x + 1);
                var startY: int = Math.max(0, node.y - 1);
                var endY: int = Math.min(_grid.numRows - 1, node.y + 1);

                for (var i: int = startX; i <= endX; i++)
                {
                    for (var j: int = startY; j <= endY; j++)
                    {
                        var test: Node = _grid.getNode(i, j);
                        if (test == node || !test.walkable || !_grid.getNode(node.x, test.y).walkable || !_grid.getNode(test.x, node.y).walkable) continue;

                        var cost: Number = _straightCost;
                        if (!(test.x == node.x) || (test.y == node.y))
                        {
                            cost = _diagCost
                        }

                        var g: Number = node.g + cost;
                        var h: Number = _heuristic(test);
                        var f: Number = g + h;
                        if ((isOpen(test) || isClosed(test)))
                        {
                            if (test.f > f)
                            {
                                test.f = f;
                                test.g = g;
                                test.h = h;
                                test.parent = node;
                            }
                        }
                        else
                        {
                            test.f = f;
                            test.g = g;
                            test.h = h;
                            test.parent = node;
                            _open.push(test);
                        }
                    }
                }

                _closed.push(node);
                if (_open.length == 0)
                {
                    trace("No Path Found");
                    return false;
                }

                _open.sortOn("f", Array.NUMERIC);
                node = _open.shift() as Node; // takeing the first element of array(which is the lowest cost!)
            }

            buildPath();
            return true;
        }

        private function buildPath():void
        {
            _path = new Array();
            var node: Node = _endNode;
            _path.push(node);

            while (node != _startNode)
            {
                node = node.parent;
                _path.unshift(node); // add to the begining of array
            }
        }

        public function get path():Array
        {
            return _path;
        }

        private function isOpen(node: Node):Boolean
        {
            for (var i: int = 0; i < _open.length; i++)
            {
                if (node == _open[i])
                    return true;
            }

            return false;
        }

        private function isClosed(node: Node):Boolean
        {
            for (var i: int = 0; i < _closed.length; i++)
            {
                if (node == _closed[i])
                    return true;
            }

            return false;
        }

        private function manhattan(node: Node):Number
        {
            return  Math.abs(node.x - _endNode.x) * _straightCost +
                    Math.abs(node.y + _endNode.y) * _straightCost;
        }

        private function euclidian(node: Node):Number
        {
            var dx: Number = node.x - _endNode.x;
            var dy: Number = node.y - _endNode.y;
            return Math.sqrt(dx * dx + dy * dy) * _straightCost;
        }

        private function diagonal(node: Node):Number
        {
            var dx: Number = Math.abs(node.x - _endNode.x);
            var dy: Number = Math.abs(node.y - _endNode.y);
            var diag: Number = Math.min(dx, dy);
            var straight: Number = dx + dy;
            return _diagCost * diag + _straightCost * (straight - 2 * diag);
        }

        public function get visited():Array
        {
            return _closed.concat(_open);
        }
    }
}

```

i think i should explain this, inside the codes, in class declaration
you see

```
//private var _heuristic: Function = manhattan;
//private var _heuristic: Function = euclidian;
 private var _heuristic: Function = diagonal;

```

these are cost functions! each uses a different method, for example one uses,
if its left or right or top or bottom cell, it will cost 1 and if its topLeft, topRight, bottomLeft, bottomRight Cells it will cost 1.5 point, and it will uses these point to find the nearest path!
there is also custom costing as well ! why ? , for example every where is ground and some parts are water cells, you can say ground cells worth 1 point and water cells worth 3 point, meaning if you pass 3 ground cells it equals passing one water cell, and all these also will be considered in your nearest path Algorithm ,
and using it, you can easily make a game with different fields and paths
there is also

```
if (test == node || !test.walkable || !_grid.getNode(node.x, test.y).walkable || !_grid.getNode(test.x, node.y).walkable) continue;

```

this part which has walkable variable for each node, if its true, the node can be used as a path! and if its false that node **IS NOT WALKABLE** this way you can even build walls and impossible to walk objects in some cells

**here is a link to my Final project that uses this class (it's swf file which is uploaded online, so you can simply watch the output as long as you have flash player)**
**Make sure you watch this :**
http://www.fastswf.com/HIa1W9M
hopefully what i said helps you.
Good luck.
> 1 votes

# Answer
The easiest solution is to use any flood-type algorithm, for example as you mentioned Dijkstra's algorithm. The only difference is the stopping condition:

```
if(Resources.Any(r => r == node)) { ...}

```

instead of

```
if(resource == node) { ...}

```

you can improve its performance by excluding resources that cannot be possibly reached yet from the check (=found distance is smaller than direct distance) and of course by simplifying the underlying data to graph of nodes and weighted edges.
Personally, I would not suggest A\* as it is harder to implement and there can be many special cases in labyrinth leading to flood-type complexity anyway but if you need the little extra performance and/or if you expect the path to be often straightforward I dont see any problem with it.
However, for the fastest solution you can pre-compute all vs all distances in graph using Floyd–Warshall algorithm in `n^3` and resolve nearest resource in linear time, more precisely `O(1)` for each resource. This solution has also the upside of not-having to implement anything as you can use any existing implementation without any modifications.
For finding *optimal* (or near optimal) solution to find shortest path *between many*(not just single closest) resources you can also check this question.
> 1 votes

# Answer
I have developed my own algorithm and software to find shortest paths between all of the locations with some optimizations and tuning for the game I develop.

It is a 2D tile based RPGMaker style game - similar to generation 3 Pokemon games

I can't claim that my algorithm is the best or superior but it worked very well for my maps which are usually 64x64 grids and even one of them is 192x192 grid - when you consider the amount of time spent

This is the video of my development it can give you a lot of ideas/hints and even you may develop a better approach: https://youtu.be/jRTA0iLjv6M

The software is fully multi threaded and uses a recursive function. I even had to debug and fix a complex memory leak related to started tasks

You can access the full source code on GitHub : https://github.com/FurkanGozukara/pathfinding-2d-tile-map

It can be probably further improved and tuned but I didn't spend more time on it since it works and already implemented to the game.
> 0 votes

---
Tags: 2d, path-finding, maze, dijkstra
---


# Question
Title: Is precomputed pathfinding still relevant?
**Context**

Old Lucas Arts (ScummVM era) point and click graphic adventure games used precomputed pathfinding. Here's a rough outline of the technique.

**Step 1**

The floor in each room was divided into what they called "walk boxes", which were pretty much equivalent to nodes in a navigation mesh, but limited to trapezoid shapes. E.g:

```
 ______ _____ _________ _____
\   A  |  B  |    C    |  D   \
 \_____|     |         |_______\
       |_____|         |
             |_________|

```

**Step 2**

An offline algorithm (e.g. Dijkstra or A\*) would calculate the shortest path between each and every pair of nodes, and store **the first step of the path** in a 2D matrix, indexed in each dimension by the starting and ending node used. E.g. using the walk boxes above:

```
      ___ ___ ___ ___
     | A | B | C | D | <- Start Node
  ___|___|___|___|___|
 | A | A | A | B | C |  ---
 |___|___|___|___|___|     |
 | B | B | B | B | C |     |
 |___|___|___|___|___|     |-- Next node in shortest path
 | C | B | C | C | C |     |   from Start to End
 |___|___|___|___|___|     |
 | D | B | C | D | D |  ---
 |___|___|___|___|___|
   ^
   |
End Node

```

As you may guess, the memory requirements increase quickly as the number of nodes increase (N^2). Since a short would usually be large enough to store each entry in the matrix, with a complex map of 300 nodes that would result in storing an extra:

```
300^2 * sizeof(short) = 176 kilobytes

```

**Step 3**

On the other hand, calculating the shortest path between two nodes was extremely fast and trivial, just a series of lookups into the matrix. Something like:

```
// Find shortest path from Start to End
Path = {Start}
Current = Start
WHILE Current != End
    Current = LookUp[Current, End]
    Path.Add(Current)
ENDWHILE

```

Applying this simple algorithm to find the shortest path from C to A returns:

```
1) Path = { C }, Current = C
2) Path = { C, B }, Current = B
3) Path = { C, B, A }, Current = A, Exit

```

**Question**

I'm suspecting that with today's powerful hardware, coupled with the memory requirements of doing this for every level, any benefits this technique once had are now outweighted by simply performing an A\* at runtime.

I've also heard that nowadays memory lookups might even be slower than general computation, which is why creating sine and cosine look up tables is not as popular anymore.

But I must admit I'm not yet too knowledgeable on these matters of low-level hardware efficiency though, so I'm taking this chance to ask the opinion of those more familiar with the subject.

On my engine I also needed the ability to dynamically add and remove nodes to the graph at runtime (see this) so the precomputed route only made things more complicated, so I scrapped it (not to mention my runtime A\* solution was already running perfectly). Still, I was left wondering...

*Bottom line,* is this technique still relevant nowadays in any scenario?

# Answer
> 4 votes
> On my engine I also needed the ability to dynamically add and remove nodes to the graph at runtime (see this) so the precomputed route only made things more complicated, so I scrapped it (not to mention my runtime A\* solution was already running perfectly). Still, I was left wondering...
>
> Bottom line, is this technique still relevant nowadays in any scenario?

I can see no benefit from using such a technique.

I lacks the flexibility of a Graph (you can have different LODs, they don't have to be any specific shape, ect...). Also any user of your engine is going to know what a graph is and how to use one. So if they want to add extra functionality their going to have to learn how to implement their extension using a situation completely novel to them.

As you mentioned it looks like it would scale horribly. Also its worth noting that if a graph fits on the cash and you run all of your path findings back to back it really cuts down on the IO time. It looks like you implementation would soon grow too large to fit on any cache.

> I've also heard that nowadays memory lookups might even be slower than general computation, which is why creating sine and cosine look up tables is not as popular anymore.

Unless you can fit all of your program and its need memory in the cache you are going to bottle neck at pulling things in and out of memory way before you bottle neck the processor.

> I'm suspecting that with today's powerful hardware, coupled with the memory requirements of doing this for every level, any benefits this technique once had are now outweighted by simply performing an A\* at runtime

Also realize that many games have separate loops for updating the AI. I believe he way my project is set up is that there is an update loop for user input at 60hz, the AI is only 20hz, and the games draws as quickly as possible.

Also as a side note I did some GBA programming just for fun and nothing at all transfers over to using a modern device. For the GBA everything was about minimizing the workload of the processor (because it was pathetic). You also have to realize that most high level languages C# and Java (not so much C++ or C) do tons of optimizations for you. As for optimizing you code their isn't much to do other than access memory as little as possible and when you do run as many computations on it as possible before bringing in new memory that will bump it out of the cache and making sure you are only doing things once.

Edit: Also to answer your title yes it is. Precomputing frequently used paths is an excellent idea and can be done with A\* anywhere outside of your game loop. For example from you base to a resource in a RTS so that the gathers don't have to recalculate every time they want leave or return.

# Answer
> -1 votes
I would say definitely yes. It certainly reduces time and effort spent and yet takes very limited storage space.

I recently coded and implemented precomputed/precalculated pathfinding into my 2d tile based game for some degree autonomous movement.

You can watch the whole video and look at the whole source code. It was certainly challenging since I didn't use any secondary sources to develop the algorithm. Therefore, I can't say it is the best or most optimized one though it worked pretty fast and works perfect in the actual game at the moment.

---
Tags: ai, path-finding, performance, optimization
---