# Question
Title: OpenGL approach to depth-testing-like combination of a large buffer of fragments
I have a depth buffer and color buffer created by another effect. The buffer is more than double my screen size. It is not rendered from geometry, but as a whole it resembles a rendered scene with an ortho projection. I can't generate this data w/ any other projection. I'm trying to redraw the scene in two-point perspective. This means each fragment from the orthographic data will be skewed and translated based on the depth value.

If I render a fullscreen quad, each fragment will not know how or where to sample from the original buffer. It seems like I the sources have to assign themselves to destinations, rather than a destination gathering sources.

Impractical or incomplete solutions: \- Generate a tri or point for every pixel in the source buffer, and actually rasterize them with depth testing. This is really slow, but it could be possible to generate the vertices in a compute shader or something? We're still dealing millions of tris for an average screen. I'm skeptical that this is the real solution. \- Something with SSBO and atomicMax. It seems like you can only compare your actual data, so I would have to pack my colors with depth values somehow.

This seems like a fairly fundemental operation, so I'm hoping there is some canonical technique or opengl extention that does this sort of thing for me well. Even a name for this operation might help me find existing literature.

The final solution must be realtime for typical screen sizes. C++/OpenGL.

# Answer
When I've done something similar (reprojecting colour-depth images from the Kinect 2 into the game's 3D space), I...

1. ...made a Mesh with a vertex for each texel in the input texture. (You can break this into multiple mesh chunks if you have more texels than your vertex limit allows)
2. ...rendered the mesh as a collection of Point primitives, rather than triangles.
3. ...sampled the source texture in the vertex shader and offset the scene position of the vertex according to the depth value in the image.

From there, the regular depth buffering takes care of overlapping fragments.

I can't claim this is *the* most efficient route, but it was good enough for us to maintain a realtime framerate with new input images streaming continuously from the Kinect sensor.
> 1 votes

---
Tags: opengl, graphics, graphics-programming, compute-shader
---


# Question
Title: Store functions with parameters in a List
I want to store functions with parameters in a List, so that I can call them at a later stage.

Let's say (this is rough code)

```
void Func1(int index)
{
   Debug.Log("Func1"+index)
}

void Func2(int index)
{
   Debug.Log("Func2"+index)
}
.
.
.

void Store(Func1(1))
{
  list.Add(Func1(1));
}

void Replay(int position)
{
  list[position](); // this calls the function with the parameter
}

```

# Answer
You declare that you have a list of actions:

```
List<Action> list;

```

Do not forget to initialize it:

```
list = new List<Action>();

```

Then, you create an action from the function using a lambda expression:

```
Action action = () => Func1(1);

```

And you add the action to the list:

```
list.Add(action);

```

You can, of course, inline the lambda expression:

```
list.Add(() => Func1(1));

```

Afterwards you can call the actions, for example, in a loop:

```
foreach (var action in list)
{
    action.Invoke();
}

```

Actually, you do not need to use `Invoke`:

```
foreach (var action in list)
{
    action();
}

```

Ah, yes, that works too:

```
list[position]();

```
> 7 votes

---
Tags: c#
---


# Question
Title: Assets bundles have higher size than uncompressed sprites
I've created a script that generates assets bundles by compressing sprites using LZ4 compression. I need this in order to generate smaller files that I'll download from a server at runtime but after taking a look at those bundles. I've found out that they actually have a higher size than the uncompressed sprites. For example, I've generated a bundle from three sprites that have a size of 201KB together, but if I take a look at its generated bundle, its size is 300KB. This is only one example, there are other bundles that are 6MB but their original files are only 500KB and that doesn't make any sense to me. Can someone point me in the right direction?

# Answer
Thanks for your answers, actually you guys gave me a hint of what's going on here and I've found out the solution for this. Well, it happens that it doesn't matter if you compress your PNG files with photoshop before, Unity converts those PNGs in a unity readable format which of course have another file size based on the import settings you are using. In this case, I was testing an asset bundle I've made from a group of png assets which were ~250 KB in total (as PNGs), but ~600KB as an asset bundle, I've tested many different texture settings with no luck, but after changing the resolution of those PNGs to something multiple of 4, I could make use of DXT5 compression which reduced the size of the asset bundle to something more normal.
> 1 votes

---
Tags: unity, assets, unity-webgl
---


title: Finding an angle between two bodies

text:
# Question
Title: Finding an angle between two bodies
I am trying to find angle between vectors a and b. But the cosine for some reason is not within +/- 1, that means that it is not possible to find an angle between a car and a pedestrian...

Any help appreciated

**EDIT** I have rewritten my function in accordance with the answer below (I had to do some changes due to writing in Python, for example pedestrian.body.position is equivalent to body.GetPosition()

I also tried to normalize both vectors, but the cosine is still not within +/- 1 And the car can move in both direction, so I do not know how to get its other component...

<pre><code>    def detect_pedestrian(car,pedestrian):
        #Find a vector which connects pedestrian with a car
        pedestrian_position = pedestrian.body.position
        car_position = car.body.position

        #Find vectors a and b
        car_vector = Box2D.b2Body.__GetTransform(car.body).R.GetYAxis()
        pedestrian_vector = pedestrian_position - car_position

        #Calculate magnitudes of both vector
        pedestrian_vector_magnitude = np.linalg.norm(pedestrian_vector)
        car_vector_magnitude = np.linalg.norm(car_vector)

        #Normalize both vectors
        pedestrian_vector_normalized = pedestrian_vector/pedestrian_vector_magnitude
        car_vector_normalized = car_vector/car_vector_magnitude

        #Calculate angle
        magnitudes = pedestrian_vector_magnitude * car_vector_magnitude
        dot_product = b2Dot(pedestrian_vector_normalized, car_vector_normalized)
        cosine = magnitudes/dot_product
        arccos = np.arccos(cosine)

        print(cosine)

```
</code></pre>

# Answer
> 0 votes
Well, this is my final working solution of a function detect\_pedestrian

```
    car_velocity = car.body.__GetLinearVelocity()
    if car_velocity == (0,0):
        car_velocity = (0,1)
    car_vector = Box2D.b2Body.__GetTransform(car.body).R.GetYAxis()
    pedestrian_vector = pedestrian.body.position - car.body.position

    pedestrian_relative = pedestrian_vector - car_vector
    pedestrian_length = np.linalg.norm(pedestrian_relative)
    velocity_length = np.linalg.norm(car_velocity)
    dot_product = np.dot(pedestrian_relative, car_velocity)
    cosine = dot_product / (pedestrian_length * velocity_length)
    print(f"Pedestrian angle: {np.degrees(np.arccos(cosine))}°")

```

# Answer
> 0 votes
To calculate vector **a**, you need to use `GetPostion()` on the bodies, and subtract them, then normalize it.

```
// Get vector a
b2Vec2 carp = carbody.GetPosition();
b2Vec2 pedp = pedbody.GetPosition();
b2Vec2 a = b2SubV2V2( pedp, carp );
a.Normalize();

// Get vector b
carbody.GetTransform().R().col1(); // assume car travels in +x, use col2() for +y.

// Determine angle between them.
float32 dotp = b2DotV2V2( a, b );
// NOTE: Should clamp dotp to -1..1 because of FP inaccuracy.
dotp = dotp < -1 ? -1 : dotp;
dotp = dotp >  1 ?  1 : dotp;
float32 ang = acosf( dotp );

```

You probably also want the sign of the angle (is the pedestrian to the right, or to the left of the car?)

You can obtain that using the dot product of **a** with the sideways-axis of the car's frame, and see if that is positive or negative. If it is to the right, flip the sign of the angle you calculated.

# Answer
> 0 votes
The dot product of two **UNIT** vectors equals the cosine of the angle between those vectors.

so in order to get what you expect you have to use unit vectors - so be sure to have your two vectors normalized before doing the dot product (looks like you don't do that)

---
Tags: mathematics, algorithm, box2d, python
---


# Question
Title: How can velocity be normalized after a collision if a projectile needs to maintain its height?
I want a thrown disc to travel along the same height, even after collisions. The problem is, there's an edge case that I'm not sure how to deal with.

The lowest-tech solution would probably be to quickly interpolate the rotation of the disc so that it's flat, and also interpolate its height so that it never collides with another object in a way that would impact its height, but that might be a bit heavy-handed. I worry that it would look really bad if you're holding the disc at an angle when releasing it for a throw, and it just suddenly "swooshes" flat mid-flight. Would that seem janky?

If I don't do that, and I simply retain the disc's rotation as it flies along its path, then it might collide with an object's edge in a way where the correct bounce angle would send it upwards or downwards, which I don't want. But if I simply hard-code the y velocity to 0, then in those instances, the lateral velocity becomes very low. Should I just check for a "minimum" speed, and increase it to that if it falls below that? Because the issue is that in the case where it bounces upward, there's a good chance that the correct bounce angle, if the y velocity is ignored, results in the disc continuing in the same direction rather than bouncing.

So I'm honestly leaning towards extending the collision boxes for these objects really far above and below where the disc could possibly be thrown, that way regardless of its orientation, it would always be the side of a cylinder colliding either with the side of a box or one of its vertical edges, and the velocity change should thus (hopefully) always look like it makes sense.

# Answer
> 1 votes
It sounds like what you want can be achieved with the various axis lock settings in `RigidBody`:

Here I've locked `linear_y` so the disc cannot move up or down, and I've locked *all* angular movement, so it cannot rotate at all. Here's a demo:

---
Tags: physics, godot, virtual-reality, projectile-physics
---


# Question
Title: Mapping decibel range to linear audible intervals
I am working in an engine that encodes sound as decibels (dB). Let's assume the decibel range of human hearing is -60dB to 0dB.

Audibility is not linear across this range.

So my question is...

**How does one map a decibel range to a set of numbers (for example, 1-10), such that each number corresponds to (roughly) one linear step up in audibility?**

# Answer
We use `dBvalue = 20 * log10( volumeAsPercent )` where `volumeAsPercent` is in the range of \[0.001 .. 1\]. `dbValue` will be in the range of \[-60 .. 0\].

(That's a bit annoying because the actual engine - OpenAL - uses 0..1 for its *gain*, so we have to convert that back using `volumeAsPercent = 2^(dBvalue/6)`. It will not exactly give the same result as the input but will give an approximation to `volumeAsPercent = 10^(dBvalue/20)` which is close enough (I don't know why we use that formula, and we can't change it at this point).)

I'm not a sound engineer, I don't play music and I don't have a sound studio to test this, but testing this formula with increments of 10%, seems to give a nice progression in making the sound louder (from completely muted at 0, up to what is in the original wav file at 1).

Here are the plotted curves.
> 1 votes

---
Tags: gui, sound, music, sound-effects
---


# Question
Title: ToonRamp Shader + Normal Maps: How to keep strict lighting bands?
I'm trying to achieve a shading similar to the one on this image:

Image 1: https://i.stack.imgur.com/iB5nH.jpg

To get something similar to this I wrote a toon ramp shader (similar to the one in the Standard Assets) with normal maps. The shader works, and without a normal map you can see the lighting bands strictly defined, with visible seams separating them (Image 2). But once you add a normal map, the toon bands won' t have well defined seams anymore, and will blend smoothly all across the mesh (Image 3).

Image 2 & 3: https://i.stack.imgur.com/hIVo4.jpg

This is my current shader:

```
Shader "Custom/ToonRampWithNormals"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _BumpMap("Bumpmap", 2D) = "bump" {}
        _Ramp("Toon Ramp", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Ramp

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _Ramp;

        half4 LightingRamp(SurfaceOutput s, half3 lightDir, half atten)
        {
            half NdotL = dot(s.Normal, lightDir);
            half diff = NdotL * 0.5 + 0.5;
            half3 ramp = tex2D(_Ramp, float2(diff,diff)).rgb;
            half4 c;
            c.rgb = s.Albedo * _LightColor0.rgb * ramp * atten;
            c.a = s.Alpha;
            return c;
        }

        struct Input
        {
            float2 uv_MainTex;
            float2 uv_BumpMap;
        };

        sampler2D _MainTex;
        sampler2D _BumpMap;
        half _Glossiness;
        fixed4 _Color;

        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutput o)
        {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_BumpMap));
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

