# Question
Title: Something is preventing my NavMeshAgent from moving
I apologize for the vague title. I really wish I could ask something more specific, but I can't. I had my click-to-move script working fine with the NavMesh. I showed it to my colleague earlier today, and must have accidenntally made a change and saved. Now the guy's not walking.

There are no errors and my debugging leads me to believe all code paths are working as expected. When I click on a location, it checks that it is valid on the NavMesh, then updates the NavMeshAgent's destination:

I am not going to post the code because I don't think the problem resides there, but rather it was something I did in the editor. The character also turns in the correct direction, and starts the walk animation correctly, but it looks like something is blocking its movement, and I can't figure out what that is.

The following screenshots will help clarify my situation. Note that the camera is shaking because its position is set to match the character's in Update. The character appears to be colliding with something, which makes it look like the camera is colliding too (note this is not a physics-based game in any way).

*edit* here's some more screenshots, showing the person slightly above the ground and their collider (it's the box near their feet). I disabled the collider on the floor so there are no colliders other than the player's.

# Answer
> 5 votes
So it turns out it was something to do with a change I made to my Animator (not sure what, will debug later).

The takewaway here is that if you encounter a wierd bug like this, try disabling *every* component one-by one, don't assume that because the component doesn't seem related it can have no effect.

*edit* and use source control

*edit2* figured out specifically what the issue was. When I was showing my friend how Unity animations work I made one that animates the player's *position*. This was overriding the NavMeshAgent's destination. The wierd thing is, this particular animation is never triggered by the scene. **Just having a defined animation which changes the player's position was enough to prevent it from moving**.

# Answer
> 3 votes
I had a similar problem, so I turned off **Apply Root Motion** in my character's **Animator** component.

# Answer
> 1 votes
I had a probem where My enemey was rotating but not moving , turns out I had to turn root motion on... It took me 5 hours to find that fix and I butchered my script to fin

---
Tags: unity
---


title: Correct normal map for rotated sprites

text:
# Question
Title: Correct normal map for rotated sprites
I am trying to find the best way to correctly do normal mapping in a 2D batched sprite renderer.

For each sprite sheet (aka texture atlas) I render all sprites as a textured quads with a single `glDrawElements()` call. Therefore, vertex coordinates in VBO are already transformed (on CPU) according to sprite position, rotation and scale.

Unfortunately, on rotated sprites normal map texture is also rotated, leading to incorrect normals:

I did a bit of research on this subject and so far I found few possible solutions:

1. Pass **tangents** to shader. Pretty straightforward, the same way it's usually done for 3D models. While this approach would work, doing it for just simple 2D sprites seems quite wasteful.
2. Pass just **sprite rotation** in additional vertex attribute. Then I could use this attribute in the fragment shader to rotate normal vector accordingly.
3. Use **dFdx(), dFdy()** functions. It looks like I could use these functions to deduce transformation from screen to texture coordinates and then use it to rotate normals. To be honest, this approach is not entirely clear to me, and I don't fully understand its possible performance implications, especially on mobile platforms.
4. Use **geometry instancing**. I think if I use `glDrawElementsInstanced()` and just dump all the sprite coordinates + transformations in one giant texture buffer, I then could use this information in the fragment shader to rotate normals. But as with approach #3, I don't fully understand if it could lead to possible performance or compatibility issues on mobile platforms.

So far I think approach #2 is probably the better solution. Not only it is simple and requires minimal changes to the code, but it would also allow me to offload sprite rotation calculations from CPU to GPU. I'd still have to pass sprite rotation per-vertex (and not per-sprite), but I don't think this is to big overhead.

But maybe there is a better, more elegant or more performant solution to this problem? How this is typically done in 2D games?

# Answer
> 1 votes
Assuming you have access to the code of the shader and not using a "magic" library.

Instead of rotating the normal texture, you could modify the direction of the normal vector. Since on the normal map, the colors are actually "vectors", you can easily swap the direction of a vector adding a minus before the coordinate/direction at fault. In the following video, the direction of the lightning is facing the wrong direction on the x axis. By adding a minus sign in front of it in the fragment shader code, it fixes the problem: https://youtu.be/BCGKsh51TNA . In your case, you may have to swap 2 of the directions. Hope that helps.

# Answer
> 1 votes
this is how I solved this issue for myself. I hope it helps , )

In the frag shader the important bits are. . .

```
vec2 rotate(vec2 v, float a) {

   float s = sin(a);
   float c = cos(a);
   mat2 m = mat2(c, -s, s, c);
   return m * v;
  }

void main() {
    ....
    ....
    //The delta position of light
    vec3 LightDir = vec3(LightPos.xy - (gl_FragCoord.xy / Resolution.xy), LightPos.z);

    LightDir.xy = rotate(LightDir.xy,Angle); //uniform Angle is the angle of the sprite

    ....
    ....    }

```

whole thing looks like:

```
//attributes from vertex shader
varying vec4 vColor;
varying vec2 vTexCoord;

//our texture samplers
uniform sampler2D u_texture;   //diffuse map
uniform sampler2D u_normals;   //normal map

//values used for shading algorithm...
uniform vec2 Resolution;      //resolution of screen
uniform vec3 LightPos;        //light position, normalized
uniform vec4 LightColor;      //light RGBA -- alpha is intensity
uniform vec4 AmbientColor;    //ambient RGBA -- alpha is intensity
uniform vec3 Falloff;         //attenuation coefficients
uniform float Angle;

vec2 rotate(vec2 v, float a) {
    float s = sin(a);
    float c = cos(a);
    mat2 m = mat2(c, -s, s, c);
    return m * v;
}

void main() {
    //RGBA of our diffuse color
    vec4 DiffuseColor = texture2D(u_texture, vTexCoord);

    //RGB of our normal map

    vec3 NormalMap = texture2D(u_normals, vTexCoord).rgb;

    //The delta position of light
    vec3 LightDir = vec3(LightPos.xy - (gl_FragCoord.xy / Resolution.xy), LightPos.z);

    LightDir.xy = rotate(LightDir.xy,Angle);

    //Correct for aspect ratio
    LightDir.x *= Resolution.x / Resolution.y;

    //Determine distance (used for attenuation) BEFORE we normalize our LightDir
    float D = length(LightDir);

    //normalize our vectors
    vec3 N = normalize(NormalMap * 2.0 - 1.0);
    vec3 L = normalize(LightDir);

    //Pre-multiply light color with intensity
    //Then perform "N dot L" to determine our diffuse term
    vec3 Diffuse = (LightColor.rgb * LightColor.a) * max(dot(N, L), 0.0);

    //pre-multiply ambient color with intensity
    vec3 Ambient = AmbientColor.rgb * AmbientColor.a;

    //calculate attenuation
    float Attenuation = 1.0 / ( Falloff.x + (Falloff.y*D) + (Falloff.z*D*D) );

    //the calculation which brings it all together
    vec3 Intensity = Ambient + Diffuse * Attenuation;
    vec3 FinalColor = DiffuseColor.rgb * Intensity;
    gl_FragColor = vColor * vec4(FinalColor, DiffuseColor.a);
  }

```

result:

---
Tags: 2d, opengl-es, normals, normal-mapping, opengl-es3
---


# Question
Title: Unity Timeline character transform initial values
I'm trying to make a runtime cutscene in Unity using the Timeline editor. I have a humanoid character with an animation controller, track and a cinemachine track set-up in the playable. The timeline starts playing onTriggerEnter() through script. Initially I applied the track offsets and the timeline plays perfectly in the editor but in play mode the player swaps to random positions in the world and it looks really ugly. So I changed the track offsets to scene offsets and it's almost works perfectly except that the position and rotation of the character are relative to the input just before the character enters the trigger (all input is disabled on trigger entered).

What I intend to do is set a default position and rotation to the character at the beginning of the timeline. Is there any way to achieve that within the timeline editor, if not how else could I do it?

# Answer
I managed to fix my issue. The problem was 'root motion' was enabled on the character's animator. Disabling that during the timeline worked just fine with the provided track offsets.
> 1 votes

---
Tags: unity, animation, cutscene
---


title: 2D party follow the leader in Unity?

text:
# Question
Title: 2D party follow the leader in Unity?
I am attempting to make a 2d side-scrolling platformer where the player collects other characters as they advance through the levels, like you would in a classic top down rpg. However, I am having a huge issue in getting the other members of the party to actually follow the leader's direct path. I can get them to follow smoothly, however, I want them to follow the players direct path at an offset from the player.

Most codes I have found tutorials or any advice over seem to only address following the player smoothly, however, it doesn't work very well for platformers, where the party members should do exactly as the player does, slightly delayed. Is there anyone who has advice for achieving this behavior? It's been killing me for the past few days trying to make it work, in all honesty.

# Answer
> 2 votes
You just have to make the other characters do exactly the same things the player-character does, but with a delay. So you have to create a script which records the actions of the player and then allows to retrieve the player's position X steps ago.

The C# standard already has the ideal data-structure for that, the `Queue`. It allows you to create a first-in-first-out buffer of a fixed size where you can add elements to the end with Enqueue and remove elements from the beginning with Dequeue.

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

public class FollowTheLeader : MonoBehaviour {
    public GameObject leader; // the game object to follow - assign in inspector
    public int steps; // number of steps to stay behind - assign in inspector

    private Queue<Vector3> record = new Queue<Vector3>();
    private Vector3 lastRecord;

    void FixedUpdate() {
        // record position of leader
        record.Enqueue(leader.transform.position);

        // remove last position from the record and use it for our own
        if (record.Count > steps) {
            this.transform.position = record.Dequeue();
        }
    }
}