So, what have I done wrong? How can I have well defined lighting bands and have normal mapping?

If you can think of a better way to achieve something similar to the reference or have any thoughts about it please share, any contribution is much appreciated.

# Answer
> 0 votes
Everything is all right with the shader. The issue was in the texture itself, it had too many small details, tried another texture with fewer details and BAM it works as intended.

.

---
Tags: unity, shaders, lighting, normal-mapping
---


title: Expose private methods to inspector?

text:
# Question
Title: Expose private methods to inspector?
In Unity we can use the Attribute `[SerializeField]` to expose private fields to the Unity inspector like so:

```
[SerializeField]
private float speed;

```

Now I want to do the same for methods that I want to use in the inspector: for example `OnClick` callback methods for buttons. Using `[SerializeField]` does not work and from what I can tell there is no `[SerializeMethod]` or similar to expose this functionality. **How can I expose private methods to the Unity inspector similar to how `[SerializeField]` exposes private variables?**

To understand what I mean by "expose" I meant having it show up in the inspector like this:

The reason I want this functionality is because I just encountered a bug where I was calling a public method from a script that was just meant to be called as a callback to the `OnClick` method. Pretty much the same reasoning as wanting to use `[SerializeField]` to hide variables but expose them to the inspector.

# Answer
# You can't

Private methods can't be exposed to the editor. Your goal her is to have another script invoke the method, and the only way to do that (and in fact the only thing that even makes sense) is for that method to be `public`.

Technically speaking, you *could* invoke private methods via Reflection, but this is a performance nightmare and is not recommended. As such, the Unity Editor doesn't allow private methods to be the target for invocation in this manner.

Alternatively, you can allow buttons to invoke private methods by assining the `Onclick` behavior via code:

```
Button btn = someGO.GetComponent<Button>();
btn.onClick.addListener(delegate { myPrivateFunciton(); });

```

The scope that this code is running it has access to `myPrivateFunciton` and therefore has the executive authority to pass off a reference to another object (in this case, the button), similar to passing a private field reference to another class instance.
> 8 votes

# Answer
This topic seems to be very old, but since I stumbled upon the same issue and found this topic, here is my solution.

In nutshell, for every Unity component that exposes "Unity-only" methods you make *two* classes:

1. ***Main*** class. A well designed *public* class that follows all the best practices. It declares Unity specific methods (like callbacks for the controls) as `protected`. The external consumers of your code will see this class and will only be able to use what you've explicitly declared `public`. They will be able to inherit and access the protected methods, but it would also require them to replace the component. And given the difficulty of dealing with the serialized Unity fields, I'd say it's not feasible. So, we may safely assume nobody will be calling your protected methods.
2. ***Decorator*** class. A *private protected sealed* class that inherits from the *main class* and declares *new* public methods for what was declared as `protected` in the main class. The external consumers won't be able to see this class, but Unity *will* be able to see this class and invoke its callbacks!

The downside of this approach is that you cannot declare the main class *sealed*. But it's tolerable. Not that many people use it anyway.

Simple code sample:

```
// This class implements the logic.
public class MainClass : MonoBehaviour {
  protected void MyUnityCallback() {
    // External callers won't be able to use this method.
  }
}

// This class exposes methods to Unity.
sealed class MainClassDecorator : MainClass {
  public new void MyUnityCallback() {
    base.MyUnityCallback();
  }
}

```

HINT. Using "debug" mode in Unity inspector you can easily replace the main class by its decorator.

HINT2. To enable debug mode in the editor, right click on the inspector tab title.
> 1 votes

# Answer
You seem to have a misconception about how accessibility-levels work in C# (or programming in general). An element marked private ***cannot*** be accessed outside of the class it's declared in, by definition.

The reason you are able to expose fields is because the editor is not working with the actual run-time instance, but rather with a serialized copy that the editor will substitute with an instance when the time is right. Fields are serializable, and serialized types that have a `Drawer` show up in the inspector, so when you override Unity's default behavior using the `[SerializeField]`, and the protected/internal/private field gets serialized, it will show up in the inspector. It's more of a consequence of how the system works, rather than actually "exposing a private field" as if it was a concrete action that could be taken.

Methods are not serializable. Methods aren't data; they are procedures. It makes no sense to serialize a definition of "how to do something". Definitions are the responsibility of the classes/assembly. --- This is also the reason why you can't deserialize data without access to the assemblies that define it. The compiler is not clairvoyant; it needs to know the format that the data is supposed to be in, in order to reassemble the data back into a concrete instance.

Since methods aren't serializable, the inspector can only know about them through reflection. And while there are ways to get references to non-public methods through reflection, it will not be something that Unity will provide out-of-the-box, because it's something that presents many problems:

* It breaks encapsulation.
* It breaks the strictness principle.
* It would lead to massive clutter.
    + The method-lists that Unity displays only show public methods; there are hundreds of non-public classes, and possibly thousands of non-public methods being omitted. The editor's reflection can't differentiate between the method you want to expose, and all other non-public stuff; it would have to show them all, and that would make the system unusable.
> -2 votes

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


title: Elegant autotiling

text:
# Question
Title: Elegant autotiling
I'm looking for information about how people implement autotiling in their tile-based games. So far I have always improvised it with a bunch of hardcoded "if ... else ..." statements, and now I decided that it is time to find some more elegant solution. I went searching on the Internet for examples of autotiling implementations and discussions on the topic, but I only came up with three articles:

(Especially the last one is comprehensive and very helpful.)

I have also looked at various implementations and documentation of libraries, that implement it, for example, flixel: http://www.flixel.org/features.html#tilemaps

Sadly, all the solutions that I could find are exactly as improvised and haphazard, as what I started with, and almost never cover all the possible cases.

I'm looking for an elegant example of autotiling implementation that I could learn from.

# Answer
I've used A Bitwise Method For Applying Tilemaps and found it to be a very elegant solution. The article provides a concrete example and discusses how to extend the algorithm to handle multiple terrain types.
> 13 votes

# Answer
I arrived here by Googling this problem myself, read the linked articles, and produced a relatively compact solution which generates the common set of 47 tiles. It requires a 2x3 tileset for the autotiled material like this:

With a single-tile variant at the top left, inner corners at the top right, and four outer corner tiles at the bottom (you may recognize this arrangement from RPG Maker).

The trick is to break each "logical" map tile into 4 half-tiles for rendering. furthermore, a half-tile in the tileset can only be in *that position* in a generated tile, so a top-left half tile can only be used in a top-left position.

These restrictions mean that you only need to check 3 full-tile neighbors per half-tile, instead of all 8 neighboring tiles.

I implemented this idea quickly to test it. Here's the proof-of-concept code (TypeScript):

```
//const dirs = { N: 1, E: 2, S: 4, W:8, NE: 16, SE: 32, SW: 64, NW: 128 };
const edges = { A: 1+8+128, B: 1+2+16, C: 4+8+64, D: 4+2+32 };
const mapA = { 0:8, 128:8, 1:16, 8:10, 9:2, 137:18, 136:10, 129:16 };
const mapB = { 0:11, 16:11, 1:19, 2:9, 3:3, 19:17, 18:9, 17:19 };
const mapC = { 0:20, 64:20, 4:12, 8:22, 12:6, 76:14, 72:22, 68:12 };
const mapD = { 0:23, 32:23, 4:15, 2:21, 6:7, 38:13, 34:21, 36:15 };

export function GenerateAutotileMap(_map: number[][], _tile: integer): number[][]
{
    var result = [];
    for (var y=0; y < _map.length; y++) {
        const row = _map[y];
        const Y = y*2;
        // half-tiles
        result[Y] = [];
        result[Y+1] = [];
        // each row
        for (var x=0; x < row.length; x++) {
            // get the tile
            const t = row[x];
            const X = x*2;
            if (t != _tile) continue;
            // Check nearby tile materials.
            const neighbors = (North(_map, x, y) == t? 1:0)
                + (East(_map, x, y) == t? 2:0)
                + (South(_map, x, y) == t? 4:0)
                + (West(_map, x, y) == t? 8:0)
                + (NorthEast(_map, x, y) == t? 16:0)
                + (SouthEast(_map, x, y) == t? 32:0)
                + (SouthWest(_map, x, y) == t? 64:0)
                + (NorthWest(_map, x, y) == t? 128:0);
            // Isolated tile
            if (neighbors == 0) {
                result[Y][X] = 0;
                result[Y][X+1] = 1;
                result[Y+1][X] = 4;
                result[Y+1][X+1] = 5;
                continue;
            }
            // Find half-tiles.
            result[Y][X] = mapA[neighbors & edges.A];
            result[Y][X+1] = mapB[neighbors & edges.B];
            result[Y+1][X] = mapC[neighbors & edges.C];
            result[Y+1][X+1] = mapD[neighbors & edges.D];
        }
    }
    return result;
}

```

Explanation:

* `A` is the top left part of the tile, `B` is the top right, `C` is the bottom left, `D` is the bottom right.
* `edges` holds bitmasks for each of these, so we can grab only the relevant neighbor info.
* `map*` are dictionaries mapping neighbor states to graphic indices in the tileset image (0..24).
    + since each half-tile checks 3 neighbors, each one has 2^3=8 states.
* `_tile` is the tile targeted for autotiling.
* Since our logical tiles are twice as large as our rendering tiles, all the autotile coords (x,y) have to be doubled in the rendering map.

Anyway, here are the results (with only one tile, anyway):
> 5 votes

# Answer
I read most of the links and spent some time to come up with another solution. I don't know if it's good or not, but to simulate the *RPG Maker VX Ace* auto-tile behavior (47 tiles) I started doing something like this:

> (left 0 or 1) + (right 0 or 1) + (up 0 or 1) + (down 0 or 1) now I have 5 cases.
>
> if 4 = Tile 46 is placed
>
> if 3 boarders =
>
> if 2 4 cases + 2 cases not sure about algorithm but not much branches to make.
>
> if 1 = working on it but every direction can end up in 4 cases
>
> if 0 = I can use the number algorithm shown in the links with 1, 2, 4, 8 and getting id from 1 to 15 I can directly use.

I am not a programmer and not the best with math algorithms and the 1, 2, 4, 8, 16, 32, 64, 128 solution I also didn't liked much.

Maybe my approach is at least better than that.
> 0 votes

---
Tags: algorithm, tiles, tilemap
---


# Question
Title: I cannot save my game data on Godot Engine
I'm trying to save my game on Godot Engine by pressing a "save" button but I get this message error when i do:

> Attempt to call function 'get\_nodes\_in\_group' in base 'null instance' on a null instance

this is my project code:

```
#File.gd, contains the methods to write and read over the file
extends Node

var path_name := "res://resource/debug/save"
var file := "sav.tres"

class_name WriterReader

func write():
    var writer := Save.new()
    var directory := Directory.new()

    writer.version = ProjectSettings.get_setting("application/config/Version")
    for node in get_tree().get_nodes_in_group("persistance"): #it's  the line that thows the error
        node.save(writer)
    print(writer.version)

    if not directory.dir_exists(path_name):
        directory.make_dir_recursive(path_name)

    if ResourceSaver.save(path_name.plus_file(file), writer) != OK:
        print("ERROR")

#the save button gdscript file
extends Button

func _ready():
    var save = Save.new()
    self.connect("pressed", self, "save_game", [save])

func save_game(save):
    var s = WriterReader.new()
    s.write()

#it's the part of code where of the player character is saving
extends KinematicBody2D
...

func save(write: Resource):
    write.dat = {"position": position, "health": health}

#sav.gd, singleton used to save the player data

extends Resource

class_name Save

var dat : Dictionary = {}
var version := ""

```

I'm a beginner on Godot so I cannot figure out why this happens.

could somebody explain me, please?

Thanks

# Answer
Your `WriterReader` is calling `get_tree` while it is not part of the `SceneTree`. You could do something like this:

```
func save_game(save):
    var s = WriterReader.new()
    add_child(s)
    s.write()

```

Since it looks like your `WriterReader` isn't designed to be part of the scene tree, it might make more sense to pass the objects into `write` from outside:

```
# in WriterReader.gd:
static func write(nodes: Array):
    # ...
    for node in nodes:
        node.save(writer)
    # ...

# in Button.gd:
func save_game(save):
    # this should work, as your Button is part of the SceneTree
    WriterReader.write(get_tree().get_nodes_in_group("persistance"))

```
> 5 votes

---
Tags: godot
---


# Question
Title: Node representations in a navigation mesh
There are different ways to represent nodes in a navigation mesh. It's either along triangle centroid, along triangle vertices or along edge midpoints.

As I understand if you choose triangle centroid or edge midpoints as nodes, the path isn't going to be optimal, but you can use a funnel algorithm to optimize it.

If you choose triangle vertices as nodes however, I understand you can find the more optimal path from get-go. But you will get a "wall hugging" issue. Which you can solve by using some algorithm I unfortunately forgot the name of.

What is the preferred or most optimal option?

# Answer
> 0 votes
I don't think there is any Generic "Optimal" way to do this. It mostly depends on your type of game.

For instance, in a RTS, you probably want to go with the center of a triangle rather than edges so that you can have lots of units walking over the Map. In a FPS you might want to use edges to get a better and more complex node mesh. So that they AI might be able to flank you etc.

Could you tell us more about the type of project you are making? This way i guess it would be easier to help you find the more optimal solution for your needs.

Good luck!

---
Tags: path-finding
---


# Question
Title: How to make a more accurate lap time? get_timer() LIMITATION?
In the room there are 22 cars. All cars have a different speed.

The cars are numbered from 1 to 22 with the help of the variable carNumber.

**CODE - obj\_Car / Set car speed (Create Event):**

```
velocity=10-((carNumber-1)*0.01);

```

---

**Here's how there is a difference in car placement near the end of the lap:**

---

**However, even with this difference, the times of many cars are repeated:**

---

The detection of lap time looks like this.

**CODE - obj\_Car / Time lap (Collision with obj\_Finish) :**

```
other.orderLapTime[car]=get_timer()-other.discount;

```

---

* Discount = this is the exact time when the room starts (cars already start running).

**CODE - obj\_Finish / Set discount (Create Event):**

```
discount=get_timer();

```

---

The display is made with a modifier (multi, to simulate actual track times).

**CODE - obj\_Finish / Draw time lap (Draw Event):**

```
draw_text(1500,100+(20*(i)),string_format(orderLapTime[i]*obj_Seth.multi/1000000,1,3));

```

---

**Even taking the multiplication and increasing the number of decimal places, there are still many repeated times:**

Some inconsistencies including. Cars with slower speeds marking faster times.

---

I could slow down the base speed (10) to solve such a problem, but I already think in the long run. The races can't take so long. In addition I intend to give the player the option to set the speed with which the race takes place (a multiplier, more frames, etc).

It could also increase the difference between the speeds (0.01 to 0.05), but I would like a general resolution, so that I can notice through the lap time, if only by one thousandth (0.001).

---

**EDIT 1 - Attempts made based on answers and comments from Bálint and TomTsagk**:

That is what I tried to do.

**CODE - obj\_Car / lap time (Step Event):**

```
unit+=velocity/60*0.001;

```

Below the results...

---

**Respective code:**

```
draw_text(1500,100+(20*(i)),string_format(orderLapTime[i],1,3));

```

---

**Respective code:**

```
draw_text(1500,100+(20*(i)),string_format(orderLapTime[i],1,5));

```

The speed difference between the cars is 0.01.

# Answer
> 0 votes
The solution I found, you should count the time using the step event at the finish line.

**obj\_Finish - step event:**

```
timer+=1;

```

And when the car collides with the finish line, just add to the timer result the distance between the origin of the car and the origin of the finish line.

**obj\_car - colision with obj\_finish:**

```
distance=point_distance(x,y,other.x,other.y);
lapTime=other.timer+distance/10;

```

That way, even if multiple cars with different speeds collide with the finish line in the same frame, the distance from each to the finish line will be different, so the time will be different.

The division by 10 made the calculation value correct, so that I could order the cars..

# Answer
> 1 votes
Your problem seems to be that you only check whether any cars have passed the finish line in every frame. Since the game has a fixed time-resolution (60Hz) it really can't tell the difference between a lot of cars. (In your second example, the difference between a lot of the displayed times are a millionth of a second, which is a microsecond, which is probably due to code execution and the general slow speed of clocks with microsecond resolution).

What you'll need to do instead is check exactly when they cross the line. The easiest option would be to just start stepping between the frames with 1000th of a second steps, each time moving the car just a tiny bit (speed in units / second * 0.001s). You'll know the exact time any car passes by counting how many steps it took to reach the goal, dividing it by 1000 and adding it to the current frame time.

---
Tags: game-maker, path, lap, time
---


# Question
Title: Navigating to android app settings > permission from unity
I am trying to rout from my unity application to android app settings permissions. till now I achieved to rout to app settings, But i want to take 1 step more to go inside permission i mean App Settings \> Permissions.

**Code:**

```
try
        {
#if UNITY_ANDROID
            using (var unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            using (AndroidJavaObject currentActivityObject = unityClass.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                string packageName = currentActivityObject.Call<string>("getPackageName");

                using (var uriClass = new AndroidJavaClass("android.net.Uri"))
                using (AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("fromParts", "package", packageName, null))
                using (var intentObject = new AndroidJavaObject("android.content.Intent", "android.settings.APPLICATION_DETAILS_SETTINGS", uriObject))
                {
                    intentObject.Call<AndroidJavaObject>("addCategory", "android.intent.category.DEFAULT");
                    intentObject.Call<AndroidJavaObject>("setFlags", 0x10000000);
                    currentActivityObject.Call("startActivity", intentObject);
                }
            }
#endif
        }
        catch (System.Exception ex)
        {
            Debug.LogException(ex);
        }

```

Help if it is possible... any help is appropriated. Thank in advance.

# Answer
I don't think it's possible to open 'permissions' page directly from the app.

However you can open settings page with Toast like, "click permissions and allow X permission to proceed", to guide the user.
> 1 votes

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


# Question
Title: How do I simulate the Doppler effect in a game?
I am trying to simulate the Doppler effect in a game (a car racing game). I am not using a specific sound library that simulates the effect; I only have a callback function where I mix the data.

I already figured out how to change frequency of a sample in the mixer function.

**What I don't know is how much the frequency should change, depending on player and emitter position and velocity.**

Here is what I have in the game:

```
//player
vec3 p.pos;
vec3 p.vel;

//emitter
vec3 e.pos;
vec3 e.vel;

```

---

1. According to Wikipedia, the relation between emitted frequency and observed frequency is given by:

```
 float f = (c + vr) / (c + vs) * fo

```

where **c** is a constant, the velocity of waves in the medium (typically a big number), and **vs** and **vr** are source and receiver velocities relative to medium.

So I guess:

```
float vr = p.vel.length; //player speed
float vs = e.vel.length; //emitter speed

```

However, I think this is wrong. It won't produce any change in frequency (for example) if `vr = 0` (player doesn't move) and the emitter has constant speed, then `vr` and `vs` won't change (while they should).

Maybe should I calculate the velocity of the player relatively to the velocity of the emitter, like this?:

```
relative_speed = distance(p.pos + p.vel, e.pos + e.vel) -
distance(p.pos, e.pos);

```

Then how should `vr` and `vs` be found?

---

2. Wikipedia gives another formula to simulate the effect of a vehicle when that vehicle passes by the observer:

```
 vr = vs * cos(theta);

 //theta is angle between observer and emitter
 //theta = atan2(e.pos.y-p.pos.y, e.pos.x-p.pos.x);?

```

However, this formula supposes that the receiver doesn't move, which is not the case here. If the player and the emitter move at same speed (or with a small difference), there should be no Doppler effect. This function is also specific to one case, I suppose the final formula should be the same no mater the situation.

---

EDIT: I'm trying to find a correct formula, using SkimFlux's post:

```
vr,r = vr.vel * cos(shortest_angle_between ( vr.vel , vs.pos - vr.pos));
vs,r = vs.vel * cos(shortest_angle_between ( vs.vel , vr.pos - vs.pos));

//is there a easier/faster way to find them out?
//note: vr.vel and vs.vel are vectors, the green and red arrows in SkimFlux's picture.

```

---

EDIT 2:

**For those interested, here is final formula:**

```
vec2 dist = vs.pos - vr.pos;

vr,r = dotproduct(vr.vel, dist) / length(dist)
vs,r = dotproduct(vs.vel, dist) / length(dist)

```

It uses vector projection:

Then `vr,s` and `vs,r` should be injected into the first Wikipedia formula:

I tested it and it works successfully, providing great results.

# Answer
1) Assumes that both objects are moving on the same line - (this is explained in the wikipedia page you linked) your conclusion is correct, in this situation, with constant velocities, the frequency shift is constant. For the frequency shift to change, the relative velocities need to change, hence formula 2), for the situation where `Vs` is constant but not colinear with the S-R axis.

Formula 2) is misleading however: `Vr` should be read as `Vs,r`, that is, the radial/relative component of the source velocity.

Please note that the Doppler effect depends only on velocities, you only need the positions to find the S-R axis.

*Edit*: this should help you figure out the velocities, you need to use the `Vs,r` and `Vr,r` quantities with formula 1:
> 9 votes

# Answer
For XACT, there is the doppler pitch scalar variable should be specified, ie relative speed, where 1.0 is the same speed, but \< 1.0 is slower and \> 1.0 is faster

Thank you guys for the code, which I've transferred to this piece of C#, where a sound is calculated between screen position and a cue. Works precisely

```
soundElements.ForEach(e =>
            {
                var cuePosition = new Vector3(e.PhysicPosition, 0);
                var distance = cuePosition - ScreenCenter;
                var distanceLength = distance.Length();
                e.Cue.SetVariable("Distance", distanceLength);
                var dopplerPitchScalar = 1.0f;
                if (e.AssociatedBody != null)
                {
                    //https://gamedev.stackexchange.com/questions/23583/how-do-i-simulate-a-doppler-effect-in-a-game
                    var screenVelocity = Vector3.Dot(ScreenVelocity, distance) / distanceLength;
                    var cueVelocity = Vector3.Dot(new Vector3(e.AssociatedBody.LinearVelocity, 0), distance) / distanceLength;
                    var relativeVelocity = screenVelocity - cueVelocity;
                    dopplerPitchScalar = (1f + relativeVelocity / SoundEffect.SpeedOfSound) / (1f - relativeVelocity / SoundEffect.SpeedOfSound);
                    //Console.WriteLine($"C: {ScreenCenter}, V: {ScreenVelocity}, D: {dopplerPitchScalar}");
                }
                e.Cue.SetVariable("DopplerPitchScalar", dopplerPitchScalar);
            });

```

Btw.
> 0 votes

---
Tags: c++, physics, sound, racing, sound-effects
---


# Question
Title: Health bar without image collapsing to the centre in Unity 2D
I am trying to create a health bar that collapse symmetrically to the centre. The color palette of my game is minimal and the health bar is only one color that does not change with size. I am new to Unity and am not sure how to achieve this.

This video uses a GameObject with an Image component, adds the health bar sprite to the image, makes the Image type fill and then changes the fill amount from the script.

I have two questions for my particular case,

1. I would prefer not to use an image. Since the bar is one color I can use color selector to make the bar, but then it does not have the fill type. Is there a way to do using only color?
2. The the bar is anchored at one end left or right. I want to anchor it at the centre. One work around is to use two objects side by side and fill them in opposite directions to get the desired effect. Is there a better way?

# Answer
> 0 votes
**tl;dr:** control the size of the health bar by changing its scale.

---

Using an UI Image is just the easiest and most lightweight way to get Unity to fill a rectangular canvas area with colored pixels. So it's the optimal thing for your use-case.

If you do not want to draw a proper health bar image yet, you can simply create a new UI image and not assign any sprite asset to it. If you leave the source image blank ("None (Sprite)"), then Unity will visualize it as a solid color rectangle in the Color you assign to the Image component in the inspector.

If you want to do a health bar which fills up and depletes, then you should first create the background as a black image and then the filling as a child of that image in the color you want. Use the Width and Height of their Rect Transform to control their size. Make them the same size, or make the filling slightly smaller so you get a visible border around it.

If you now want to change the fill-state of the health bar, do so by manipulating the scale X of the filling between 1.0 (full) and 0.0 (empty). If you already have a script which manages damage, then you might do it from there. Or you can create a new script which references both the transform of the health bar filling and a game object, checks the health of the game object in Update, and calculates the new size for the health bar filling.

The parent health bar:  The filling (set to 65% full by changing the Scale.X):

## Bonus: Controlling the fill direction

You can control the direction from which the health bar fills by changing the Pivot and Anchor in the Rect Transform of the child. The default value (both 0.5) already gets you the behavior you describe (collapsing to the center). If you want it to collapse to the left, for example (like most health bars do), set the Pivot X to 0.0 and the Anchor Min X and Max X to 0.0. You will have to correct the Width and Pos X afterwards because Unity might change those during this process.

Variant with health bar collapsing to the left:

---
Tags: unity, animation, gui, image
---


# Question
Title: In unity C#, why use the .SetBool(booleanname, boolean) command when you could just write 'booleanname = true'?
I noticed on a tutorial for unity someone used the code:

```
private Animator animator;
private bool isRunning = false;

```

While further on, did:

```
animator.SetBool("isRunning", true)

```

Why could you not just do

```
isRunning = true

```

if it is in the same class?

# Answer
> 1 votes
These two lines do different things.

```
animator.SetBool("isRunning", true)

```

This sets *The Animator's* `isRunning` parameter to true - which is likely to affect which animation state it selects / blends to within its animator control graph.

```
isRunning = true;

```

Sets *this script's* `isRunning` member variable to true. We can't see much of how this script functions or even what it is called in your example, but it sounds like it's used for local book-keeping of gameplay state, so that your control script knows it's in the "running" state and can make control decisions differently informed by that fact.

`isRunning = true` will *not* automatically change your animator's parameter states or affect how it selects animations to play. `animator.SetBool("isRunning", true)` will *not* set your control script's member variable to affect its control logic.

Depending on the design of your control script, you might need to set both the animator parameter and the control script's member variable in the same places, to keep the internal control model consistent with the animated "view" of that model state.

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


# Question
Title: How to move/rotate different parts of an entity indepently from each other?
Background: I am playing around with a simple isomorphic 3D shooter where a player controls a character which can shoot other players. Here's an example scene where you can also see the hierarchy for the game objects and the controlling script:

As you can see, I have created a simple turret which consists of three parts:

* Guns
* Torso
* Bottom

Just to be more clear, here's a screenshot of the turret close up with its armature:

In Unity, I have already created a simple `PlayerController.cs` script (see beloc) which allows a player to move the entire game object around using `W`, `A`, `S`, `D` and look using the mouse.

However, I want to rotate the Bottom independently. So if the Player moves left, the bottom should rotate towards that direction but the torso should still focus on the mouse position.

Now the first question is how I can do that. I don't know how to get access to the game objects and rotate them independently. The second question is how I can or should design the player game object s.t. I can exchange models more easily. What I mean by that is: Imagine the player switches the weapon. Obviously, only the guns should change but e.g. not the entire character. Only the mesh etc. should change dynamically.

I am sure this isn't that hard to accomplish but I couldn't find a simple example that kind of explains how to do it.

---

PlayerController.cs

```
public class PlayerController : MonoBehaviour
{

    [SerializeField]
    public float moveSpeed = 1f;
    private Vector3 _forward;
    private Vector3 _right;
    public LayerMask layerMask;

    // Start is called before the first frame update
    void Start()
    {
        this._forward = Camera.main.transform.forward;
        this._forward.y = 0;
        this._forward = Vector3.Normalize(this._forward);
        this._right = Quaternion.Euler(new Vector3(0, 90, 0)) * this._forward;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.anyKey)
        {
            this.Move();
        }

        this.MouseLook();
    }

    public void Move()
    {
        var rightMovement = this._right * Input.GetAxis("HorizontalKey");
        var upMovement = this._forward * Input.GetAxis("VerticalKey");
        transform.position += (Time.deltaTime * this.moveSpeed * Vector3.Normalize(rightMovement + upMovement));

        var heading = Vector3.Normalize(rightMovement + upMovement);
        if (Vector3.Magnitude(heading) > 0.0)
        {
            transform.forward = heading;
        }
    }

    void MouseLook()
    {
        Ray castPoint = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(castPoint, out hit, float.MaxValue, layerMask))
        {
            Vector3 direction = hit.point - transform.position;
            direction.y = 0.0f;
            transform.forward = Vector3.Normalize(direction);
        }
    }
}

```

# Answer
A few ways you can achieve that depending on how you want to set it up.

Parent //the parent with the script on it.

//the children in the parent are numerically ordered starting at 0

Guns =0

Torso =1

Bottom=2

For the guns you always have it look in the direction of the mouse position `transform.LookAt();`

For the bottom you can either rotate the object in code behind or just make a few simple move animations and set to run as you move around.

To get access to those children objects you can use `transform.GetChild()`