```

This script is just a very simple proof-of-concept. It only copies the position, but you likely also want it to copy the player's rotation (or at least the direction it faces), what action it performs (walking, jumping, etc.) and also handle a couple other edge cases specific to your game. So you will likely need to record more in the queue than just a Vector3. If that is the case, create your own `struct` type with all the data you need and use that as the type of your queue.

It might get even more complicated if you don't just want the followers to move onto the exact position of the leader but leave them some personal space when standing. The naive solution would be to just not dequeue the next action if the distance to the leader is too short. But this could lead to some weird situations. For example, if the player jumps, you might not want the follower to stop mid-air. You might want them to wait until the player completed the jump. So you might want to use `record.Peek()` to look at the next action in the queue without removing it and if you find that it is a "start to jump" action, then don't dequeue it while the leader is still in the air. Or alternatively you could have certain "uninterruptible" actions like jumping and have the follower ignore the minimum distance during these actions.

And then there is the question: Do you want the follower to be able to fail? You could give it its own collision physics, but then you will have situations where the follower is no longer able to do what the leader did (like jumping on a moving platform which isn't there anymore). What happens now? You could do it like *Sonic 2* did and have the follower just try anyway, die, and then miraculously return after a short while. But that kind of slapstick humor might not be appropriate for the theme of every game. If you want the followers to act more competently, then you will have to implement 2d platformer pathfinding. But this can get really complicated, especially with changing environments.

---
Tags: unity, c#, 2d, movement, ai
---


# Question
Title: Rotate a 2D object slowly to the touch position in Unity
I am creating a circular Joystick like setup in Unity. Played a lot with it in different ways but I don't get the desired results.

```
void Update()
     {
         //movement = Input.GetAxisRaw("Horizontal");
         if (Input.touchCount > 0)
         {
             touch = Input.GetTouch(0);
             if (touch.phase == TouchPhase.Began)
             {
                 firstTouchY = touch.position.y;
             }

             if (touch.phase == TouchPhase.Moved)
             {
                 if (touch.deltaPosition.y < 0)
                 {
                     movement = -1;
                 }
                 else if (touch.deltaPosition.y > 0)
                 {
                     movement = 1;
                 }
                 rotatePlayer();
             }
         }
     }

     private void rotatePlayer()
     {
         transform.RotateAround(Vector3.zero, Vector3.forward, movement * Time.fixedDeltaTime * moveSpeed);
     }

```

This is what I want.

# Answer
> 1 votes
Waited more than I expected. I found a simple solution for this.

```
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = new Vector2(mousePos.x - transform.position.x, mousePos.y - transform.position.y
                );
transform.up = direction;

```

---
Tags: unity, 2d, rotation, touch
---


# Question
Title: Why do I get syntax error: identifier FHttpRequestPtr
I'm trying to add HTTP requests to my game and everything compiles fine until I try to set up a delegate for when the response is ready. Adding this function causes the compiler to fail for syntax error identifier FHttpRequestPtr.

header

```
void OnSaveTokenResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);

```

cpp

```
void UGamejoltApi::OnSaveTokenResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{

}

```

I have both `#include "Http.h"` and `#include "Interfaces/IHttpRequest.h"`. I also have this in my build file `PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "HTTP" });`.

# Answer
> 1 votes
The solution was to move the `#import "Http.h"` to the header file. Then it compiles fine.

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


# Question
Title: Artifacts at seams between meshes in Unity in isometric camera only
I'm trying to piece together some very simple placeholder models that I intend to use as tiles in Unity and I'm seeing odd pixel artifacts along the seams of the tiles that only show up when using an isometric camera. You can see them in this image.

And the same geometry but just from a perspective camera shows no artifacts.

I verified that the two models are exactly aligned right along the seam by checking the actual vertex data. The artifacts are dependent on the camera itself and shift along the seam as the camera is panned and zoomed.

I've disabled shadows, set the texture filter mode to point, disabled mipmap generation

The geometry is quite simple and is imported from the OBJ file below.

```
# normals
vn -1 0 0
vn 1 0 0
vn 0 0 1
vn 0 0 -1
vn 0 -1 0
vn 0 1 0

# texcoords
vt 0.970703 0.5
vt 0.974609 0.5

# verts
v 0 2 0
v 0 2 -4
v 0 2.3 0
v 0 2.3 -4
v 0 2.5 0
v 0 2.5 -4
v 4 2 0
v 4 2 -4
v 4 2.3 0
v 4 2.3 -4
v 4 2.5 0
v 4 2.5 -4

# faces
f 3/2/1 2/2/1 1/2/1
f 4/2/1 2/2/1 3/2/1
f 5/1/1 4/1/1 3/1/1
f 6/1/1 4/1/1 5/1/1
f 7/2/2 8/2/2 9/2/2
f 9/2/2 8/2/2 10/2/2
f 9/1/2 10/1/2 11/1/2
f 11/1/2 10/1/2 12/1/2
f 7/2/3 3/2/3 1/2/3
f 9/1/3 5/1/3 3/1/3
f 9/2/3 3/2/3 7/2/3
f 11/1/3 5/1/3 9/1/3
f 2/2/4 4/2/4 8/2/4
f 4/1/4 6/1/4 10/1/4
f 8/2/4 4/2/4 10/2/4
f 10/1/4 6/1/4 12/1/4
f 2/2/5 7/2/5 1/2/5
f 8/2/5 7/2/5 2/2/5
f 5/1/6 11/1/6 6/1/6
f 6/1/6 11/1/6 12/1/6

```

With the following texture applied as Albedo on a default Unity material (a bit odd since it was originally generated in MagicaVoxel)

I'm really at a loss for what could be causing these to show up. Only spotted them because I was testing an outline shader and it was outlining all the artifacts as the normals on those pixels were odd. With a pixel shader set to display \_CameraNormalsTexture instead of the color the artifacts are still visible as variances in the normals as you can see in the image below.

# Answer
> 1 votes
This appears to be due to some Z fighting between the edge of the horizontal quad and the edge of the vertical quad of the tile. Removing the vertical quads (and adding them back as individual pieces on just the edges of the terrain) resolved the issue.

---
Tags: unity, isometric, mesh
---


title: Why is the pawn not moving?

text:
# Question
Title: Why is the pawn not moving?
I have a set of moving chess pieces and am now trying to implement the rules to prevent them from going anywhere. The pawns use this code to move: (Sorry for the blurriness, the IDE did it automatically when I zoomed out so I could get it all.)

When I go to move the Pawn, it won't move at all. Weirdly, when I had the `if` statement at the top set to `true`, it would work just fine, just excluding the moving double on the first move.

What is causing this problem, and how can I fix it?

# Answer
The reason the pieces are not moving is that it never does the first section of code, and when it runs the second section, the only place it lets it move is the spot it is already in.

It never runs the first section because when you click on the pawn the first time it changes the value of the variable before it even moves. In the second section, the `mouse_y >= y && mouse_y <= (y + 64)` is the 64 by 64 grid the pawn is in as its location is determined by the top left corner.

To fix this, you would make it so that it does not change until after it has moved instead of when the player clicks on it, and change the `y + 64` to `y + 128`.
> 0 votes

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


# Question
Title: Add oceans to an earth model with only continents?
I have the following earth model, it only has continents:

I wanted to add water but as you can see, some of the continents are now hidden due to the water sphere being more round than continents:

I tried the following:

* downscale water sphere, kinda works but only when it's significantly smaller, overall result is then unconvincing.
* change shader and render queue offset, does not do anything actually.

I was hoping that maybe there could be a way to render transparent parts of this earth model as a specific color or eventually another material.

Please do not suggest to use another earth model, I wouldn't have asked the question otherwise :)

# Answer
I have been able to achieve it with very little changes:

* background water sphere uses material with standard shader and `Transparent` rendering mode
* continents-only sphere material render queue is set to Overlay

**Update:**

I just phong tessellated the whole thing and added this to fix the normals:

```
#pragma vertex:vert ...
#pragma target 4.6

void vert(inout appdata_full v)
{
    float3 normal = normalize(v.vertex.xyz);
    v.vertex.xyz = 0.5 * normal;
    v.normal = normal;
}

```

And by making making water sphere infinitesimally smaller and using a standard material configuration, all rendering problems are gone and it looks better :)
> 2 votes

# Answer
You can upscale the earth model, subdivide the larger triangles that end up underwater and make sure the new vertices are all the same distance from the center as the existing vertices.

There are 2 ways to add a vertex, in the middle of a triangle where you replace that triangle with 3 new triangles each bordering one of the edges of the old triangle and with the new vertex.

The other is in the middle of an edge between triangles, those 2 triangles then get replaced by 4 triangles each bordering one of the edges of the old triangles that isn't the one you are splitting and again with the new point as the third.
> 2 votes

---
Tags: unity, shaders, models, transparency
---


# Question
Title: GLSL: sampler2D fallback to constant color?
So I have the following situation: I'm sharing a blinn shader accross many meshes. Some meshes have specular & normal maps, others do not.

I'd like to, without making the shader code too complicated, be able to specify a constant color instead of a texture, for the normal or specular maps. This is for example if a given mesh doesn't need one of those maps.

The way I imagine it, I would just pass a flat "grey" as the specular map, for instance, and the shader could just act as if a texture was passed in. Is this possible?

Ideally, I don't want to have an extra uniform for each mesh specifying whether or not the texture should be used.

Another alternative would be to actually create a grey texture on the fly, if this is the better way, please advise on the simplest way to do this.

# Answer
> 4 votes
I've had the same problem several times and haven't found a way to specify a default color that would be used when a texture is not used.

I've ended up creating 1x1 pixel fully white, black and transparent textures that are globally available. This does the job pretty well and is easy to use, although I don't like the unnecessary texture accesses in the shader.

# Answer
> 1 votes
Here is where it comes the shader/material distinction.

The shader is a GPU program that produces some lighting/shading effect. In your case you need to build a material system (albeit a simple one) where multiple materials can use the same shader, but pass different values for each material, that's one reason we have uniforms.

Another point is, if some material doesn't need a specific property of a shader (e.g. especially normal map) then it shouldn't have it. Just create an appropriate shader for it (or use uber shaders), you also want to do this for performance reasons.

If you want a diffuse shader to be to have a solid color, just create a "non-texture" or blank-texture and pass it by default, probably white and it doesn't need to be big 1x1px is fine (though I didn't try it), and pass the diffuse color, this way you can modulate while still having only the diffuse color.

# Answer
> 0 votes
I have implemented a simple solution that seems to be working for myself. I solved it by ensuring that my shader takes in both colour and texture coordinate data. The other requirement is that you set the colour of all textured vertices to black. My fragment shader is then set up as follows:

```
    #version 330 core
    out vec4 gl_FragColor;

    in vec2 TexCoords;
    in vec4 vsColour;

    uniform sampler2D texture_diffuse1;

    void main()
    {
        gl_FragColor = vsColour;
        gl_FragColor += texture(texture_diffuse1, TexCoords);
    }

```

If there is texture data it will overwrite the black value.

---
Tags: opengl, glsl
---


# Question
Title: How can I come up with a simple diminishing return equation?
There are formulas out there for a diminishing return equation; however, those usually involve exponential. What other ways are there for coming up with such an equation? Take, for example, the following test case -- One farm produces 10 food, for every 10 farms produced, the production rate drops by 5%.

# Answer
> 33 votes
For formulating a diminishing returns equation, I'd immediately think fractions.

This is a graph of \\$y=\frac{1}{F}\\$

\\$y\\$ will get smaller as \\$F\\$ gets larger. This will give you a steady drop-off that never reaches 0. From this you can transform it to get the sort of curve that you want. Using numbers \> 0 will **always** give positive output that is **never** 0.

Honestly, I'd recommend going to WolframAlpha and putting in some equations and looking at the graphs that it draws to see if it gives the curve that you want. Other than that, read up of linear and quadratic equations to be able to quickly figure out what it is that you want to alter in a formula. This is because modelling graphs through equations is a bit of a big topic, and if I could explain it here perfectly I'd sell that explanation to some maths teachers first.

Basically, for linear graphs, remember \\$y=mx+c\\$. \\$m\\$ is the gradient, and can be positive or negative depending on what you need, and \\$c\\$ is the point at which it intercepts the y axis. \\$x\\$ is your input variable and \\$y\\$ is your output.

This is a graph of \\$y=mx+c\\$ where \\$m=1\\$ and \\$c=0\\$

For quadratic graphs, it gets a bit more complicated, so I'll be a bit vague and you'll have to read up on the specifics yourself. Khan Academy is a really good resource for teaching this. It's of the general form \\$y=ax^2+bx+c\\$. \\$c\\$ is still the y intercept, and you can tweak it to "lift" the graph. \\$a\\$ and \\$b\\$ both affect the curve similarly, but to different degrees.

This is \\$y=-x^2+2x+10\\$. Note the \\$-x^2\\$, which makes the curve inverted.

Basically, play around with the graphs until you get what you want, although I highly recommend reading up on it more if you want to design the experience quickly and cleanly. Basic equations are important to games and really interesting.

Other things to note are exponential and logarithmic graphs, i.e. graphs of \\$y=e^x\\$ and \\$y=ln(x)\\$ to get rapidly increasing and rapidly decreasing graphs depending on the transformation. As well as this, vectors and transformations are helpful, as they describe what you're doing the the "base" graph.

# Answer
> 25 votes
**Diminishing returns = decreasing derivative**

* Since you still want some returns even at higher levels means that the derivative should be positive, otherwise building more farms would decrease the food production (which might even make sense if you take into account logistics and upkeep costs)
* It should approach zero assymptotically, if it goes towards a non-zero value you will end up with constant increase per farm at some level
* depending on how fast it goes to zero you can have an upper limit or an unbounded function

So what do you need to do? Pick a function that fits the above criteria and integrate it.
The simplest choice for this task is `g(t,n) = 1/(t+1)^n` where `n=1` marks the boundary between ever increasing and bounded functions.
The integral of g from 0 to x is what you need: `f(x,n) = ((x+1)**(1-n) - 1)/(1-n)`
Here is how it looks for different `n`

And here its normalized to the same final value

By changing the exponent `n` you can easily adjust the balancing
*Note: The derivative here is the production per farm, while the integral is the total production for a number of farms*

# Answer
> 5 votes
In general, a linear equation will start with `y = mx + b`, where `b` is your starting value, and `mx` is how you adjust the starting value as `x` increases.

So the first part of your equation, the `b`, will be `10` because you want farms to start at 10 food.

```
y = mx + 10

```

Next, in your case, you want to adjust the food by produced by every ten farms. So you will need to divide by ten to get an equation that works for every ten farms (assuming that the `x / 10` returns an integer, ie `13 / 10 = 1`:

```
y = m * (x / 10) + 10.

```

So finally, we need to figure out how we want the food to change for every `x / 10` farms. In your case you want it to decrease by 0.5 (5% of 10), which is linear. So we get:

```
y = -0.5 * ( x / 10 ) + 10.

```

So for farm `x = 5`, we get `5 / 10 = 0, 0 * -0.5 = 0, 0 + 10 = 10`. For farm `x = 11` we get `11 / 10 = 1, 1 * -0.5 = -0.5, -0.5 + 10 = 9.5`, for farm 23, we would get 9.0.

Then you just need to compute the total food for all farms.

```
y = 0
for( x = 0; x < totalFarms; x++ )
{
    y += -5 * ( x / 10 ) + 10;
}

```

But maybe you by 5%, you wanted it to decrease by 5% of the previous value. Ie, `10, 10 * 0.95 = 9.5, 9.5 * 0.95 = 9.025` (in this case, the amount we decrease by gets less and less). So lets modify the equation. `5%`is an exponential type increase, and the exponential formula is `y = b*m^x`.

We still have `b = 10`, and we need to do our divide by 10 trick. So we have `y = 10*m^(x/10)`. `m` is `0.95`, since we want to take 95% of the value each time. So the equation for farm `x` is `y = 10*0.95^(x/10)`.

# Answer
> 4 votes
Would a linear diminishing return do? \\$production\ per\ farm = (1 - (0.05 \frac{ f}{10}) ) * production\ rate\\$.

This gives a total production (rate * # of farms) peak at f = 100.

# Answer
> 3 votes
You might want to consider an algorithmic solution that matches the situation.

That is, consider *why* there are diminishing returns in your game situation, and model those.

Multiple facilities of the same type might have diminishing returns in that there might be other resources or facilities which they depend on, or which result in bottlenecks, or other limiting situations, such as a road network, or available workers or transportation or fresh water or electricity or whatever.

One farm can produce 10 food per day in ideal circumstances, but it requires two farmer-hours per day as well. It also requires one fresh water per food per day, and its own well only provides up to 5 water per day. The rest must be taken from an adjacent stream or river or brought in by transportation. And getting the food to where it needs to be to be useful may also be an issue. Etc. Remove some or add more depending on what you want to represent, but these can be much more interesting and meaningful reasons, which add interest and value to your other game systems, as opposed to an artificial mathematical formula not based on other game elements.

# Answer
> 1 votes
If you want a generalized equation to mess around with, you could use a cosine graph: A\*cos(Bx+C)+D

But modify it to half a period, so it would include the pseudo exponential rise at the beginning, then a short period of linear increases, to a finally diminishing point of returns. The only problem with this is that it would require to to create a impassable ceiling. So after a certain amount of farms you would see no increase.

The Image below is a graph of increases in pace for 30 min runs, doing the exact same workout in preparation. It's obviously not perfect, but you might be able to work off this to find what you're looking for.

# Answer
> 0 votes
Here is standard capacitor charge voltage equation which looks like diminish return: $$\large{v(t)=V\_0 * (1 - e^{\frac{-t}{t\_0}})}$$

---
Tags: game-design, mathematics
---


# Question
Title: 2D line of sight - hiding all tiles behind walls
I'm interested in knowing the techniques on how 2D games hide tiles that are behind walls.

This is a really old MMO that is probably the easiest example to show what I'm asking.

Here you can see all the tiles apart from inside the two buildings

But enter the building and let the door close, and you can see only what's inside.

Stand beside or IN the doorway, and you can see inside and out.

What techniques should I look into to achieve an effect like this?

---

EDIT: A video of a similar game that shows the effect also, skip through parts and you'll get the idea: https://www.youtube.com/watch?v=ujwQ0-gNQ64

# Answer
The simplest implementation is for your `Tile` class to have two members: `visible` and `opaque`. Optionally, but a very useful third member is `solid`.

* `visible`: Is the tile currently visible by line of sight to the player?
* `opaque`: Does this tile block visibility of the tiles behind it?
* `solid`: Does this tile block movement?

If a tile is not visible it should not be drawn. A tile can block movement even if it isn't visible.

Doors flip their `opaque` and `solid` members as their state changes.

* Open: `opaque = false; solid = false;`.
* Closed: `opaque = true; solid = true;`.

By running your line of sight algorithm in every direction you can easily determine what tiles the player can see and therefore which tiles should be drawn.

If you want a floodfill look-and-feel you can use light propagation techniques a la Minecraft to tell if an area is enclosed or outdoors or needs to be visible and if the player is currently within such an area. If they are, only draw the tiles visible to the player.
> 1 votes

---
Tags: 2d, line-of-sight
---


title: Making object move in an angle

text:
# Question
Title: Making object move in an angle
I have a game with a beat-em-up perspective (think Final Fight, Streets of Rage) where movement is in X and Z. My movement logic consists of checking controller input of X-axis for X movement and Y-axis for Z movement. I use this logic to move enemy as well, using this method:

```
internal bool MoveTowardsPosition(Vector3 targetPosition)
{
    bool reachedPosition = false;
    bool reachedX = false;
    bool reachedZ = false;

    // Determine x direction
    if (Mathf.Round(Mathf.Abs(targetPosition.x - _enemy.transform.position.x)) > 0)
    {
        if (targetPosition.x < _enemy.transform.position.x)
            Input.HorizontalMove = -1;
        else
            Input.HorizontalMove = 1;
    }
    else
        reachedX = true;

    // Determine z direction
    if (Mathf.Round(Mathf.Abs(targetPosition.z - _enemy.transform.position.z)) > 0)
    {
        if (targetPosition.z < _enemy.transform.position.z)
            Input.DepthMove = -1;
        else
            Input.DepthMove = 1;
    }
    else
        reachedZ = true;

    if (reachedX && reachedZ)
        reachedPosition = true;

    return reachedPosition;
}

```

So what happens here is that given a target position, I add to the HorizontalMove (X) and DepthMove (Z) until the enemy reaches the destination (these X and Z additions will be read on Update to do a transform.translate()). The enemy does move to the destination but in a unnatural path. So when Z is larger, it will reach the destination X first then traverse Z. So for example, X=2 and Z=5, it'll traverse with a path like this:

What I'm trying to do is for it to traverse a path like this:

I figured instead of adding fixed 1/-1, I need to determine X and Z based on that angle but I'm lost on how to compute/do it. Can you guys lend me a hand, please?

# Answer
I think you'll want to pass a normalized vector into the movement function. Something that will combine the x and z movements into a single variable. Likely you'll need to use the Pythagorean theorem as well. This video may have what you are looking for:

https://youtu.be/m7VY1T6f8Ak
> 1 votes

---
Tags: unity, movement
---


# Question
Title: How to prevent unwanted scaling of textures in world space
I allow players to select buildings of different sizes in my game, in the image below is a building that is 30x30 units and one that is 10x10 units.

To indicate that the building is selected, I added a child called `Selection indicator`, this child is simply a texture dragged into the scene, which creates a plane. I activate/deactivate this on select/deselect.

So far so good, but as you can see in the image, in order to match the different sizes, I need to scale the `Selection indicator`, which distorts its edges. Simply using sprite editor here does not seem to change anything since it's in world space.

How could I approach this in a way that the frame for my `Selection indicator` does not stretch like in the image?

# Answer
> 2 votes
Instead of a plane, use the SpriteRenderer component. The reason is that the sprite renderer allows you to use 9-sliced images, like you might know them from the UI system.

First, go to the sprite renderer and set "Draw Mode: Sliced".

Then go to the import settings of the texture you use to represent the select indicator, set "Texture Mode: Sprite (2D and UI)", "Sprite Type: Single" and "Mesh Type: Full Rect". Then click on "Sprite Editor" and and enter the width in pixels for the left, right, top and bottom border like this:

If you want to change the size of the indicator game object, do **not** use `transform.scale`, because that will also enlarge the edges and corners. Use the SpriteRenderer.size property instead. It will resize the center without changing the width of the border.

---
Tags: unity
---


# Question
Title: Is it possible to move buttons or other ui elements over each other dynamically in Godot?
What im trying to do is have it set up so that if the player clicks on a character their ability's will appear on the ui, but i want to use the same ui space for the other characters as well.

So is it possible to have multiple buttons in the same area and then depending on which character is selected only the buttons connected to that character appear?

Thank you in advance for the help.

# Answer
To answer your question as written, yes, you can have multiple `Control` nodes sharing the same space, and only set one to be visible at a time.

Note that `BobStats` and `JaneStats` are sharing the same `PanelContainer`, but only `BobStats` is visible. I've wired up the following signal connections:

```
Button1.pressed -> BobStats.show()
Button1.pressed -> JaneStats.hide()
Button2.pressed -> BobStats.hide()
Button2.pressed -> JaneStats.show()

```

There's a node called a TabContainer that is specifically designed for showing one control at a time:

However, based on how you've described your question, I'm thinking you don't actually want multiple controls sharing the same space, but rather a single set of controls whose values you modify when a particular character is selected.
> 2 votes

---
Tags: godot
---


# Question
Title: How to display a list of 2D arrays in the inspector
Simply put, how do I make `public List<bool[,]>` appear in the inspector? Every 'bool\[,\]' is a solution to a puzzle in my game and I want to be able to view and edit them in the inspector.

# Answer
> 3 votes
You will need to create a custom property drawer.

You will also need to create a custom serializable class for your solution dataset. I may be wrong, but I don't think you will be able to assign a property drawer to a generic list type like you have.

https://unity3d.com/learn/tutorials/modules/intermediate/live-training-archive/property-drawers-custom-inspectors

http://catlikecoding.com/unity/tutorials/editor/custom-data/

The nice thing about the property drawers is that you can display the data how you want, it doesn't have to be in the typical list format that unity usually displays. You could make it a grid if you wanted.

# Answer
> 2 votes
```
using UnityEngine;

public class Script : MonoBehaviour
{
    public static int X, Y;
    [System.Serializable]
    public class Column
    {
        public bool[] rows = new bool[Y];
    }

    public Column[] columns = new Column[X];

}

```

---

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Script))]
public class CustomScriptInscpector : Editor {