for example

```
var Guns = transform.GetChild(0);
var Torso= transform.GetChild(1);
var Bottom = transform.GetChild(2);

```
> 0 votes

---
Tags: unity, blender
---


# Question
Title: Efficient update of instance data for instance rendering
I started implementing instanced rendering in my 3D engine, but I quickly stumbled upon some issues that I'm not sure whats the best practice to work around.

When I setup my scene, I capture the amount of instances for every mesh and I write the transformation matrices first into a *dynamic* list and finally into an "instance buffer" (UBO) which is sent to the shaders and indexed by `gl_InstanceID` to fetch the correct transform. This is working perfectly.

So when I apply frustum culling per instance, what I do now is that once I found out that an instance should be culled, I remove this transformation matrix from the dynamic list and therefore I keep the transformation matrices of just the active instances which end up getting drawn from the `glDrawElementsInstanced`.

Obviously inserting and removing elements from this dynamic list is expensive and I want to get rid of it. So I was thinking that I'll implement a fixed length list this time consisting of per-instance structs to hold instance data something like this:

```
struct InstanceData {
    float worldMatrix[16];
    bool isOccluded;
    /* and more */
};

```

However this leads to another problem. In this case, since the draw call will render a fixed amount of instances all the time, regardless if they are visible or not, I'll have to discard the vertices in the shader, and I don't think that this is optimal either.

I've thought of other ways as well, such as sorting the instances based on their occlusion status on every frame, but then I'll have to pay the price for the sorting.

Is there any common practice to deal with instanced data? I fear that I should experiment with all the options and find what suits me best x.x

Thanks in advance

# Answer
Just have your VertexBuffer (for the insances) a fixed length (maximum allowed instances).

You also have a local buffer (array) of the same sice and an index variable. Each frame you set the index to zero and go over all of your objects. If it is in Frustum, add it to the local buffer (means: set the buffer at the current index with relevant data) and increment the index variable.

when done, you just put that data into your vertexbuffer from 0 to index and when drawing you send that buffer with a maxindex of your index. (there should be an overload when you set the data)

That way you don't need to recreate your VertexBuffer but just update it's contents (the same is true for your local buffer).

unfortunately, I can't provide any OpenGL Code so just talking about the theory how I woudld do it with DX, where there are overloads in SetData and DrawIndexedInstances, to just set/render a range of the buffer.
> 0 votes

---
Tags: instancing, asset-management
---


# Question
Title: Ledge climb animation and movement (2d platformer)
Struggling to make a decision on the implementation of a ledge climb mechanic for a physics driven 2d platformer. What is the best way to go about this without it getting overly complex?

So far I understand (hobbyist here not a pro) there a few options including:

1. Apply controlled force to the rigid body on the y axis until the root position is just above the hand position then apply enough force on the x axis so as the character is standing on the platform. At the same time somehow sync this with the climb animation(s).

**Remarks**: movement is easy here and can even be controlled by a prismatic sliding joint but I'm unsure of how I would keep the animations (spine) in sync with the movement.
2. Root motion animation that drives the root position of the character. Teleport the rigid body when complete and hope box2d can still properly respond in time to any collision if any objects happen to fall from the sky.

**Remarks**: sounds easier to actually animate but not sure if I'll run into any problems with the spine runtime, box2d or later down the line moving platforms and varied height platforms.
3. Apply IK constraint programmatically on the hands to lock them in place and proceed to rotate the bones manually or apply small preset (few keys/frames) animations whilst applying the needed force to the rigid body at the same time.

**Remarks**: seems like this would give maximum control to the player but it sounds way to complicated for me to implement at my level, not exactly sure where I would start.

Thanks in advance for any input!

FYI: This is an ECS (libgdx + ashley) based engine with box2d. The ledge grab is already implemented as a separate system so we can assume here that the character is already capable of hanging from a ledge of any height.

# Answer
i believe you need more design choices here before you can make a proper decission, specifically, what can happen to the character while he is hanging/climbing?

since you said the game is physics based i asume that you might have a rock falling on your head while either hanging or climbing, so if this is the case i believe going for rootmotion might be the simplest solution, you just need to animate the climbing, while it's climbing it's in a slightly different hanging state, the only difference being that you cannot initiate the climbing action.

Now this is assuming you have the whole hanging situation under control, meaning that if while you are hanging and any interaction happens, the character reacts properly.

Then all you need to do is to set your character's state back to idle once the climbing animation is complete.
> 2 votes

# Answer
you could just move the transform.y up n number of times until the feet are on the ledge and forget the physics temporarily, i think it will work fine, you can always measure the distance between falling objects and the player in case collision fails during a transform translation. to make sure a collision occcurs..
> 0 votes

# Answer
If the player is pressed against a climbable object then allow up/down to move it on the Y axis. During this state ensure it cannot move on the X axis. As you move you can call Animation.Sample on your climb animation to ensure the point in the animation matches the distance climbed rather than trying to time everything.
> 0 votes

# Answer
In my opinion, the "best" way would be to: When you detect climbing is possible, temporarily lock the player's position. Use the animation with root motion and lock the controls. When the animation is over, unlock the players position and controls.

Of course if you do it recklessly, it will look weird OR it will require pixel perfect precision. But you can avoid it - give the player some range where they can climb, and with a lerp quickly adjust the position to the perfect spot.
> 0 votes

# Answer
Can the player freely move horizontally while they are midair (air control)? If so, I would simply apply an appropriate amount of vertical force to get the player's feet above the platform and let the player move horizontally onto it.

This would give the player more control over the character and open up more movement options - For example, if the player (while hanging from a ledge) wanted to jump, shoot at something on the platform, then fall back down and re-grab the ledge while the projectile traveled to its target so as to dodge any projectiles the target fired back at the player. Such a tactic might make for an interesting boss fight strategy.
> 0 votes

---
Tags: 2d, libgdx, box2d, spine
---


title: Way to Round Numbers

text:
# Question
Title: Way to Round Numbers
I have it when the player clicks the mouse they can move the peice aoround the board. I am trying to have the chess pieces snap to a grid after the mouse has been released. Is there any way to round numbers so that I can round the X and Y coordinates so that it will snap to the grid?

# Answer
You will basically turn the position of your mouse click into an integer. To do this simply divide the coordinates obtained by the size of the grid you want to create (32 in my case).

Then just multiply by the same amount you divided (32 in my case).

Splitting has to be done using `div`, no `/`.

**Create Event:**

```
gridx=0;
gridy=0;

```

**Global Left Pressed Event:**

```
gridx=mouse_x div 32;
gridy=mouse_y div 32;

x=gridx*32;
y=gridy*32;

```

---

The way I suggested above is more didactic and simpler to change, but if you want it can be simply...

**Global Left Pressed Event:**

```
x=(mouse_x div 32)*32;
y=(mouse_y div 32)*32;

```
> 1 votes

---
Tags: game-maker
---


title: Way to Prevent Stacking Pieces

text:
# Question
Title: Way to Prevent Stacking Pieces
I have a chessboard with all the black pieces that move with this code: I found that when I move the pieces, they will stack on top of each other. How can I prevent this?

I have since changed the code to this:  When I move a piece over another it still picks that piece up, but now it will occasionally completely prevent any stacked pieces from moving. What can I do, and is there a way to do this while still being able to move one piece over top of another?

Also, the pieces origin and collision box ( all similar to the king) look like this:

# Answer
**Just use the function place\_empty:**

```
if(place_empty((mouse_x div 32)*32,(mouse_y div 32)*32)){
    x=(mouse_x div 32)*32;
    y=(mouse_y div 32)*32;
}

```

In my case, my piece has dimensions 32x32 and its origin is at the top left.

To understand this calculation, I recommend looking at your own question (Way to Round Numbers), the answer of which helps to understand.

If you have difficulties in this, or in converting the code to DnD, just comment.
> 0 votes

---
Tags: movement, mouse, game-maker-dnd
---


title: How to change the intensity of a light

text:
# Question
Title: How to change the intensity of a light
I just want to change the intensity of a light.

The script is already in the light object, but I can't turn it up or down to save my life, and wherever I look, no one has the answer.

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

public class Flashlight : MonoBehaviour
{

    public bool flashOn;

    void Update()
    {
        if (flashOn)
        {
            light.intensity = 0;

            if (Input.GetKey("q"))
            {
                flashOn = false;
            }
        }
        else
        {
            light.intensity = 1;

            if (Input.GetKey("q"))
            {
                flashOn = true;
            }
        }
    }
}

```

# Answer
Is `light` a reference to a component attached to a game object, presumably the same one this script is attached to? If not, you'll need a reference to it, and you'll need to assign it at some point, like so:

```
public class Flashlight : MonoBehaviour
{

    public bool flashOn;
    public Light light;

    // After saving this script, the light field should appear
    // in the inspector alongside your flashOn boolean field.
    // You may assign it manually there, or through code at runtime.
    // I prefer the latter, and it is done like so:
    public void Awake()
    {
        light = GetComponent<Light>();
    }

    void Update()
    {
        if (Input.GetKeyDown("q"))
            flashOn = !flashon;

        if (flashOn)
            light.intensity = 0;
        else
            light.intensity = 1;
    }
}

```

You may also find it useful to review the Unity API documentation for `Light.intensity` here.

I adjusted your script a little here, changing `GetKey` to `GetKeyDown`. This way it will only change the state of the flashlight once when your key of choice is pressed, rather than toggling it every frame while the key is pressed, which I assume is not the intended functionality as it would be very difficult for a player to press a button for only a single frame.

Good luck with your game!
> 0 votes

# Answer
For better performance, don't set the light every frame, instead, compare it with another boolean that keeps the last state.

```
using UnityEngine;

[RequireComponent(typeof(Light))]
public class Flashlight : MonoBehaviour
{

    public bool flashOnOff = true;
    private bool prevFlashOnOff;
    Light lt;

    void Start()
    {
        lt = GetComponent<Light>();
        prevFlashOnOff = !flashOnOff; //will force sync at first frame
    }

    void Update()
    {
        if (Input.GetKey("q")) flashOnOff = !flashOnOff;

        if (flashOnOff != prevFlashOnOff)
        {
            prevFlashOnOff = flashOnOff;
            lt.intensity = flashOnOff ? 1 : 0;
        }
    }
}