    Script targetScript;

    void OnEnable(){
        targetScript = target as Script;
    }

    public override void OnInspectorGUI()
    {

        Script.X = EditorGUILayout.IntField(Script.X);
        Script.Y = EditorGUILayout.IntField(Script.Y);

        EditorGUILayout.BeginHorizontal ();
        for (int y = 0; y < Script.Y; y++) {
            EditorGUILayout.BeginVertical ();
            for (int x = 0; x < Script.X; x++)
            {

                targetScript.columns [x].rows[y] = EditorGUILayout.Toggle (targetScript.columns [x].rows[y]);
            }
            EditorGUILayout.EndVertical ();

        }
        EditorGUILayout.EndHorizontal ();

    }
}

```

# Useful link:

https://unitylist.com/p/fw5/2D-Array-Editor

# Answer
> 1 votes
Unity doesn't display 2D array in the inspector. For this we need to add our own Editor script to make it appear in the inspector and make it editable .

Fortunately there is already a tutorial available on how to achieve this functionality .

Link:- https://www.youtube.com/watch?v=uoHc-Lz9Lsc&feature=youtu.be

Download Link for the code :-

https://www.dropbox.com/s/8em24v1j749yl62/2DArray-In-Inspector-Scripts.zip?dl=0

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


# Question
Title: Can't find sibling node, keeps giving "null instance"
I'm trying to set it up so that there are three buttons but only one can be toggled at a time. So when one button gets toggled it makes sure that the other two are not toggled.

The code is trying to set the toggled status however since it can't find the node I'm at a loss.

```
var vec = Vector2(0,1000)
var ori = Vector2(0,0)
func _ready():
    pass

func _on_Ally1_Button_toggled(button_pressed):
    if button_pressed:
        set_position(ori)
        $Player_Button.set_pressed(false)
    else:
        set_position(vec)

```

This is what the tree looks like.

The `Player_Ally1_ui` is trying to access `Player_Button` but as stated it can't seem to find it and just returns null.

Any help is greatly appreciated, thank you in advance.

# Answer
`$Player_Button` refers to the *child* of the current `Node` called `Player_Button`, not the sibling. You actually want `get_node(../Player_Button)` (as the `$` syntax doesn't support `..`).

A better option might be connecting these nodes via signals in the Editor. One of the advantages of this is that you can move the nodes around in the tree and the Editor will handle updating the singal connections for you. If you use hard-coded node paths, you'll have to update your code every time you move nodes around (which I find happens frequently in `Control` nodes).
> 1 votes

---
Tags: godot
---


# Question
Title: Game Either Runs Poorly or at Different Speeds
I'm making a simple 2D shooter game using C++ and SDL2. For my main game loop, I used the code from the famous Fix Your Timestep article. The problem is that, because I'm using a fixed delta time, the game's objects move at different speeds depending on the hardware of the computer it is being played on. On more powerful PCs, the game runs very fast, and on weaker PCs, it runs slowly.

I was able to get around this problem by removing the `if (frameTime > .25) { frameTime = .25; }` statement, however this caused, paradoxically, the game to run poorly on computers with more powerful CPUs. I'm not limiting the FPS, and so when I run the game on a powerful PC, it starts off running at around 1500 FPS, but then the FPS quickly drops to unplayable levels, all while using up a significant percentage of the CPU power. On weaker PCs, however, the game runs just fine.

My question is, how do I balance these two issues so that the game runs at an acceptable framerate, while also making sure that the game objects move at the same speed, regardless of the hardware it is being played on? The game runs at a low resolution and uses very simple graphics, so it should be able to run smoothly even on weak PCs.

# Answer
> 0 votes
You should limit the speed from above as well. This most likely this is the reason why it behaves so strangely on a fast PC, it's simply too fast. Try to implement such a limitation. Let's start with delay ~30ms per one frame and see. Then I recommend to experiments with this value.

Perhaps later one you'd like to add some physics and so on. With unlimited FPS the physics may become unstable. Keep that in mind.

---
Tags: c++, physics, sdl2
---


# Question
Title: Accessing the Properties of an object already in Scene in Unreal Engine using C++
I am trying to learn more about raycasting in C++ and am trying to implement raycasts in a mini third-person game I am creating. In order to shoot a raycast, I first need to determine its starting location, which in this case I intend it to be from the center of the third-person camera already built-in.

In order to do that, however, I need to access the properties of the camera already in the scene and store its location in a variable using c++. I am relatively new to unreal so I have no idea how to access an object's properties that's already in the scene using C++.

Any help is appreciated

I am still searching, but I couldn't find a satisfying answer yet.

# Answer
> 0 votes
Getting the camera itself is fairly easy:

```
APlayerCameraManager *camManager = GetWorld()->GetFirstPlayerController()->PlayerCameraManager;

FVector camLocation = camManager->GetCameraLocation();
FVector camForward  = camManager->GetCameraRotation().Vector();

```

however getting the center of the view is better done via the HUD api and it's project/deproject functions. It can also be accessed from the player controller with following API:

Documentation

```
//Prototype
bool DeprojectScreenPositionToWorld
(
    float ScreenX,
    float ScreenY,
    FVector & WorldLocation,
    FVector & WorldDirection
) const

```

To get all objects of specific class that are already in scene you could use `TActorIterator`for example like follows:

```
//This will iterate over every static mesh that is placed in the world(scene).
for (TActorIterator<AStaticMeshActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
    // Same as with the Object Iterator, access the subclass instance with the * or -> operators.
    AStaticMeshActor *Mesh = *ActorItr;
    ClientMessage(ActorItr->GetName());
    ClientMessage(ActorItr->GetActorLocation().ToString());
}