```
> 0 votes

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


# Question
Title: UE4 Code Project is not showing sub folders created within C++ Classes Folder even though they exist
These were my steps.
Created an empty code project in UDK4.
The editor starts up.
On the left bottom you have:

If you try to right click on C++ Classes,
Or select \[Add New\] while having C++ Classes highlighted
The option to add a new folder is greyed out.

This seems odd, since you can add a new C++ Class and set your sub folder in there. When the class gets created and our IDE in my case (Visual Studios) opens up the folder gets created in there no problem. I also tried setting the public or private option when making a new c++ class that just added a sub folder of /private /public where my new class gets nested in code but still not seeing the folder format display on the Unreal Editor.

So what's going on with UDK4? It seems highly unlikely that the issue is actually a bug.
Is it something I'm doing wrong? Or some second step I need to do?

Different Attempts:
1) Tried making the sub folder in the class create pop up, that created the folder in Visual Studios but still did not show up in the Unreal Editor
2) Restarted Unreal Editor to see if it would refresh the folder hierarchy, no luck.
3) Shutdown both UDK4 and VS and restarted UDK4 then VS also tried VS then UDK4 just in case as a second test.
4) Attempted to drag and drop a folder into the hierarchy from Visual Studios you just get a red O with a slash next to the mouse icon stating it wont allow it.

# Answer
You should create a folder when you are creating/adding the class, in the dialog message when it asks for the class name you can add a folder to the path.

In case that after the restart of UE4 the folder doesn't appear there could be 2 things: 1) UE4 will reflect only UCLASS files and folders - (if the folder doesn't contain any UCLASS it will not show in editor).

2) Sometimes you have to regenerate project files so UHT will pick up the newly created objects. -- Don't forget to close both UE4 and VS before doing that.
> 1 votes

# Answer
This is normal behaviour. All the C++ files header files have to be in the same folder so that Unreal can find them (and I presume VS as well) so it prevents you from adding sub-folders.
> -1 votes

---
Tags: c++, unreal-4
---


# Question
Title: Game navigation disabled after changing Quality settings
Just installed Unity 2019.11.f1(Personal)\[Window10/64bit-Dx11 on Dx10\] and ran the sample *"Lightweight rendering pipeline"* Construction Project.

At the start,the game navigation keys \[W-A-S-D\] worked **but the navigation was slow.**
So on changing the Quality settings\[Edit-ProjectSettings-Quality\] **from default "High" to "Low",** the **game navigation keys have got disabled** and the console throws the following error-

```
Converting invalid MinMaxAABB

```

On reverting back to the working "High" quality settings , **the navigation controls no longer work.**
How to resolve this issue?

# Answer
> 0 votes
**NOTE**\- *Reader's are requested to check performance of the below mentioned Packages in their own LWRP(light weight rendering pipeline) project,before not installing/uninstalling them.*

Eventhough Unity's new **Vfx/Shader Graph info shows support for LWRP projects** in the Package Manager ,but if the computer's **GPU does not support DX11**(eg Dx11 on Dx10),some issues/errors may occur which may not be obvious.

> **Obvious error's**

***Shader Graph***

`Compute shaders not supported on Gpu`

***Vfx Graph***

```
Vfx rendering requires compute shaders,no rendering will occur.

```

> ***Weird Issues***

However,along with no support for Shader/Vfx Graph ,there are some weird issues.

-**Game Navigation Controls (W-A-S-D)get disabled**,resulting in complete stalling of development.

-Also,following ***error*** is repeatedly thrown by the console

```
Converting invalid MinMaxAABB

```

However,on **uninstalling the Vfx and Shader graph packages from the LWRP project** , the game runs fine.

---
Tags: unity
---


# Question
Title: Formula for calculating time difference regardless of speed
**See the following situation:**

* The `first car` has a speed of 10 pixels per second and completes one lap in a circuit in 84 seconds.
* I want the `second car` to complete this same lap in the circuit, but in 85 seconds (1 second slower than the first car).
* For this I find that I need to slow down this second car by 0.118. Making it stay at the speed of 9.882 pixels per second.

So far no problem.

* Now using the `third car` with speed 5 pixels per second, the third car completes the lap in 167 seconds (same circuit).
* The speed of the `fourth car` is equal to the speed of third car minus 0.118 (5 - 0.118), but fourth car is not 1 second slower than third car, but 4 seconds (approximately).

Obviously the lap time is not just about the speed value. It is neither linear nor percentage.

Otherwise the third car would complete the lap in the circuit twice as long as the first car.

I would like to know how to do so that I can handle the lap time regardless of the speed of the car.

That is, the car could have 100, 80, 55... and yet I can make the car 1 tenth slower, whatever its speed.

---

**EDIT 1**

**In the examples below, car speeds will be defined by the following line of code:**

```
velocity=10.118-(car*0.118);

```

**The lap time detection in the example below was done as follows:**

```
distance=point_distance(obj_car.x,obj_car.y,obj_finish.x,obj_finish.y);

lapTime=(obj_finish.timer+distance/10)/3.395;

```

---

**The lap time detection in the example below was done as follows:**

```
distance=point_distance(obj_car.x,obj_car.y,obj_finish.x,obj_finish.y);

lapTime=obj_finish.timer+distance/10;

```

---

**The lap time detection in the example below was done as follows:**

```
lapTime=obj_finish.timer;

```

---

This is a famous circuit of Australia, I made many other from the most varied parts of the world. So it would need a general rule.

As you can see in all the examples, even though the differences between car speeds are the same, the time difference is still growing.

This is because the slower the car is, the greater its percentage loss in speed.

**Even excluding all modifiers:**

* 3.395 - This number is used to convert the finish line counter value to the real time of one lap of the circuit.
* distance/10 - This value is used so that in cases of very small differences, if the cars arrive at the same step of the game, it will have different times.

**Link to a question I also asked, which will help to understand this increase in distance:**

https://forum.yoyogames.com/index.php?threads/how-to-make-a-more-accurate-lap-time-get\_timer-limitation.69526/#post-414136

# Answer
I was making a mistake in a sum in the lap time of the circuit.

**I was doing this:**

```
lapTime=(obj_finish.timer+distance/10)/3.395;

```

**When was it to do this:**

```
lapTime=(obj_finish.timer+distance/velocity)/3.395;

```

To make the desired lap time increment, I need to know what the lap time will be at the chosen speed.

**If the lap time is 84 seconds:**

* velocity = (84/84)\*10 =\> velocity = 1\*10 =\> velocity = 10
* lapEstimated = (10/10)\*84 =\> lapEstimated = 1\*84 =\> lapEstimated = 84
* velocity = (84/(84+0.5))\*10 =\> velocity = (84/84.5)\*10 =\> velocity = 0.99408...\*10 =\> velocity = 9.9408...

**Below are the lines of code that solve my problem (I increased the lap time of all cars by 5 tenths of a second):**

```
velocity=(84/(83+car))*10;
lapEstimated=(10/velocity)*84;
velocity=(84/(lapEstimated+0.5))*10;

```

**Result:**
> 0 votes

---
Tags: game-maker, path, time
---


# Question
Title: How to prevent crafting costs and selling prices to converge in economies?
There is a pattern in player driven economies, where the production (or crafting) costs and the selling prices of items converge to a point where the profit margin becomes minuscule or even negative. Examples which come to mind are World of Warcraft and Eve Online, but I am sure you may recognize this pattern in other games (primarily MMOs) as well.

*A simple example:*
Reagent costs for a health potion is 1.0 gold in total.
Crafting process requires only some seconds.
Putting an item into the auction house costs 0.1 gold.
The auction house price ranges around ~1.1 gold. Expected total profit is around ~0.0 gold. Player invested 200 gold in order to achieve the crafting skill needed to produce it.

In EVE Online players are forced to have high skill in production and marketing in order to have *any* profits at all. For newcomers it's near impossible to do any production related activity which is even remotely worth the time.

**Why is this a problem?**
It renders crafting to be more costly than beneficial in the very most cases. However, players should be incentivized to do crafting as some secondary activity, and not be financially punished for practicing it.

So a solution which comes to my mind is to create a better crafting system (but how?). However the fundamental issue might be the natural effects of market economies. It is not unfamiliar to the real economy to follow the same pattern. It's a price mechanism to prevent over-saturation and challenge business sustainability: If your product costs more than its production, that business is not sustainable; and if there is too much competition, you have to set your prices too low in order to keep up.

Let's stick to WoW and EVE Online as basic reference examples.
**The questions are:**

* Is this an issue at all which deserves to be fixed? Can it be fixed at all on a large scale?
* How can you fix it, or at least reduce that price pattern from occurring that much?
* Is there a way to have that solution remain being free market based and player driven?

# Answer
> 5 votes
The reason is often that the crafting process itself has no cost. If crafting is nothing but pressing a button, then you can not expect players to pay each other just to press that button.

If you want crafting to create value in your game economy, then you **have to make crafting itself more expensive for the player**.

* Make crafting more complicated than pressing a button. You could, for example, have minigame-based crafting which takes a while to craft an item. Just make sure the minigame is actually interesting to play.
* Add another cost for crafting which isn't tradeable, like a slowly replenishing stamina stat. This limits the crafting output of each player-character and forces them to carefully think what to craft. This in turn creates a scarcity of crafting services which drives up the price.

Another option is to **allow players to form local monopolies or cartels** in order to drive up prices. This requires two things:

* Small, controllable markets. You can achieve that by making it difficult and/or costly to transfer items from one game location to another, so you allow local markets to form. That means a global trade house is anathema to this strategy.
* Players are forced to specialize in one crafting discipline, but also require the services of a lot of crafting disciplines. So there might be a situation where there is only one potion brewer in a location but lots of players who need potions. The potion brewer is now able to dictate prices.

For completeness, I would like to also add a 3rd option which unfortunately is unlikely to work. You could always use your powers as game developer and do some **price manipulation through the NPCs** in your game. If you put an NPC in the game who buys potions crafted by players for 1 gold, then no player will be able to buy a potion from another player for less than 1 gold. But now you have a couple problems:

* You no longer have a free market economy in your game. (Ok, but who needs that anyway if you can create the illusion of one through NPCs?)
* You just created another money faucet which leads to inflation. (Ok, but that could be counter-balanced by adding more money drains).
* You might notice that players will increase the price at which they trade crafting material cost because the crafters can afford to pay more. And again, market equilibrium will be that crafters make little to no profit. Well, you *could* counter that problem in the same manner: add NPCs who sell crafting materials and thus put a hard limit on their maximum price. But then you will realize that you have a problem which is **not ok**: crafters suddenly have a very easy time to generate lots and lots of money from nothing. You are back at the root cause of the problem: crafting itself is just too cheap and easy for the players.

---
Tags: game-design, economy
---


title: 3D A* Pathfinding Algorithm Help

text:
# Question
Title: 3D A* Pathfinding Algorithm Help
I want to make a 2D turn-based-strategy board game, so I'll need to give my game some pathfinding logic so that units know how to move from place to place. However, I want my levels to have multiple floors, bridges, tunnels, cliffs, etc, so I need a pathfinding algorithm that works in 3D.

Many searches have pointed me the direction of using a navmesh, but since I don't know what my terrain's geometry will be like (I'm in the very beginning stages of development), I don't think that I want to go that route. Instead, I've been following Sebastian Lague's A\* Pathfinding tutorial with Unity and slightly modifying it for usage in a 3D space.

I've gotten to the point where the algorithm is supposed to work, but the algorithm is not returning a path. Can someone help me figure out where I've gone wrong?

I know it's a lot, but here is my code:

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

public class aStarPathfinding : MonoBehaviour
{
    public GameObject[] pathTargets;
    public List<Node> path;
    public Vector3 areaSize;
    public static Vector3 nodeSize = Vector3.one;
    Vector3 gridOrigin;

    public class Node
    {
        // position of the node in world space
        public Vector3 worldPosition;
        // is walkable
        public bool walkable = true;
        // parent node during pathfinding
        public Node parent;
        // grid positions
        public int xGrid, yGrid, zGrid;
        // costs
        public int gCost, hCost;
        public int fCost
        {
            get
            {
                return gCost + hCost;
            }
        }

        // find distance between two nodes
        public static int GetDistance(Node start, Node end)
        {
            // calculate deltas in all dimensions
            int dX = Mathf.Abs(start.xGrid - end.xGrid);
            int dY = Mathf.Abs(start.yGrid - end.yGrid);
            int dZ = Mathf.Abs(start.zGrid - end.zGrid);

            // sort the deltas in ascending order
            List<int> moves = new List<int>();
            moves.Add(dX);
            moves.Add(dY);
            moves.Add(dZ);
            moves.Sort((a, b) => a.CompareTo(b));
            // use the list to calculate the g cost
            return 17 * moves[0] + 14 * (moves[1] - moves[0]) + 10 * (moves[2] - moves[1]);
        }

        // constructor
        public Node(Vector3 worldPosition, int xGrid, int yGrid, int zGrid)
        {
            // set the world position and grid positions
            this.worldPosition = worldPosition;
            this.xGrid = xGrid;
            this.yGrid = yGrid;
            this.zGrid = zGrid;
        }
    }

    public Node[,,] grid;

    private void Start()
    {
        CalculateGrid();
    }

    private void Update()
    {
        if (pathTargets.Length == 2 && Input.GetKeyDown(KeyCode.Space))
        {
            CalculatePath(pathTargets[0].transform.position, pathTargets[1].transform.position);
        }
    }

    void CalculateGrid()
    {
        // create grid
        grid = new Node[Mathf.FloorToInt(areaSize.x / nodeSize.x), Mathf.FloorToInt(areaSize.y / nodeSize.y), Mathf.FloorToInt(areaSize.z / nodeSize.z)];

        // calculate grid origin
        gridOrigin = transform.position;
        gridOrigin.x -= grid.GetLength(0) / 2 * nodeSize.x;
        gridOrigin.y -= grid.GetLength(1) / 2 * nodeSize.y;
        gridOrigin.z -= grid.GetLength(2) / 2 * nodeSize.z;
        gridOrigin -= Vector3.up * nodeSize.y;

        // populate grid with nodes
        int x = 0;
        int y = 0;
        int z = 0;

        // iterate through the dimensions
        while (y < grid.GetLength(1))
        {
            while (x < grid.GetLength(0))
            {
                while (z < grid.GetLength(2))
                {
                    // create node
                    Node n = new Node(gridOrigin + new Vector3(x * nodeSize.x, y * nodeSize.y, z * nodeSize.z), x, y, z);
                    if (n.walkable) grid[x, y, z] = n;
                    z++;
                }
                z = 0;
                x++;
            }
            x = 0;
            y++;
        }

    // convert world position to node
    Node GetNodeFromWorldPoint(Vector3 worldPos)
    {
        // determine the point's position on the grid
        Vector3 v = worldPos - gridOrigin;
        int x = Mathf.FloorToInt(v.x / nodeSize.x);
        int y = Mathf.FloorToInt(v.y / nodeSize.y);
        int z = Mathf.FloorToInt(v.z / nodeSize.z);

        // determine whether point is inside the pathfinding area
        if (x < 0 || x >= grid.GetLength(0)) return null;
        if (y < 0 || y >= grid.GetLength(1)) return null;
        if (z < 0 || z >= grid.GetLength(2)) return null;

        // return the new node
        return grid[x, y, z];
    }

    // calculate path given two nodes
    void CalculatePath(Vector3 startPosition, Vector3 endPosition)
    {
        // calculate start and end nodes
        Node startNode = GetNodeFromWorldPoint(startPosition);
        Node targetNode = GetNodeFromWorldPoint(endPosition);
        if (startNode == null) throw new System.ArgumentException("The start position must be within the pathfinding area.");
        if (targetNode == null) throw new System.ArgumentException("The end position must be area.");

        // create open and closed sets
        List<Node> openSet = new List<Node>();
        HashSet<Node> closedSet = new HashSet<Node>();
        openSet.Add(startNode);
        closedSet.Add(targetNode);

        // iterate through the open set
        while (openSet.Count > 0)
        {
            // find the node in the open set with the lowest f cost OR the lowest h cost
            Node currentNode = openSet[0];
            for (int i = 1; i < openSet.Count; i++)
            {
                if (openSet[i].fCost < currentNode.fCost || openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost)
                    currentNode = openSet[i];
            }

            // remove the current node from the open set
            openSet.Remove(currentNode);
            closedSet.Add(currentNode);

            // path found
            if (currentNode == targetNode)
            {
                List<Node> path = new List<Node>();
                // retrace the path
                while (currentNode != startNode)
                {
                    path.Add(currentNode);
                    currentNode = currentNode.parent;
                    path.Reverse();

                    this.path = path;
                    return;
                }
            }

            // check all neighbors of the current node
            foreach (Node neighbor in GetNeighborsToNode(currentNode))
            {
                // if the neighbor is not walkable or closed
                if (!neighbor.walkable || closedSet.Contains(neighbor)) continue;

                // calculate f cost of neighbor
                int newMovementCostToNeighbor = currentNode.gCost + Node.GetDistance(currentNode, neighbor);
                if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor))
                {
                    neighbor.gCost = newMovementCostToNeighbor;
                    neighbor.hCost = Node.GetDistance(neighbor, targetNode);
                    neighbor.parent = currentNode;

                    // add neighbor to open set
                    if (!openSet.Contains(neighbor))
                        openSet.Add(neighbor);
                }
            }
        }
    }

    // find all neighbors to the node
    public List<Node> GetNeighborsToNode(Node n)
    {
        // get starting location
        int xStart = n.xGrid;
        int yStart = n.yGrid;
        int zStart = n.zGrid;
        List<Node> neighbors = new List<Node>();

        // search in 3x3x3 block centered on original node
        for (int y = -1; y <= 1; y++)
        {
            int yCurrent = yStart + y;
            for (int x = -1; x <= 1; x++)
            {
                int xCurrent = xStart + x;
                for (int z = -1; z <= 1; z++)
                {
                    int zCurrent = zStart + z;
                    // skip center block
                    if (x == 0 && y == 0 && z == 0) continue;
                    // skip blocks that would be outside the grid
                    if (xCurrent < 0 || xCurrent >= grid.GetLength(0) || yCurrent < 0 || yCurrent >= grid.GetLength(1) || zCurrent < 0 || zCurrent >= grid.GetLength(2)) continue;
                    // if there is a node at the queried grid location, add it to the list of neighbors
                    Node neighbor = grid[xCurrent, yCurrent, zCurrent];
                    if (neighbor != null) neighbors.Add(neighbor);
                }
            }
        }

        return neighbors;
    }
}

```

I know that the methods `GetNeighborsToNode` and `GetNodeFromWorldPoint` work fine due to some OnDrawGizmos methods that I've ommitted to make the post shorter, but I've included those two methods for completeness and context. I also omitted a Debug.Log that showed me the total number of iterations after the `CalculatePath` method had no more nodes to check, and no matter where i placed my start and end nodes, the number of iterations was always the same.

Can anyone help me?

UPDATE: So I edited my code so that I can step through it using the space key, and the pathfinding works fine until it reaches the target node, at which point `currentNode == targetNode` will always return false, even if the two nodes are the same. To check if they are the same instance, I checked the grid coordinates (which matched) and also set up a test to change a dummy property of the Node using the `currentNode` reference, then checked the `targetNode` reference to see if it changed, and it did not, which confirms that they are referencing two different instances.

To confirm that there were no other issues with the algorithm, I changed it to compare the coordinates of the current and target nodes rather than comparing the nodes themselves, and it worked perfectly.

# Answer
I was stepping through the algorithm using debugs to highlight nodes and color coding them based on what was being queried, and I realized that during the setup of the algorithm, `targetNode` was being added to the closed set, thus making it so that `targetNode` will never be `currentNode` since `currentNode` is only ever chosen from the open set.

Removing the line...

```
closedSet.Add(targetNode);

```

...seems to have solved the issue.

It's strange however that I was still able to reach a node with the same co-ordinates as `targetNode` without it actually being `targetNode`. I'll update this answer if I figure that part out.
> 1 votes

---
Tags: unity, c#, path-finding
---


# Question
Title: SFML function does all the job with setting up timestep?
Usually i set up timestep something like this:

```
timestep=1.0f/60.0f;
if(time>=timestep)
{
update;
time-=timestep;
}

```

But SFML has the next function: window.setFramerateLimit(). Does it do the same thing i described above?

# Answer
The function in question doesn't account for the actual frame rate being achieved. It just stalls the program to ensure a certain frame rate isn't surpassed.

For example, if you set the limit to 60, your program updates and draws at a constant maximum speed of 60Hz, but it's also possible everything sled down more while under heavy load.

In most cases you'd still want to implement your game update the way you suggested.
> 2 votes