```

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


# Question
Title: How can I insert a prefab instance programmatically inside the Canvas, in the bottom-left corner of the Canvas?
I am trying to create the Snake game in Unity, based on this video tutorial. I have also viewed this tutorial.

I have created the new project with the 3D template and manually added the Canvas. I created a prefab from an Image which loads a texture from the Assets. I have this code:

```
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
    public GameObject whiteCellPrefab;
    int N = 30, M = 20, size = 16;

    // Start is called before the first frame update
    void Start()
    {
        Transform p = GameObject.Find("Canvas").transform;
        for (int i = 1; i <= N; ++i)
        {
            for (int j = 1; j <= M; ++j)
            {
                GameObject g = Instantiate(whiteCellPrefab, p);
                g.transform.localPosition = new Vector3(i * size, j * size);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
}

```

If I manually add a prefab instance to the Canvas, it is positioned as I want: in the bottom-left corner. But the script above, attached to the Main Camera object, creates the Image objects starting from the center point of the Canvas towards the top-right corner of the Canvas.

In the example shown here, I also added a new prefab instance to the Canvas in the Unity editor. It is positioned correctly even when play testing but the ones added with the script are shown somewhere else.

## Screenshots

## Download my example

I tried to explain all the steps involved in my problem above, but here is the repo with my problem.

Thank you.

# Answer
Since you are already parenting the prefabs when you set localPosition that is relative to the center point of the canvas.

Change your Start method like this:

```
void Start()
{
    Transform p = GameObject.Find("Canvas").transform;

    for (int i = 1; i <= N; ++i)
    {
        for (int j = 1; j <= M; ++j)
        {
            GameObject g = Instantiate(whiteCellPrefab, p);
            g.transform.position = new Vector3(i * size, j * size);//set the position NOT the localPosition
        }
    }
}

```

You need to set he position and NOT the localPosition like this:

```
g.transform.position = new Vector3(i * size, j * size);

```

To clarify things further please add this script to your white\_cell prefab. It will allow you to see the difference between localPosition and position of each prefab during runtime and designtime.

```
using UnityEngine;

public class WhiteCellPrefab : MonoBehaviour
{
    public Vector3 LocalPositionDebug;
    // Start is called before the first frame update
    void Start()
    {
        LocalPositionDebug = transform.localPosition;
    }
    private void OnDrawGizmos()
    {
        LocalPositionDebug = transform.localPosition;
    }
}

```
> 1 votes

---
Tags: unity, c#, gameobject, prefabs
---


title: Unreal Engine and Simple Animation

text:
# Question
Title: Unreal Engine and Simple Animation
I am creating a card based game and I am stuck on an animation detail. My question is I need an animation to shuffle the deck, a animation for dealing and an animation for drawing. My question is should I create the animations in Unreal Engine or would I create them in blender. I know traditionally with characters and other animations you would create them within blender. However I am unsure in this instance as we are talking about simply shuffling, dealing, and drawing cards.

# Answer
I guess that should not make much of a difference you obviously can import animations from blender so that wont be a problem.
> 0 votes

# Answer
If you are already familiar with unreal, animation/modeling and simple, I think you could use it.

Especially if you are going to do a simple animation (just moving the cards with simple moves).

Now if you want something more refined, with the cards rotating on some axis, I think it would be easier for the blender. Because I believe that if you need help you will find it easier, both here in the forum and on youtube.
> 0 votes

---
Tags: animation, unreal-4, blueprints
---


# Question
Title: Unity LWRP Sprite Renderer Sorting incorrectly after upgrading
I'm making a project where every tile is a sprite renderer, this would work fine in the old unity system (from the fact that it used it until recently), but upgrading to the LWRP broke the sorting of the sprite renderers. Previously, I didn't have to change the order at all, but now they phase in and out of each other based on the position of the camera, like the picture shown below. They all use LWRP/2d/Sprite-Lit-Default, as any other of the LWRP materials do not use the texture from the sprite renderer and instead make it all black.

I do not want to use sorting layers because I have meshes sprinkled in, and what i have seen there is no way to control if the mesh is on anything but order 0, besides some hacky way. Even using a box mesh it gets cut off when the floor is closer to the camera.

Here is what it looks like far away, the floor should be there the entire time and not have the darkness of the walls seeping down into them.

I don't think I can use mesh renderers either, as I want a way to control the texture from each individual object, and share a material through all of them. I think if I used a mesh renderer I would have to use a material for each different tile, and I would not be able to tile them like I am doing now.

# Answer
I solved this problem by not using the LWRP Lit sprite shader. I created my own in Shader Graph that samples \_MainTex and that fixes the sorting problem. The main cause was that the LWRP sprite shader made them automatically two-sided, while the old system they were one sided and that was causing my problem.
> 1 votes

---
Tags: unity, sprites
---


title: (C#) Need help with Shuffling a list

text:
# Question
Title: (C#) Need help with Shuffling a list
I'm making a deck building game in Unity and need a way to shuffle a deck of cards in a list.

I've tried to use a version of the Fisher Yates Shuffle, but It's not working. I'm not given any errors, the game just doesn't do anything when I try to use the function.

This is the code I'm working with.

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

public class Deck : MonoBehaviour
{
    public List<Card> AbilityDeck;

    public void ShuffleDeck()
    {
        Shuffle(AbilityDeck);
    }

    public void Shuffle<T>(IList<T> list)
    {
        System.Random random = new System.Random();
        int n = list.Count;
        while (n < 1)
        {
            int k = random.Next(n);
            n--;
            T temp = list[k];
            list[k] = list[n];
            list[n] = temp;
        }
    }
}

```

# Answer
> 4 votes
Your loop condition is `while (n < 1)`.

Since `n` is integer and initialized to `IList<T>.Count`, which – on a good implementation – can't be negative. It means that the only value of `n` that satisfies the condition `(n < 1)` is `0`.

That means that it will only enter the loop when the list is empty (`n = 0`). And in that case there is nothing to shuffle, isn't it?

Thus, the code does nothing.

---

I searched for a similar implementation of Fisher-Yates shuffle and found this one:

```
int n = list.Count;
while (n > 1) {
    n--;
    int k = rng.Next(n + 1);
    T value = list[k];
    list[k] = list[n];
    list[n] = value;
}

```

Source: Randomize a List

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


# Question
Title: How can I fix a GameObject along one axis only when it is part of another object in Unity?
Hello I have an Object player and inside player, I have an object Boundary which is supposed to follow the player as he moves up or down only? (As the player moves right or left I don't want the boundary object to move. How can I do it?

# Answer
Does it have to be a child object? If not; Create another object. Get a transform reference to it. Update its transform each frame like so;

```
object.position = new Vector2(transform.position.x, object.position.y);

```
> 1 votes

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


# Question
Title: What is the proper way of handling resolution and size units on a 2D game?
So I started to learn SDL2 and I want to make a simple 2D game.

Now when I render a texture I have to specify in pixels the size of the element I want to draw and also the position in pixels on the window.

It doesn't feels like a good practice to hardcode pixel values because if I want to change the resolution of the window or the aspect ratio it will look really bad.

There is any recommended approach to follow?

# Answer
> 2 votes
Generally it's up to you. Think about it in a abstract way. Read some articles and extract the ideas. Give it some time and gather the experiences.

Imagine that games have something like GameObjects(player, enemy, bonus, wall, trap, weapon, etc.) Each such a object have some properties and methods like position, rotation, moveTo, scaleUp, etc.

Those properties and methods should use coordinates which are called the "game" coordinates and they should be somehow mapped to the screen when rendered.

So what do you need?

**Basically you need two coordinate systems and some functions that allow you to do the conversion between those two coordinate systems.**

For example:

`void gameCoordinates2ScreenCoordinates(const game_coord& from, screen_coord) {...}` \- called when object is sent to renderer

and vice versa

`void screenCoordinated2GameCoordinates(const screen_coord& from, game_coord& to) {...}` \- e.x. called when mouse click happen

If your game is very simple app you can even start with mapping 1:1 and later on you can always refactor it according to your current needs.

Perhaps later on you want to map your x-axis of the screen to float between 0.0f(left edge of screen) to 1.0f(right edge of the screen) or -1.f to 1.0f or .0f to 10.f or whatever suits your needs.

Keep in mind following hints regarding the conversion functions:

* they should be generic
* they are called often so
* do only the necessary math
* avoid memory allocation

# Answer
> -1 votes
Old graphics have to be in powers of two. New graphics have a split. If the file is in the DirectDraw Surface format, then images need to be in multiples of four, otherwise images needs to be in multiples of eight. Therefore, for portability, images needs to be multiples of eight.

Note that it is the sprite sheet that needs to have multiples of eight in dimension. The individual sprites do not have to be so if they are packed, but requiring correct offsets, width, and height. Of course, evenly spaced sprites are easier to load, but uses more memory with padding.

The ideal tile sizing is based on the square root of vertical resolution in landscape, or horizontal resolution in portrait mode. Round up the square root of selected resolution to the nearest multiples of eight. This is the minimum resolution that a tile should be. Tiles may be larger especially for handheld devices. However, no tiles shall be smaller than the suggested minimum resolution.

As an example, a chess board requires a minimum of 8x8 pixel tile (a square of the board) would need a resultion of 64 pixel tall screen. If the chess board requires a minimum of 16x16 pixel tile, then it would need 128 to 256 pixel tall screen. If the chess board requires a minimum of 24x24 pixel tile, then it would need 192 to 576 pixel tall screen. If the chess board requires a minimum of 32x32 pixel tile, then it would need 256 to 1024 pixel tall screen. Every tile size has a minimum and maximum range of screen resolution they could support, but the maximum resolution could be ignored if you scale up the tiles with resolution instead of pixel perfect.

The ideal sprite size should be integer multiples of the tile size. For a three-quarter viewport that most games have or isometric viewport, the ideal size is two tiles tall and one tile wide for medium sized characters. All top-down viewport have medium size sprites equal tiles in size. For side-scrollers, medium size characters should be four to six tiles tall and one tile wide for more realistic looks. Of course, if you like the chibi style, keep the two tiles tall and one tile wide.

Heads tall ratio

* chibi - two heads tall
* infantile - three heads tall
* toddler - four heads tall
* children - five heads tall
* young adult - six heads tall
* adult - seven heads tall
* hero - eight heads tall
* superhero - nine heads tall
* fashion - ten heads tall

Use `SDL_GetWindowSize()` (some cannot see without syntax highlight) and adjust the tile size accordingly. It is better not using pixel perfect if you want scalable to higher resolution, 4K and up. Remember that there is a maximum resolution in pixel perfect based upon my suggestions of ideal tile size.

Remember that for most humans, we could only see upto 2M resolution. 1K (SD), 2K (HD), 4K (UHD), 8K, 16K, 32K, 64K, 128K, 256K, 512K, 1M, 2M, and a single screen only covers about 1/4 of our horizontal span, so 512K is the maximum resolution that we need to deal with.

* 1K (SD) - 24x24
* 2K (HD) - 40x40
* 4K - 48x48
* 8K - 72x72
* 16K - 96x96
* 32K - 136x136
* 64K - 192x192
* 128K - 264x264
* 256K - 376x376
* 512K - 528x528
* 1M - 744x744
* 2M - 1056x1056 pixel perfect realistic graphics

Visibility is an issue. When screen resolution goes up, the pixel density tends to also go up, so the minimum resolution needs to increase.

When talking about non-pixel perfect, it means to be pixel perfect to the game resolution, but the game resolution is scaled up to the screen resolution. Not all games need to have an extra step in scaling up. Games could be made directly to access the screen resolution.

Of course, with a game resolution, then the resolution is fixed to a certain perspective, and it would scale to most devices. It is common for developers to use 640x360 resolution as a base because it scales to 1280x720 and 1920x1080 in integer increments, so it does not deal with anti-aliasing.

```

void scale2coordinates( SDL_Window * Window, int & MinimumTileSize )
{
    int x, y;
    SDL_GetWindowSize( Window, &x, &y );
    MinimumTileSize = int( sqrt( float( min( x, y ) ) ) ) + 7 & ~7;
}

void scaleSprite( SpriteStruct Sprite, int MinimumTileSize )
{
    SDL_Rect RenderSize = { Sprite.x * MinimumTileSize.y, Sprite, Sprite.WidthInTiles * MinimumTileSize, Sprite.HeightInTiles * MinimumTileSize };
    SDL_RenderCopy( Renderer, Sprite.Texture, & Sprite.Rect, & RenderSize );
}

```

You scale based on the rect's of the sprite and tile size. Look up Render to texture tutorials.

---

```
void GetScale( SDL_Window * Window, int & ScaleScreenResolution )
{
    int x, int y;
    SDL_GetWindowSize( Window, &x, &y );
    ScaleScreenResolution= min( x / MinRows, y / MinColumns );
}

void ScaleToScreen( TileStuff, int ScaleScreenResolution, int ScaleTileResolution )
{
    ScreenStuff = TileStuff * ScaleScreenResolution / ScaleTileResolution;
}

void ScaleToTiles( ScreenStuff, int ScaleScreenResolution, int ScaleTileResolution )
{
    TileStuff = ScreenStuff * ScaleTileResolution / ScaleScreenResolution;
}

```

Here, Stuff refers to what needs to be scaled to screen and scale to tiles. I assume that most 2D games are tiled based and not using giant bitmaps. I also assume that tiles are squares, but there are rectangular tiles engines as well, so there might need to be separate x and y scales. Also, I assume that not all games are fixed in 4:3 or 16:9 aspect ratio.

Usually the art scale from image to screen, and input is scaled from screen to tiles.

---
Tags: c++, 2d, sdl2, resolution
---


# Question
Title: Monogame - Load SpriteFont using .spritefont file without using the Pipeline Tool
There is a way to load a sprite-font **without using the Monogame Pipeline tool?**

I am creating a Game-Engine using Monogame, i cant use the Monogame Pipeline tool because the way that Game-Engine manage the Content Files is different, and it needs to read the source file, not the .xnb file that Monogame Pipeline tool create.

# Answer
As it turns out, there is a way to load a `SpriteFont` without the need of MGCB, and to make it better.

You'll need to use SpriteFontPlus. It generates `SpriteFont` objects dynamically from normal image files.
> 1 votes

# Answer
No, the SpriteFont content type starts as instructions to the content pipeline to convert a specific font at a specific size (in pt) into a set of textures for every UTF-8 character. Since a .SpriteFont doesn't contain any textures, it has to be compiled by the content pipeline to be imported in MonoGame as a SpriteFont.
> 0 votes

---
Tags: monogame
---


# Question
Title: How is actual object size in a scene calculated?
I've got stuck with 'pixel per unit' parameters and object scale.

I've created two different sprites. A background picture, 1000x1000 pixels, and another one for a 'player', 200x200 pixels. I've added two empty game objects, with default transform, so positions are (0; 0; 0) and scale is (1; 1; 1). I added a sprite renderer to both of them, and assigned the required sprites. Both sprites have 1 pixel per unit.

And the 'player' in the scene looks much more bigger than the background.

I expect that if ppu=1, then the background would have a size of 1000 units, a player 200 units and it would be 5 times smaller.

What am I doing or understanding wrong? What is an actual object size?

# Answer
The problem was caused by manual replacing of .png picture in project's folder. At first time I didn't found a valid way to import an image as sprite, so I created a default one in Unity, which creates a sprite and a picture 1x1 pixels. Then I replaced it with my own picture, but metadata didn't change, and the Unity still worked with sprite like it is still 1x1 pixel, not 1000x1000, 200x200 etc.

The valid way to import a picture as sprite is just to put it to *Assets* folder in the project, or drag and drop a file to *Assets* folder in Unity.
> 1 votes

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


# Question
Title: Syntax error in multi-pass Surface Shader
I'm trying to make a Surface Shader that uses multiple passes, with two different blending functions for each one, but I get the following error I don't understand:

> Parse error: syntax error, unexpected TOK\_PASS, expecting TOK\_SETTEXTURE or '}' at line 28

```
SubShader
{
    ZWrite Off
    Tags { "QUEUE"="Transparent" "IGNOREPROJECTOR"="true" "RenderType"="Transparent" "PreviewType"="Plane" }
    Pass
    {
        //transparency
        Blend SrcAlpha One
        CGPROGRAM
            #pragma surface surf Lambert
            #pragma target 3.0
            struct Input
            {
                //
            };
            sampler2D //;
            void surf (Input IN, inout SurfaceOutput o)
            {
                //
            }
        }
     ENDCG
    }
    Pass
    {
         //alphabend
        Blend SrcAlpha OneMinusSrcAlpha
        CGPROGRAM
        #pragma surface surf Lambert
        #pragma target 3.0

         sampler2D//;
         fixed4 //;

         struct Input
         {
          //;
         };
         void surf(Input IN, inout SurfaceOutput o)
         {
         //
         }
        ENDCG
    }
}

```

# Answer
> 2 votes
Surface shaders wrapped in `CGPROGRAM` does not need to be surrounded by a `Pass` block. Simply separate the two passes between `CGPROGRAM` tags.

i.e.,

```
ZWrite Off
Tags { "QUEUE"="Transparent" "IGNOREPROJECTOR"="true" "RenderType"="Transparent" "PreviewType"="Plane" }
    //transparency
    Blend SrcAlpha One
    CGPROGRAM
    ...
    void surf (Input IN, inout SurfaceOutput o)
    {
        // Pass 1
    }
    ENDCG

    CGPROGRAM
    ...
    void surf(Input IN, inout SurfaceOutput o)
    {
        // Pass 2
    }
    ENDCG
...

```

---
Tags: unity, shaders
---


# Question
Title: How to use an array of y values to render a 2D top-down Java game?
I'm fairly new to the world of coding, and there's probably a simple solution here. I made this array (the actual one is more complex since it includes everything I have so far) for the y values of every object that needs to be rendered, but I don't know how to use it to keep track of which y values correspond to which object in order to draw them from lowest y value to highest y value.

```
int [] yValues = {deer.getY(), sprite.getY(), tree.getY()+150};
    Arrays.sort(yValues);

```

The deer just randomly walks around, and the player (sprite) is controlled by arrow keys. I added to the y value of the trees so that characters that walk around would stay behind them.

Right now I've hard-coded the layering, depending on when the sprite is in front of or behind the tree (hair and skin y positions are dependent on the y position of the sprite, which is why I didn't include them in the yValues array).

```
//Printing order
    if (sprite.getY() < tree1.getY()+150) { //if the player is behind the tree

        g2d.drawImage(deer.getImage(), deer.getX(), deer.getY(), this);

        g2d.drawImage(sprite.getImage(), sprite.getX(),
            sprite.getY(), this);
        g2d.drawImage(skin.getImage(), sprite.getX(),
                sprite.getY(), this);
        g2d.drawImage(hair.getImage(), sprite.getX(),
                sprite.getY(), this);

        //the tree is drawn after everything else
        g2d.drawImage(tree.getImage(), tree.getX(), tree.getY(), this);
    }

    if (sprite.getY() >= tree1.getY()+150) { //if the player is in front of the tree

        //the tree is drawn before everything else
        g2d.drawImage(tree.getImage(), tree.getX(), tree.getY(), this);

        g2d.drawImage(deer.getImage(), deer.getX(), deer.getY(), this);

        g2d.drawImage(sprite.getImage(), sprite.getX(),
            sprite.getY(), this);
        g2d.drawImage(skin.getImage(), sprite.getX(),
                sprite.getY(), this);
        g2d.drawImage(hair.getImage(), sprite.getX(),
                sprite.getY(), this);
    }

```

From here, how would I use the yValues array to order the drawing?

\[I found this post helpful to what I'm trying to do\] (Java Slick2d image depth/layering).

# Answer
This is what I figured out and it works, but Martin's answer is probably a lot more efficient.

I went ahead and used the array of y values that I made, and then below it made a bunch of code segments like this:

```
for (int i = 0; i < yValues.length; i++) {
if (sprite.getY() == yValues[i]) {

            g2d.drawImage(sprite.getImage(), sprite.getX(), sprite.getY(), this);}
//And so on for each sprite.
}

```
> 1 votes

# Answer
instead of trying to identify the drawing order for each sprite itself you should create a proper drawing order first of.

```
List<Sprite> sprites;
Comparator<Sprite> topLeftComparator;

void draw(Graphics graphics){
    sprites.sort(topLeftComparator); //create proper drawing order first
    for (Sprite sprite: sprites){
        sprite.draw(graphics); //then draw all sprites
    }
}

```

## Details

let's assume you have a class (better: an interface) named `Sprite`. That `Sprite` allows you to set the position of the sprite (and read it back) and to draw it

```
interface Sprite {

    //set & read back position
    void setPostion(int x, int y);
    int getX();
    int getY();

    //draw
    void draw(Graphics graphics);

}

```

you can now create and position all Sprites that you want to draw. Add them to your list:

```
Sprite tree, player;
List<Sprite> sprites;
...
//set postion
tree setPosition(2,4);
player.setPosition(2,3);

//and add to the list
sprites.add(tree);
sprites.add(player);

```

then you simply sort that list and draw your sprites according to the order of the list (as mentioned above).

## Sorting

the magic happens when you sort the list. The sorting algorithm that is used sorts the sprites first by **y-value** (aka each row) and than by **x-value** (by column). That results in an top/left-\>bottom/right order.

```
Comparator<Sprite> topLeftComparator = new Comparator<Sprite>() {

    @Override
    public int compare(Sprite s1, Sprite s2) {
        int compareValueOfRow = Integer.compare(s1.getY(), s2.getY());
        if (compareValue == 0){ //0 means y is equal for both
            //the return according to x-pos
            return Integer.compare(s1.getX(), s2.getX());
        }else{
            return compareValue;
        }
     }

};

```
> 1 votes

---
Tags: java, 2d, rendering
---


# Question
Title: How to calculate the transformation such that two points with different position, orientation and origins line up?
Let's say you have two different 3D Objects which both contain a node that is off center (not at the origin) and have an orientation. How do you calculate the transform for one of the object so that both of these nodes line up? As in both nodes end up at the same position in space and the same orientation?

In gaming terms, both 3D objects have "snap" points and I'd like to calculate how to transform one of them so that they snap together at that specific node.

The cubes are the 3D objects, the X/Y/Z axis represent the origin of each of these objects, and the arrow is the node. The goal would be in this case both arrows overlap and thus the cubes end up at the exact same place. Note the origin is NOT at the same spot for both objects.

# Answer
For each object, you need to define a coordinate system at the snap point. If you only had a position and an orientation (depicted by the arrow in your images), you are leaving one degree of freedom (rotate around the arrow), and that leaves us with infinite solutions. Therefore, you need to define a complete coordinate system for the snap point.

For each object you should have:

* A transformation from object origin to world origin (let us call it `O`). You input `(0, 0, 0)` and get the origin of the object in world coordinates.
* A trasnformation from snap point to object origin (let us call it `S`). You input `(0, 0, 0)` and get snap point in object coordinates.

Composition of those transformation yields a transformation such that when you input `(0, 0, 0)` it gives you the position of the snap point in world coordinates.

Remember that we use matrices to represent these transformations. Thus the composition of `O` and `S` (`C = O ○ S`) is the product of their matrices (`C = OS`).

As I said, we should have this for each object. We have two objects, thus there is `O₁`, `S₁`, and `C₁` for the first object, and `O₂`, `S₂`, and `C₂` for the second object.

We want the snap point of both objects to be in the same place. That is, we want `C₂(0, 0, 0) = C₁(0, 0, 0)`. Futhgermore, we want them to be the same transformation (`C₂ = C₁`). To acoomplish this, we are going to only move the second object, respect to the world. That is, `O₂` is our unkown.

Work it as a matrix equation:

```
C₂ = C₁
O₂S₂ = O₁S₁
O₂S₂S₂⁻¹ = O₁S₁S₂⁻¹
O₂ = O₁S₁S₂⁻¹
O₂ = O₁S₁S₂⁻¹

```

That should give you the transformation for the second object.

In english: you take the inverse of the tranformation to the snap point of the second object, compose it with the transformation to the snap point of the first object, and then with the transformation to the origin of the first object.
> 0 votes

---
Tags: 3d, mathematics, algorithm, models, transformation
---


title: curve of animation in C#

text:
# Question
Title: curve of animation in C#
I think that the animation curves in Unity lack the fact of being configurable because they are only chosen with a certain type (no sinusoidal function) and adjustable with handles.

How in C # create an animation (tanslation, rotation, scale) so as, for a selected mesh, to introduce parameters of a chosen mathematical function and any corresponding, if it is a translation for example, to x\_position, y\_position and z\_position in function of the time variable?

thank you !

What if I now need to define **time intervals**? for example:

a function f1 on \[0.20\]

a function f2 on \[20.50\]

The most difficult is to convert by the correct Time.time factor so that the real time varies well in seconds within the limits defined by each of these intervals.

thanks

# Answer
> 0 votes
You find the basic trigonometric functions in the class `Mathf`. If you want something to move in a trigonometric function over time, you just need to feed the current `Time.time` into the function.

For example, if you want an object to oscillate on the y axis in a sine curve, you would add this behaviour:

```
using UnityEngine;

public class SineMovementBehaviour : MonoBehaviour
{
    void Update()
    {
        Vector3 pos = transform.position;
        pos.y = Mathf.Sin(Time.time);
        transform.position = pos;
    }
}

```
* If you don't like the frequency, multiply Time.time with a constant.
* If you don't like the phase, add a constant to Time.time.
* If you don't like the amplitude, multiply the result with a constant.

`Mathf.Sin(Time.time * frequency + phase) * amplitude;`

---
Tags: c#, animation, curves
---


# Question
Title: Why does my value increase a ton when the tab switches from inactive to active?
I basically have a lerp function similar to this one: Client interpolation for 100% serverside game when a new server update is received, the update frequency is added to a variable (msAhead) and the delta is subtracted from it every client frame. But when I do it the variable msAhead increases a lot when the tab is switches from inactive to active. Here is my code:

```
msAhead += updateFrequency; //when new update is received.

(function loop(now) {

var now = Date.now();
delta = now - Time;

Time = now;

msAhead -= delta;

console.log(msAhead);

requestAnimationFrame(loop)

    })(0);

```

How can I fix my issue?

# Answer
> 1 votes
`requestAnimationFrame` only gets called when the canvas is getting rendered by the web browser's rendering engine. When the canvas is not on the screen, no animation frames will get requested.

If you need to do processing while the tab is inactive, you can:

* use setInterval, but keep in mind that it gets throttled to once per second when the tab is inactive
* use a WebWorker

# Answer
> 0 votes
Aside from DMGregory suggestion to enforce a maximun timestep...

---

You can use the visibility API. To do so, you will register an event handler `visibilitychange` event of the document. It will fire when the user switches tab from or to your page. In the event handler you can use `Document.hidden` or `Document.visibilityState` to check if it is visible.

It is up to you how you will handle that time... If what you want is for it not contribute to the delta, what you have to do is measure it, and substract it from the delta on the next loop.

---

By the way, the user can mess with `Date.now()` by changing system time. You might want to use `performance.now()`.

---
Tags: javascript, lerp
---


title: How do I make Unity halt on exceptions?

text:
# Question
Title: How do I make Unity halt on exceptions?
I'm trying to debug a Unity project using the Unity Editor and Visual Studio. A runtime exception keeps popping up, but the debugger doesn't halt when an exception occurs, making it impossible to debug my code efficiently.

In Visual Studio, I've gone into Tools -\> Options -\> Tools For Unity and set "Exception Support" to "True". I've also enabled *all* types of exceptions in the Exception Settings panel. I am connecting the debugger to Unity using the "Attach to Unity" button. Breakpoints are working, but the debugger isn't halting on Exceptions.

What do I need to do to get Unity/VS to actually halt on Exceptions?

Note: I've tried closing and re-opening both Unity and VS many times but that doesn't make any difference.

# Answer
This documentation on the 2.0 Unity tools preview for VS implies you have to both enable Unity exception support via `Tools -> Options -> Tools For Unity` (setting "exception support" to true, as you've done) *and* enable the appropriate CLR exception masks in Visual Studio's built-in exception settings window (check the box next to "Common Language Runtime Exceptions").

For best result you may want to check and then un-check the CLR exceptions tick, as that will ensure *all* the exception subtypes are enabled to get started with.
> 13 votes

# Answer
I think, a quick solution, you can try: Write an error log in exception block of the code

```
Debug.LogError("Exception occured");

```

And before running the editor open console and hit **Error Pause** in the console log.

The game will pause as any error occurred in the console.
> 5 votes

# Answer
You may need to do a couple more things to get this working. In my case, I wanted Unity's built-in Assertions to raise exceptions that would be caught by VS. I had to do the following to make this happen.

1. Configure Unity's Assert class to raise exceptions via `Assert.raiseExceptions=true`
2. Add the specific type of Exception to VS's exception settings window. (Right click, select Add, and input `UnityEngine.Assertions.AssertionException`)
> 3 votes

---
Tags: unity
---


# Question
Title: Huge procedurally generated subway transit map
How could I generate a single transit map image , which is not based on any real map, on a massive scale? Are there algorithms or tools which could do something like this already?

> Unlike conventional maps, transit maps are usually not geographically accurate—instead they use straight lines and fixed angles, and often illustrate a fixed distance between stations, compressing those in the outer area of the system and expanding those close to the center.

The scale I'm looking for is earth-like. If a line ran horizontally across it could have 40,075 stations kind of map. Ideally, It should also wrap around, like on a sphere.

I want it to look just like any local transit map (I'm basing myself on the Montreal metro map) which means I don't care about what a metro system of this scale should look like or how useless this would be.

### So far, the research

# Answer
If the end goal is creating an algorithm which will give you a data structure roughly representing a transit map, perhaps controllable via parameters to like branching vs linearity, sprawl, number of lines, frequency of inter-line transfer stations, etc, I would begin by creating a mental model of what exactly is represented by a transit map, which I have hinted at already with some of the aforementioned parameters.

In terms of actual implementation of this model, I think a transit map can be most easily implemented as a tree, graph, or other network of linked elements.

To test the suitability of your own mental model I would recommend taking an existing real world transit map and trying to manually encode it in your proposed data structure to see if it fits well. You could even do this translation of real world transit map into data representation on paper or on a whiteboard. Tweak the model as needed.

At this point, having tested the viability of your data model, you should implement the actual generation algorithm. Keep the algorithm simple at first and expand the parameters and behavior after you can generate a basic proof of concept example transit map data.

After tweaking this generation algorithm you should have some suitable representation in data of a transit map which you can render in your engine/environment of your choice and figure out how users can best interact with it in a way that satisfies your requirements.

---

Overall this is a vague, procedure focused answer because the question itself has no specific code snippets or implementation details and as such I cannot comment concretely on any of these approaches. I think conceptually you have a firm grasp of the subject area and should try creating a prototype at this point. If it fails you can always go back to the drawing board and do more research, but I think you need to beware paralysis by analysis.
> 2 votes

---
Tags: procedural-generation, maps, image
---


# Question
Title: Is tools programming experience useful for other positions?
What does the possible career progression look like for a tools programmer? Would experience in that field be useful to gain other programming jobs in the industry, like gameplay, engine or AI programming? Or is it considered experience that only qualifies you for further tools programming jobs?

# Answer
> 0 votes
> What does the possible career progression look like for a tools programmer?

No one knows. Every career path is different.

> Would experience in that field be useful to gain other programming jobs in the industry, like gameplay, engine or AI programming?

Yes.

Now the question you did not ask:

> I want to become an engine/gameplay/AI developer, should I start by applying on jobs for developing tools because that's the only thing I have the qualification for?

Like anything related to career, it could be possible. And you could also be stuck at what you do for various reasons. You could get a job doing X and always be assigned to the same job, on the same franchise, for ten years, even if you ask HR to move you somewhere else (because, you know, you're good at it, and you know the part of the software, and we need a monkey to do that boring job). You could also get a job doing X because you want to eventually do Y, but finally find out that X is so much fun and challenging that the desire to do Y is not there anymore, and keep on doing X, on the same franchise, for ten years, and love it (because, you know, there are still so many improvements to be done and you have the freedom to apply them). You could start doing X, ask to be moved elsewhere in the company, but get stuck there, and decide to move to another company to do Y.

Yes, *any* experience helps (even if you're not from a game dev background), as long as that's what you seek and there are opportunities (it's harder if you're in a small town with only one game dev studio). This will depend on you, the company where you work, etc...

---
Tags: career
---


# Question
Title: Transform check should return null, but returns as initialized instead
In my Player script, I initialize my FirePoint transform using GameObject.Find in the Awake function. In the editor, I purposely misspelled the name of FirePoint to test if the null check inside of my Fire function will print an error to the console. The only error that shows up is from the Awake function giving a NullReferenceException, but why don't I see my Debug.LogError? Instead, the else statement prints that the FirePoint is *not* null.

```
public class Player : MonoBehaviour
{

   [HideInInspector] public Transform FirePoint;

   private void Awake()
   {
       FirePoint = GameObject.Find("FirePoint").transform;
   }

   private void Fire()
   {
       if (FirePoint == null)
       {
           Debug.LogError("FirePoint is null.");
       }
       else
       {
           print("FirePoint is NOT null.");
       }
   }
}

```

# Answer
A possible explanation could be that you set FirePoint to something in the inspector before you added the `[HideInInspector]` attribute. Adding that attribute makes it impossible to change the inspector value, but if there is already one set it won't get cleared.

If `GameObject.Find("FirePoint").transform` throws a `NullReferenceException`, then that method gets aborted before a new value gets assigned to FirePoint. So it would retain the original value.
> 3 votes

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


# Question
Title: How to avoid Singleton/Statics/Injection in my puzzle game
I am developing a puzzle game in java with swing. Purpose of the game to find the all the correct pairs on the board without ur lifes reaching 0 , preety simple etc.

1. I have a class *My\_Button* which extends *JButton*.
2. My game consists of 6 type of Tiles (*square* , *circle* etc)
3. All these type of tiles extend *My\_Button* class and i*mplements my\_Actions* interf.
4. *my\_actions* interface has some methods, not crucial for the question.
5. I have *my\_board* class which holds arraylist with buttons , initializes buttons, fills the array , checks for validity between pairs , delete pairs etc. It contains all the game functions in a way.

Now my main problem is the *actionListener* implementation and logic. In my ActionListener in simple words i add the button that got clicked to a temp array and when 2 buttons got added to this array i do certain actions. for example: (pseudo)

```
ActionListener{
my_board.posible_pair.add(this);
my_board.click_counter++;
my_board.check_game_state();
}

```

**!check\_game\_state() runs if's and updates all the info of the game like: tries,score,check\_valid\_pair,delete etc.!**

Now my thinking and my question laid out:

**First case:** If i make every Tile class implement actionListener like the example above ill have to make my\_board singleton to be able to have acess to all this variables outside of the my\_board class.

**Second case:** even if i implement actionListener inside the my\_board class and add the actionlistener through anonymous classes to my button after i add them to the board it gives error ofc because the scope gets weird.

**Third case:** full static class and variables, its really bad programming so id like to avoid.

**QUESTION:**

--How i can reconstruct my project to manage these problem without singletons/static ?

--How i can avoid putting the check\_game\_state() inside the ActionListener which also is a bad practice?

I checked infinite number of qestions on this forum , google , stackoverflow but nothing really helps on the specifics. I have developed simmilar games before but i always follow the singleton tecqniques and id like to change that.

# Answer
i would suggest that you do some work on your design - it is **a very good** idea to rethink your design to make better (less bugs) , better to test & maintain and even adding new features.

## refactoring into dynamic context

You can move your whole static code into a dynamic context once you start your `static main` method

```
public class Game {

    //static context
    public static void main(String[] args){
        Game myGame = new Game();
        game.executeDynamicMethod();
    }

    //dynamic context
    public void executeDynamicMethod(){
    }

}

```

## planning tools

furthermore make a plan what entities should be in your game and what relations they have. Best practice for these plans is usually to use UML diagrams

Use this (or a better suitable) Model to create your classes.

## Design hints

Lastly you should try to seperate concerns. Most likely you have a game entity, a so called game model and a GUI to display that game. keep these two things separate as far as you can!
> 1 votes

---
Tags: java, game-design, swing
---


# Question
Title: UnityTeams: Files to publish but no Upload button
I am using Unity 2019.2.14f1 to build a game.

As I am working with a team, we have decided to use Unity Teams for the collaboration.

The project escalated and we ended up having to architecture a different project structure, directories and files.

Due to that, I created standard folders, deleted others, moved files.

Changes were made, the project was saved and now I see the blue icon in the majority of folders and lots of items in the Project Folder.

If I look at the Collab button on the top right corner of the screen and hover the mouse it appears the message:

> You have files to publish

However, if I press the button, even though it shows the blue icon, that shows that I have files to upload, it appears:

> You are up to date!

This is the first time I saw this problem.

I have done some changes to one of the scenes to see if the problem disappeared, however it persists.

I have been waiting for quite some time now, and decided to ask you for some guidance.

Everything is fine with the network connection.

In this particular situation, the log system that will appear when I upload the files is going to be huge. Is this be the reason behind the problem? What shall I do to solve this?

# Answer
> 0 votes
My first step was letting the team know that I was having this problem to prevent them from working on the project for a while.

Then rebooted Unity, as this was an internal bug \[I also reported the situation to Unity\].

That solved my problem - classic IT solution.

I was afraid of losing all the data and changes and didn't thought that the files are saved locally.

---
Tags: unity, architecture, file, filesystem, teamwork
---


# Question
Title: How to fix 'procedural skybox' visible horizon line on 'screen space camera' canvas?
I can see the horizon line through my screen space camera canvas.

Here are the steps to reproduce it for 2019.3.0f3:

1. create a new scene
2. create a new material for the Skybox

* set shader to Skybox/Procedural
    * set Atmosphere Thickness to 4
3. open Window/Rendering/Lighting Settings

* set Skybox Material to material created in step 2
    * click Auto Generate at bottom
4. in Hierarchy add a new UI/Panel

* set canvas Render Mode to Screen Space - Camera
    * assign the main camera to Render Camera
    * set panel image color to non-transparent white
5. set main camera rotation to 15, 15, 15

The resulting artifacts:

The canvas has been disabled, for reference:

This problem starts appearing when atmosphere thickness is \> 3, currently I need 4.

**How can this be fixed, if at all ?**

# Answer
> 0 votes
I fixed it by copying the shader from builtin shaders and added `ZTest Equal`.

---
Tags: unity, skybox
---


# Question
Title: Do I need to worry about game name trademark when making a FLOSS game?
I am planning to do a small game using only FLOSS software (Free Libre and Open Source Software like Godot, Blender, Krita...).

I am going to put it on Github with an MIT license so everyone can download it and modify it.

I wanted the name of my game to be "Seed" but I saw that there was already a game called like that

My question is: do I need to worry about creating an open source game who uses the same name as a proprietary one?

# Answer
Copyright law still applies, even to open source works; in fact the GNU GPL even uses copyright law as part of its formulation, and is itself copyrighted. So being FLOSS does not give a get-out clause from copyright law, in either direction. You can still be sued for copyright (or trademark) infringement.

As always with legal questions, if you want legal advice that will hold up in court, you will need to ask a lawyer.
> 2 votes

---
Tags: copyright, licensing, open-source
---


# Question
Title: shadow mapping with directional light and octree
i am about to add shadow mapping to my simple game, i have a map level structured in an octree the camera culls out the octree nodes out of the vieweing frusutm and everything runs smooth. Now i want shadows and i have a doubt , the directional light runs is set at an infinite distance so basically it encompasses all the octree destroying the purpose of node culling. How can i add a directional shadow map and cull nodes outside the light frusutm if it is at an infinite distance ? thanks in advance

# Answer
You only care about shadows that are visible in the camera's frustum. If something casts a shadow on a surface out of the camera's view, you never see it, so you can ignore those receivers.

That lets you start with just the octree nodes that survived the camera's frustum culling pass, encompassing all visible shadow receivers.

Shadow casters that cast shadows on these receivers could be anywhere in this volume or upstream / toward the light from here. So next you extrude the camera's frustum back toward the light until it...

* encompasses the maximum bounds of your scene / loaded chunks
* reaches a maximum defined shadow-casting distance \[for this cascade\], if you find that including all arbitrarily-distant casters is impractical for your case.

Either way, you get a finite volume that needs to be drawn to your shadow map(s), letting you select a finite number of octree nodes to include in this pass.

If you need to do directional light shadows over truly immense distances that could have geometry all along the way — like a shadow of a mountain stretching all the way across the neighbouring valley at sunset — then you can swap to an alternate method of handling these, like the "terrain shadows clipmap" used in the Witcher 3, as described around 33 minutes into this GDC Talk, while keeping your conventional shadow map for the more detailed nearby shadow-casters.
> 0 votes

---
Tags: shadow-mapping
---


title: Unreal Engine without Blueprints

text:
# Question
Title: Unreal Engine without Blueprints
Hello fellow coders I have been using Unity and other game dev libraries fora fun hobby for many years (on-and-off, I am no expert!). But I really am not happy with Unity and their multiplayer network offerings. I've always wanted to master C++ in the end and also Unreal, so now is the time I will delete Unity and only use UE4 for some time.

I jump into UE4 and many tutorials (official UE website and MANY others paid and free). All of them leap straight into Blueprint system. Every time I watch/read these tutorials I think at the end, that surely the Blueprints part is unnecessary, bloated way of achieving something that can easily be achieved purely in c++ code.

I intend to ONLY work on my own. Not part of any team, and my work will never be built upon by anyone but me. Personally I dislike visual coding. I hate moving the mouse to small areas and drag-dropping stuff etc.

Will I lose out on any functions etc in the Unreal API if I decide to shun the entire blueprint system?

What reason is there to use Blueprint if you find written code easier?

Not trying to start a flame-war, just want some experienced devs to give me their educated opinion on this matter.

If it was left to me, I would learn to make some basic games in pure code using Unreal API and then I might try to recreate the same project allowing myself to use blueprints and I will see what takes longer.

But right now I don't even know how to access User Input polling values etc in Unreal, I am about to start learning it all now. Just want to set off on the correct path FOR ME :D

Thanks for any help

# Answer
I think I am in the same mindset as you are. Yes you can work in 100% C++.

My own project is 95% C++ I only use BPs for instantiating stuff (putting actors to the level) but every single BP of mine is nothing else than just a default values setter.

It is much faster to set default values in BPs as well as performing visual stuff - for example moving some scene-components in BP is much easier than moving them in C++.
> 6 votes

---
Tags: unreal-4, unreal, blueprints
---


# Question
Title: Manually update rotation of only Y-axis on Agent
I have some code to manage to rotation of my Navmesh agents:

```
if (Agent.isActiveAndEnabled && Agent.hasPath)
        {
            if (Agent.velocity.sqrMagnitude > Mathf.Epsilon)
            {
                transform.rotation = Quaternion.LookRotation(Agent.velocity.normalized);
            }
        }

```

It's causing my some issues with some odd rotations on the x/z axis for 1-2 frames every now and then, is there some way I can get this exact behaviour but only modify the y-axis?

# Answer
If your agents are always oriented vertically, this is reasonably straightforward. Just project your velocity into the horizontal plane, and look toward that. This can always be accomplished with a pure yaw, no pitch/roll required:

```
var projected = Agent.velocity;
projected.y = 0f;

if(!Mathf.Approximately(projected.sqrMagnitude, 0f))
    transform.rotation = Quaternion.LookRotation(projected);

```

The `if` check just declines to rotate if the agent has stopped or is travelling purely vertically, which helps avoid a sudden snap to 0-degrees in those cases. Instead, we'll just keep our current yaw.

If your agent can be aligned arbitrarily, then you can use this technique explained in existing answers to locally yaw to face your velocity while keeping your current/desired local up vector fixed.
> 1 votes

---
Tags: unity, ai
---