---
Tags: sfml
---


# Question
Title: Is it a good idea to implement a MVC pattern into my LibGDX 2D RPG-style game?
For example I currently have a Player object that contains it's textures/animations and how to render these (I'd consider this as the view). Player also has an update() method which controls where the player is going to move, if it's going to lose health etc. (controller). Finally Player also has all it's attributes like runspeed, health, max health, inventory items etc.

The Player class is starting to look very cluttered and unorganized and serializing the complete Player class isn't really possible, so I made a separate PlayerState class which basically contains all it's attributes that could be changed while playing (This could actually be turned into the PlayerModel). I was wondering if it would be a good idea to split the Player up using a MVC pattern. I would have a Player, PlayerController and PlayerRenderer. Serializing the Player would be easy and it would be easier to keep the rendering separate from the updating and make sure rendering only happens when everything for the next frame has been updated.

This seemed like a good idea, however then I would also want to do this for GameMap. A GameMapRenderer that renders the map and it's textures to the screen. A GameMap model that contains what animals and hostiles are in the map and other various attributes the map might have. And of course a controller that controls everything that happens in that map.

I could go even further and say a Pig may need a model since it has attributes that can change, a renderer to render it's texture and a controller to control movement etc. but this seems a bit excessive. However, I don't like only implementing the MVC pattern to the player and then ignoring it for other classes like Pig. But the way I'm working currently is very badly structured imo and it's frustrating to work with.

# Answer
> 1 votes
## tl'dr

Design Pattern can show you a solution, how this pattern helped many others. If it is suitable for your problem is only known by **you**. Design Patterns are rather independent of applied technologies (LIBGDX).

## Details:

MVC is a Design Patter that evolved from the UI-Design-Problems in the late 70s. What you are trying to explain looks to me like you're trying to do the MVP (Model-View-Presenter), which is similar but might be worth a look.

## Summary

your Question is too broad and any answer would be strongly opinion based -\> maybe you close it / refine it?

---
Tags: java, libgdx, mvc
---


# Question
Title: C++ Wrapper class for raw pointer to an SDL_Texture
First time in game dev, so go easy on me. I understand it's senseless to copy textures, but I'm trying to see this from a copy/move perspective since there is a lot of that going on in my code and in general, for proper memory management.

Deep copying an `SDL_Texture` is a no-no since its implementation is hidden. Besides I mostly initialize and destroy it using `SDL_CreateTextureFromSurface` and `SDL_DestroyTexture`. My next approach was wherever there would be an `SDL_Texture*` class member I would try to wrap it in a `std::shared_ptr<SDL_Texture>`, but even that didn't work because of the incomplete type error.

**My main question is this:**
Would the proper way of handling a raw `SDL_Texture*` pointer getting passed around everywhere, be to create a wrapper\_class, for example

```
class WTexture {
    public:
    // constructor, destructor and everything else needed

    private:
    SDL_Texture* tex;
    //...

}

```

so, that in every class that has an `SDL_Texture* tex;` member I would swap it with `std::make_shared<WTexture> tex;`? Meaning that I can safely pass around the texture and it will only be deleted at the end of the program when the reference count reaches zero?

# Answer
Shared pointers make sense when you have unclear ownership and unclear lifespan; otherwise they're just a dead weight you're dragging around. For most games you want to have a defined build-up and tear-down points where you load all your data and dump all your data. For example, at level load and level complete.

In this case you can just use a nice, clean, raw pointer throughout your code and have another object responsible for loading and deleting the textures (or whatever) at either end of the level. Providing you clean up everything referencing the pointer before calling the cleanup this is perfectly fine.
> 3 votes

---
Tags: c++, sdl, resource-management
---


# Question
Title: Why is Instantiate spawning too many clones?
just at a bit of an impasse with this one if anyone can help.

I am developing an endless runner, and I am trying to instantiate my obstacle prefabs by having my player go through a trigger which activates an instantiation. The problem I'm having is that when the player goes through the trigger, my code seems to instantiate multiple prefabs at a time. I'll post screenshots and my code to illustrate this better.

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

public class ObsGenerator : MonoBehaviour
{

    public GameObject spawnTrigger;
    public GameObject Player;
    [SerializeField] private List<Transform> obstacleList;

    public Transform spawnLocation;

    public void OnTriggerEnter2D(Collider2D Player)
    {
        if (Player.CompareTag("Respawn"))
        {
           // for (int i = 0; i < obstacleList.Count; i++)
            {
                spawnObstacle();

            }
        }
    }

    public void spawnObstacle()
    {
        for (int i = 0; i < obstacleList.Count; i++)

            if (obstacleList.Count > 0)
            {
                Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count)];
                Instantiate(chosenLevelPart);
            }
        }
    }

```

Really appreciate anybody's help!

# Answer
When you enter the trigger and spawn the obstacle you then were looping through and spawning once for every item in the obstacle list

```
public void OnTriggerEnter2D(Collider2D Player)
{
    if (Player.CompareTag("Respawn"))
    {
            spawnObstacle();
    }
}

public void spawnObstacle()
{
        if (obstacleList.Count > 0)
        {
            Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count)];
            Instantiate(chosenLevelPart);
        }
    }
}

```
> 2 votes

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


title: Unity change scene with button

text:
# Question
Title: Unity change scene with button
I already understand how to do this but the problem I'm having is:

When I go from "MainMenu" to "Level01" and then back, the buttons lose their reference. How can I fix this?

```
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LevelManager : MonoBehaviour
{
    private static LevelManager Instance;
    public static int CurrentScene;

    private void Start()
    {
        if(Instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
            Instance = this;
        }
        //LevelManagerStartup();
    }

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.R))
        {
            if(CurrentScene != 0)
            {
                LoadScene(CurrentScene);
            }
        }

        if(Input.GetKeyDown(KeyCode.M))
        {
            if(CurrentScene != 0)
            {
                LoadScene(0);
            }
        }
    }

    public void LoadScene(int BuildIndex)
    {
        CurrentScene = BuildIndex;
        SceneManager.LoadScene(BuildIndex);
        if(CurrentScene == 0)
        {
            LevelManagerStartup();
        }
    }

    private void LevelManagerStartup()
    {
        //get a refarance to the highscoer manager
        Debug.Log(CurrentScene);
        if(CurrentScene == 0)
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
            RefButtons();
        }
        else
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
        //make sure this stuff working.
        Debug.Log("LevelManager");
    }

    private void RefButtons()
    {
        GameObject ButtonHolder = GameObject.Find("ButtonHolder");
        Button[] buttons = new Button[3];
        for(int i = 0; i < ButtonHolder.transform.childCount; i++)
        {
            buttons[i] = ButtonHolder.transform.GetChild(i).GetComponent<Button>();
            buttons[i].onClick.AddListener(() => LoadScene(i));
        }
    }
}

```

# Answer
> -1 votes
To solve I made everything static.

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


# Question
Title: How to set rotation of object using angle between two points?
I have a LineRenderer that draws a line between two points, Vector3 startPos and Vector3 endPos. How can I get the angle between these points, and apply it to an objects transform rotation, so that it points in that direction?

Here is my code that draws a line between 2 points by dragging your mouse, if you want to test just Replace the Interact methods with `Input.MouseButtonDown(1)`, hold and up.

```
Vector3 startPos;
Vector3 endPos;
float angle;

LineRenderer lr;

private void Awake()
{
    lr = GetComponent<LineRenderer>();
    lr.useWorldSpace = true;
}

public override void InteractOnDown()
{
    base.InteractOnDown();

    lr.enabled = true;
    lr.positionCount = 2;
    startPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point;
    lr.SetPosition(0, startPos);
}

public override void InteractOnHold()
{
    base.InteractOnHold();

    endPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point;
    lr.SetPosition(1, endPos);
}

public override void InteractOnUp()
{
    base.InteractOnUp();

    lr.positionCount = 0;
    lr.enabled = false;
}

```

# Answer
> 3 votes
You should always question whether an angle is actually necessary, or if a vector would suffice.

Here, all we need is the vector from the start to the end:

```
Vector3 direction = endPos - startPos;

```

Then you can use that vector to align the forward vector of your transform:

```
transform.forward = direction;

```

Or you can compute a new orientation with `transform.rotation= Quaternion.LookRotation(direction, localUp)` if you want more control over the object's twist around this direction axis.

---
Tags: unity, c#, rotation, linear-algebra
---


# Question
Title: Unity scene has phantom models in every scene new and existing a like even when deleted
I have asked about this over at Unity Forums but have not got a response yet. My issues is that in the image below all there is is a light source but several of my monster models are in the scene somehow. I cannot select them or interact with them in any fashion. The are there whether it is an existing scene or I create a new scene. If anyone has any clue what this is from it would be a great help because it is driving me madd! Thanks!

# Answer
> 1 votes
It is in fact a bug. You have to restart Unity a couple of times but then they disappear. Not sure what the editor is holding onto to make this happen. But after 3 restarts of Unity everything is normal again.

---
Tags: unity
---


# Question
Title: Handling multiple agents in astar pathing
When working with grid based path finding in how do you normally handle different agent types? In the game I am working on I have a regular agent, and one that occupies 2 cells on the grid, and one that can fly. The idea I have now is to use a separate AStar map to store the grid for each type. The height is max 4 units so I can use AStar for flying as well.

This keeps it possible to add new actor types as well but is it waste of memory? Also how to deal with avoiding nodes occupied by other agents? The game is turn based so I don’t want to do any object avoiding type thing. Is there a simple way to mark a node in the AStar as temporarily unwalkable?

I am using the Godot Engine and would like to use the in built astar implementation but I can create my own if really needed.

# Answer
> 1 votes
> This keeps it possible to add new actor types as well but is it waste of memory?

Each time you create a new AStar grid, you will be ocuppying more memory. If it is a waste or not depends on the size of the grid and the utilization frequency.

> Also how to deal with avoiding nodes occupied by other agents? The game is turn based so I don’t want to do any object avoiding type thing. Is there a simple way to mark a node in the AStar as temporarily unwalkable?

You can

* `remove_point ( int id )` : Remove the node where the another agent is
* `set_point_weight_scale ( int id, float weight_scale )` : Set a very high weight for that node in particular
* `set_point_disabled ( int id, bool disabled=true )` : Disable the node

Remember to undo the modification after the pathfinding

You can check for more on the Godot AStar documentation

---
Tags: path-finding, godot
---