# Question
Title: Best way of passing game data in functions?
In most programs, if we want to do something to, say, Bob, then `myFun(bob)` is enough. We know that the function deals with Bob and won't touch Alice.

However, in a game, everything wants to freely interact with everything else:

**Option 1**

```
killTime(bob){
  cat=bob.getNeighbor().getPet();
  bob.talkTo(cat);
}

```

We are forced to have every piece of data hold reference to each other. Web-shaped dependency is hard to maintain, hard to serialize. Chained dots don't look nice, either.

**Option 2**

```
killTime(bob,neighborList, petList){
  alice = neighborList.findNeighbor(bob);
  cat = petList.findPet(alice);
  bob.talkTo(cat);
}

```

The argument list can get long, and it is not clear what should be included. What if we want Bob to read his poem written in his notebook hidden in his drawer?

**Option 3**

```
killTime(world, bob){
  cat = findTheCatYouLike(world, bob);
  talkTo(world, bob, cat);
}

```

Bob could do anything to `world` in his small talk, not necessarily a bad thing in a game. But it doesn't feel right passing the same `world` to every function. Also, if we use C, then we are forced to have pointer members instead of data in `world`, just to reduce the compilation time of `#include "world.h"`

I don't think any approach I found is good. What would be the least bad solution in this situation?

================== edit ================

To elaborate my question, suppose that we have a RPG system, with world map, characters with HP, MP, so on. Now we want a simple `player.walk` function. `position+=velocity` straightforward? Not really. What if we want footprints on map? What if we deal damage to units we pass by? We now need to touch everything in game to in order to walk.

In most programming scenarios, it is assumed that function and data are coupled to each other. Only these functions work on these data, and only these data are used for these functions. Put the functions and the data into a class, and it's high cohesion.

I am looking for an architecture where the opposite is true. I have a bunch of data (hp, mp , pos, vel), a bunch of actions (walk, attack, wait). That is all I can be certain of. I want the flexibility to change my mind everyday how the actions affect the data. In my code, I actually started with option 1 and gradually slid into option 3.

# Answer
> 0 votes
There are many architectural patterns you see in game development. So there is no one-size-fits-all solution.

But I would like to introduce you to a common architectural pattern in game development which solves many of the problems the question asks about: The Entity - Component - System architecture.

In a nutshell, each entity is a combination of components (which are just dumb structures without methods) and each game feature is implemented as a system which operates on a set of components.

One problem with the method `killTime(bob)` is that you can't tell what it actually does just from the name. What does it mean for bob to "kill time"? Wander around the game world? Regenerate health? Pet his cat? All of that? But these are all very different game features which require very different data. So instead of just creating a `killTime` method, we create a separate system with a separate name for each of these "kill time" features. This doesn't just allow us to cleanly separate game features, it also allows us to cleanly separate their data by only passing the components these systems need.

So we would have code which works more like that:

```
updateWanderSystem(positionComponent, routeFindingComponent, map);
updateHealthRegenerationSystem(healthComponent);
updatePetSystem(positionComponent, petOwnerComponent);

```
* Names which actually say what the function does gameplay-wise
* Injection of the dependencies the function needs and only those it needs
* No need to follow long reference chains within these functions
* Most of these functions will even be unit-testable in isolation without unintended side-effects.
* (C-specific issue) the system implementations only require the headers for the components they operate on, keeping recompilation times short.

Note that none of these systems operates on "bob" as an object. It operates on a tuple of components which might belong to "bob". The advantage of this pattern is that you can use a system on any entity in the game which has the necessary set of components. Which is why ECS architectures usually don't operate on a per-entity basis but rather run each system one after another passing all components of all entities currently in the game to it as one array each.

This also has performance advantages. When a for-loop operates on an array which contains only the data it needs (as opposed to an array of objects which contain a lot of data it doesn't need) there is a good chance that that array completely fits into the CPU cache. This allows the CPU to copy the array into the cache at the start of the loop and then process the loop lightning fast without doing any memory access.

# Answer
> 0 votes
Great that you asked, *Why?* about such a fundamental aspect of programming. This is how better thinking and better tools emerge. However, classic OO-style programming languages are unlikely to change any time soon, so for you, the key thing is to classify your problem and then evaluate it according to your needs.

"Good" vs "bad" is based on what you see as most important - concision (static structure), orderly organisation of code (static structure), reduced indirection (a dynamic or runtime concern), lack of stateful side-effects (at runtime), etc. *Each of these factors plays off against the others.*

You'll find that static, architectural concerns are often at odds with runtime performance concerns. A more human-readable codebase (OO being the prime example) tends to be less performant, whilst more performant code, i.e. code better suited to the machine's architecture, is often a lot harder for *us* to follow.

This answer is long, but I want to put things into perspective for you in terms of the programming paradigms used.

**Option 1**

This is what OO purists advocate, as it reads like a natural language sentence.

However, it also contains potentially costly *double indirections* such as `bob.getNeighbor().getPet();`. Certainly `.getNeighbor()`'s result can be cached and used multiple times in the same function, but what if you only need it once? If the object is temporarily fixed (for more than a single frame), such as a cat having a new neighbour who will stick around, then you can say `cat.neighbour = bob`, to avoid making method calls to retrieve the `owner` every single frame (although profiling the impact thereof, is up to you).

Over time these indirections can be eliminated in critical sections of the code to address performance, with these sections clearly marked as optimised for x and y concerns, to avoid anyone re-refactoring them for readability in future. As performance increases, the code looks less and less canonically OO.

OO incurs costs also through its vtables, which procedural languages do not suffer from.

**Option 2**

This is sort of a hybrid between pure OO (1) and procedural (3) approaches.

Long argument lists are a common feature of C which is the modern reference point for procedural programming; often these are packed into a single context argument (`struct` or object) which is similar to `this` in OO languages (only, it is explicitly given unlike `this` which is implicit).

However, you are still using `.findNeighbor()` and `.findPet()`, which are *methods*, not global functions, and as such exist only in OO languages.

**Option 3**

This is pure procedural programming, around long before OO arrived. Functional programming is closely related, albeit that it has additional constraints around inputs and outputs.

Here you will find no `this` and no `somebody.doSomething()` *methods*; only global *functions* like `doSomething(somebody)`. That is, *where* (i.e. on what object) each function is located, is not important here: functions exist in global space. This is closer to the way they are represented in the machine's instruction cache, which makes no distinctions.

Procedural programming, for games at least, is commonly used for small, inherently fast programs written in the C language (or C subset of C++). C is commonly used where you need a special purpose component that to be lightning fast - faster than primary code written in e.g. C# or Java.

Functional programming is similar to procedural, but mandates that we inject all of the necessary inputs as function or method arguments, and returns all new output(s) based purely on those inputs and nothing else, i.e. neither inputs nor outputs are based persistent state as found in `this` members, or global members found at module level. This aims to reduce errors caused by state / side effects, assuring a higher degree of program correctness and debuggability.

**Cost of method calls and indirections**

Dot-syntax drilldown, e.g. `owner.cat.bowl`, incurs costs, this is known as *double indirection*.

In Assembly / machine code, these cause what are called `JMP` ops, which require the machine to "jump" to different location in either instruction (functions, methods) or data (members) cache, possibly causing cache invalidation, which is a major cause of reduced performance in code.

**Conclusion**

I'd aim for OO, i.e. 1 or 2, though between these, there is no "right way". I would go with option 1 until I saw a need for option 2, although 1 is more work as you have to write extra getter functions for each little thing (with a decent IDE, this is not so bad). Uncle Bob favours clean architecture over performance, suggesting we aim for the most concisely readable code *first*, and optimise only in critical sections. His background is in business programming, where maintainability comes first. In games, however, this is only where we *start*.

If you aim for program *correctness* right off the bat, and tend to have a mathematical mindset, functional programming may be preferred.

If you like C (or Basic, Pascal or Delphi) for whatever reasons, procedural may be preferred.

---
Tags: architecture
---


title: OpenGL color attachments don't work

text:
# Question
Title: OpenGL color attachments don't work
Trying to implement GBuffer. Only `gAlbedoSpec` color attachment (GL\_COLOR\_ATTACHMENT2) works properly. When i try to use another texture (gPosition or gNormal) in shader, `texture(...)` returns color from glClearColor. It means OpenGL doesn't write data to other color attachments. How to fix it?

GBuffer creation:

```
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);

glGenTextures(1, &gPosition);
glBindTexture(GL_TEXTURE_2D, gPosition);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gPosition, 0);

glGenTextures(1, &gNormal);
glBindTexture(GL_TEXTURE_2D, gNormal);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0);

glGenTextures(1, &gAlbedoSpec);
glBindTexture(GL_TEXTURE_2D, gAlbedoSpec);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gAlbedoSpec, 0);

unsigned int attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);

glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE){
    std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl;
    exit(1);
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

GBuffer using:

```
    glClearColor(0,0,0,1);
    glEnable(GL_CULL_FACE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glClearColor(0.1f,0.1f,0.1f,1); // gPosition, gNormal is always has this color
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // ... rendering objects with GBuffer writing-shader
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    gbuffer_shader->use(); // GBuffer test-rendering shader
    gbuffer_shader->uniformMatrix("projview", ui_mat);
    gbuffer_shader->uniform1i("gPosition", 0);
    gbuffer_shader->uniform1i("gNormal", 1);
    gbuffer_shader->uniform1i("gAlbedoSpec", 2);

    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D, gAlbedoSpec);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, gNormal);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, gPosition);

    // ... rendering fullscreen quad with VAO

```

GBuffer writing Vertex Shader:

```
#version 330 core

layout (location = 0) in vec3 v_position;
layout (location = 1) in vec2 v_texCoord;
layout (location = 2) in vec3 v_normal;

out vec4 a_color;
out vec2 a_texCoord;
out vec3 a_normal;
out vec3 a_fragPos;

uniform vec4 u_color;
uniform mat4 model;
uniform mat4 projview;

void main(){
    mat4 normalMatrix = transpose(inverse(model));
    a_color = u_color;
    a_texCoord = v_texCoord;
    a_normal = (normalMatrix * vec4(v_normal, 1.0f)).xyz;
    a_fragPos = v_position;
    gl_Position = projview * model * vec4(v_position, 1.0);
}

```

GBuffer writing Fragment Shader:

```
#version 330 core

in vec4 a_color;
in vec2 a_texCoord;
in vec3 a_normal;
in vec3 a_fragPos;

layout (location = 0) out vec3 gPosition;
layout (location = 1) out vec3 gNormal;
layout (location = 2) out vec4 gAlbedoSpec;

uniform sampler2D u_texture0;

void main(){
    gAlbedoSpec.rgb = (a_color * texture(u_texture0, a_texCoord)).rgb;
    gAlbedoSpec.a = 1.0f;
    gPosition = a_fragPos; // doesn't work
    gNormal = normalize(a_normal); // doesn't work
}

```

GBuffer test-rendering Vertex Shader:

```
#version 330 core

layout (location = 0) in vec2 v_position;
layout (location = 1) in vec2 v_texCoord;
layout (location = 2) in vec4 v_color;

out vec2 a_texCoord;
out vec4 a_color;

uniform mat4 projview;

void main(){
    a_texCoord = v_texCoord;
    a_color = v_color;
    gl_Position = projview * vec4(v_position, 0.0, 1.0);
}

```

GBuffer test-rendering Fragment Shader:

```
#version 330 core

in vec2 a_texCoord;
in vec4 a_color;
out vec4 f_color;

uniform sampler2D gPosition;
uniform sampler2D gNormal;
uniform sampler2D gAlbedoSpec;

void main(){
    f_color = vec4(texture(gPosition, a_texCoord).rgb, 1.0); // returns always initial (glClearColor) color
}

```

# Answer
> 1 votes
Solved by replacing count of color channels of `gPosition` and `gNormal` to 4 (`RGBA16F`) as `gAlbedoSpec`. Now GBuffer creation:

```
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);

glGenTextures(1, &gPosition);
glBindTexture(GL_TEXTURE_2D, gPosition);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gPosition, 0);

glGenTextures(1, &gNormal);
glBindTexture(GL_TEXTURE_2D, gNormal);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0);

glGenTextures(1, &gAlbedoSpec);
glBindTexture(GL_TEXTURE_2D, gAlbedoSpec);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gAlbedoSpec, 0);
glBindTexture(GL_TEXTURE_2D, 0);

GLenum attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);

glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

```

---
Tags: opengl, shaders, deferred-rendering
---


# Question
Title: How to position/transform vertices for 2D UI in shaders?
I am building a 3D engine and have a rendering abstraction that focuses on writing shaders. Most my 3D shaders have `gl_Position` output like:

`gl_Position = projection * view * model * vec4(position, 1);`

I would like to draw some 2D UI on top of all the 3D draw calls. I am having a hard time understanding how to do this.

Let's say I wanted to draw a HUD player life bar that is fixed to the bottom left corner of the screen. I can imagine drawing a quad. and maybe applying a texture to it. I would have 4 vertices for the quad to feed to the shader. How would I change the `gl_Position` calculation to handle drawing only to 2D screen space? Would I update the transformation to only apply the `projection` matrix?

`gl_Position = projection * vec4(position, 0, 1);`

How to determine the local coordinates of the quad verts? When the screen scales or resolution varies, How to ensure the quad stays positioned to the lower bottom screen? How to ensure the quad dimensions stay the same ratio?

# Answer
For 2D UI you typically achieve this by using an orthographic projection matrix, and setting view and model to identity, which collapses the typical transform:

```
gl_Position = projection * view * model * vec4(position, 1);

```

To:

```
gl_Position = projection * vec4(position, 1);

```

So yes, this approach is correct.

To lay out the UI elements, there are a number of possible approaches, but one simple and commonly used one is to set up your ortho matrix like so:

```
glOrtho (0, width, height, 0, -1, 1);

```

Or if you prefer:

```
glm::ortho (0, width, height, 0, -1, 1);

```

And you can then lay out your UI using screen co-ordinates. note 1

What might not be immediately obvious is that *width* and *height* here need not be the width and height of your window (or screen); they can be any arbitrary values. So you could, for example, decide to use *width* 640 and *height* 480 and then lay out your UI as if you had a 640x480 screen, and the ortho matrix will automatically scale and position all UI elements for you.

640x480 obviously assumes a 4:3 aspect ratio, which - on most computers from the last 15-odd years - you and your users probably don't have, so just adjust the numbers to the correct aspect ratio; e.g. for a 16:9 aspect ratio you might use 800x450 instead.

note 1: If this causes your UI to be upside-down onscreen, simply reverse the bottom and top params, like so: (0, width, 0, height, -1, 1).
> 3 votes

---
Tags: opengl, shaders, gui, graphics-programming, webgl
---


title: Unity immediate mode

text:
# Question
Title: Unity immediate mode
I have some existing C++ 2D game code that draws using immediate mode (i.e., each frame is drawn bottom-up one sprite at a time by my game code -- not using a scene graph or other retained mode concepts). I'm wondering if I can port this code to Unity without having to rework the game code to operate in terms of retained mode (adding objects to a scene, removing objects, etc.). I have read that Unity has an immediate mode GUI option. But in my case I want to use this for the game sprites themselves, not just the UI elements. I realize that for a 2D game there isn't a big difference between UI elements and game sprites. But I need to be able to do things like rotation and render-to-texture, so I wasn't sure if I'd run into trouble "misusing" the immediate mode GUI mechanism to handle the whole game. Alternatively, does Unity have a more general immediate mode option? (I did search for it and didn't see anything aside from the immediate mode GUI stuff.)

# Answer
## First of all, you should not be doing this.

The Unity scene graph exists for a reason. It's the very core concept which the engine architecture is built around. By rolling your own you are locking yourself out of approximately 99% of the features Unity provides to you. You won't really gain much over just keeping your codebase in C++. If this is just about portability, there are ways to make a C++ codebase portable to multiple platforms (but that's out of the scope of this question).

When you switch to a different technology to do the same thing you were already doing, then your first instinct is often to try to find a way to do everything in exactly the same way you used to do. But that's usually a bad approach, because you won't be using the tool in the way it was intended to be used. It's a bit like a carpenter switching from hammer and nails to screwdriver and screws, trying to drive the screws into the wood by repeatedly hitting them with the screwdriver, having a bad time and awful results and then wondering why everyone claims that screws are a viable alternative to nails.

A far better way to learn a new tool is to approach it with no preconception about how it is supposed to be used, familiarize yourself with its design choices and philosophies and embrace the differences rather than the similarities.

## Still wanting to do it that way?

If you really want to manually draw sprites directly to the screen, then Unity can do that with the method `Graphics.DrawTexture` (the rest of the `Graphics` class might also come in handy for you).

It will draw a specific texture directly to specific screen coordinates, completely ignoring the camera position and settings, transform of the gameObject, z-buffering, post processing, UI-layout, and all the other nice features you pay for with your Unity license.

Create a Monobehaviour and implement the OnGui method to draw your sprites with Graphics.DrawTexture in the order you want. Here is the example which draws a sprite 2000 times per frame to random points in a 400x400 rectangle. Regarding performance: It runs at over 200 FPS on my machine:

```
using UnityEngine;

public class TextureRenderer : MonoBehaviour
{
    public Texture sprite;
    public int numOfSprites = 2000;

    void OnGUI() {
        if (Event.current.type.Equals(EventType.Repaint)) {
            for (var i = 0; i < numOfSprites; i++) {
                Graphics.DrawTexture(new Rect(
                                         Random.Range(1f, 400f), // x-position
                                         Random.Range(1f, 400f), // y-position
                                         64f, // width
                                         64f  // height
                                     ),
                                     sprite);
            }
        }
    }
}

```
> 2 votes

---
Tags: unity, rendering
---


# Question
Title: How to isolate a child object from parent's movement? (Unity)
I currently have a very basic scene that includes a platform (ground), a capsule (player), and a camera rotator (main camera is mounted on it). The object hierarchy is the following.

This hierarchy reflects the objective of having a main camera that rotates about the player when correct command is entered.

A problem arises when the player moves. In this case, the capsule rotates about its vertical axis which causes the main camera to rotate because the camera rotator is mounted on the player. How could I isolate the camera rotator so that it remains mounted while ignoring the capsule's rotation. Thanks for considering my question.

# Answer
> 2 votes
Many Unity tutorials start with just attaching the camera as a child to the player. While this is a quick and easy way to get going (while also demonstrating pretty well how transform hierarchies work), it's usually not how most real games end up controlling their camera.

If you want your camera to follow the position of an object but not its rotation, then it can be a good reason to separate your camera rig from its subject and add a script to the rig which makes it follow the subject. The most simple script would be this:

```
 class CameraController: MonoBehaviour {

        public Transform subject;

        Update() {
             transform.position = subject.position;
        }
 }

```

It simply sets the position of the camera rig to the position of its subject, but leaves the rotation as-is.

There are many ways to upgrade this basic script to make the camera movement smarter. You can use it to implement delayed or preemtive scrolling, enforce scroll boundaries, smooth out scrolling, switch the subject of the camera (preferably with a smooth pan instead of a sudden jump), add screenshake and many more.

---
Tags: unity, c#, game-design, camera
---


# Question
Title: 3d points to rotation matrix of orientation
I have a vector in a 3D view, defined by a point p1(x1, y1, z1) and a rotation r1(x1, y1, z1). I can get a direction and a yaw. I need that vector to point another point p2 (x2, y2, z2). So I need a new rotation.

Coordinates: Coordinates are expressed like this: (5, 45, -12) This refers to the position where X=5, Y=45 and Z=-12. The 3 letters are called “axes”: Y is for the height. X and Z are for the horizontal position. Rotation: Yaw and pitch (radians). It can be converted to degrees.

I get this function, where d is the direction (vector between pos1 and pos2):

> d = normalize(d); double yaw = Math.Atan2(d.X, d.Y); double pitch = Math.Asin(d.Z)

Is it Ok?

# Answer
It seems to work using the following formulas:

```
d = normalize(d);
double yaw = Math.Atan2(-d.X, d.Z); // Counter-clockwise from Z+
double pitch = -Math.Asin(d.Y);     // Y = up, positive pitch = down

```
> -1 votes

---
Tags: 3d, trigonometry
---


# Question
Title: How do I run functional tests against my Unity3D game?
## Context

I am continuing some legacy code for a game in Unity3d, and I want to write some functional tests meant for regression, to ensure I don't break things when implementing new things or when refactoring.

I already know there is the 'Unit Test Tools' suite for Unity3d available as an asset. I have used it as a unit-test suite, so I test my models (classes).

## Example of what kind of test I am thinking about

For "functional test" I mean things like this:

* Run the program
* When in the menu scene, assert there is a button that says "start"
* Click it
* Then assert a new scene is loaded
* Assert pixel XXX is red
* Click in coordinate XXX
* Assert now that the pixel changed to green
* etc.

## Questions

**Q1:** How do I write and run *functional* tests for my game? Is this also typically done in the UnityTestTools (UTT)?

**Q2:** If UTT is more for Unit-Testing, then is there a separate suite for functional testing? Which one?

*Notes:*

I'm targetting Android, and running `Unity5.3.1f1`

# Answer
> 1 votes
As I understand it, you're looking to understand automation testing in Unity.

**Unity Test Tools**

This should be your goto method, but before digging into how, I'll examine the why.

The preferred way to do any form of automation testing is to do this in an environment as close to production as possible. Using something like the Unity Test Tools (living inside the Unity Editor) sounds like a bad idea for anyone who'd written conventional integration tests.

Why? Because with any integration testing, you want the least amount of extra stuff bogging down your application that's not there when the user opens it. The Unity Editor might have different performance or behavior compared to the iOS version (for example).

*So, why use Unity Test Tools (UTT) then?*

The main reason is convenience. Both the Unity Editor and UTT are built around being easy and visual to use. You'll have an easy time writing tests, hooking them with your specific game, and understanding when they fail.

*What about the difference in behavior between the Unity Editor and production?*

After all, the Unity Editor is a wrapper around your application. That means, there will be *some* differences between the Editor and production. But, integration testing aside, the Unity Editor has been a wrapper for a very long time now. It is a **mature platform** with thousands of game built on it. The results you get from running integration tests inside the Editor will be very accurate.

In the example scenario you provided, everything but the first item can easily be asserted using Unity Test Tools. You can open scenes and validate behaviors just like any other integration tests.

I suggest writing most (if not all) of your tests using UTT. To add compatibility with continuous integration tools (e.g. Jenkins), you might want to run those from the console using command line arguments.

**Starting the application and manual testing**

Starting the application isn't something you have precise control while in the Unity Editor. To validate that aspect of your game and more, you can use some basic manual tests.

Here's how to approach that:

1. Make sure your game emits some kind of signal when it reaches the specific milestones you care (or might care) about. Logging to a file is the most common approach (using the automatic builtin logging or a 3rd party version).
2. Periodically read and analyze the logs. This can happen manually or be scripted using your second-favorite scripting language.

**Alternatives**

Not surprisingly, as everything Unity related, we have more than a few alternatives. Here are some you might want to consider:

Depending on the scale and scope of your project you might want to employ one or many of the options I outlined above.

# Answer
> 0 votes
For anyone finding this question post 2019 this is now possible with the Unity Test Framework. https://docs.unity3d.com/Manual/testing-editortestsrunner.html

---
Tags: unity, automated-testing
---


# Question
Title: How to get x in radius percentage value?
How to find the percentage value from A to B when I know the X value in between these two points?

I created this picture to kind of illustrate what I mean better.

I wrote this function which gets the percentage, but how do I also include the center offset?

```
private float GetPercentage(Vector2 point, float radiusOffset, float centerOffset)
{
    float radius = Math.Min(circle.rect.width / 2f, circle.rect.height / 2f);

    radius *= radiusOffset;

    return 1f - (Math.Max(Math.Abs(point.x), Math.Abs(point.y)) / radius);
}

```

The radius offset is from 0-1, 0 being the 0,0 position and 1 full radius. The center offset is from 1-0, 1 being the 0,0 position and 0 being the radius border.

# Answer
> 1 votes
I’m assuming you mean you want the percentage of X between B and A, where at 0.0, X=B and at 1.0, X=A. The formula should be this: (pseudo code, I don’t know unity’s math functions)

```
float r = dist(X, center);
return (r - innerRadius) / (outerRadius - innerRadius);

```

You can calculate innerRadius and outerRadius with the radius and center offsets. Your description is little unclear so figure out how to do that yourself.

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


# Question
Title: Ideal way to instantiate abilities in a class give a dynamic list of abilities to use?
I have a PlayerClass class that is used to set my Player's class. For instance, this will make him a warrior:

```
 PlayerClass warrior = new WarriorClass();

```

WarriorClass will instantiate abilities like so:

```
 Ability ability1 = new LeapAbility();

```

Now my problem is that I will eventually dynamically update my Warrior's abilities (think talent trees or perks).

So say I give warrior a list of abilities to use. How do I do this in code? Right now I need to know the Abilities before hand and hard code their instantiation in.

Put another way, how do I instantiate a dynamic list of objects? I'm open to other solutions too if this doesn't make sense or is impossible.

# Answer
> 1 votes
You could have a function that takes in a string, which can be loaded dynamically, and returns a new ability.

```
Ability createAbilityById(String s) {
    switch (s) {
        case “leap”: return new LeapAbility();
        case “foo”: return new FooAbility();
        ...
    }
}

```

You can also look into reflection if your language supports it, but it may be overkill or too complicated.

---
Tags: game-design, architecture, objects
---


# Question
Title: Unity - Global illumination seems no longer applied to static objects on runtime
First of all I'm newbie with Unity, so please forgive me if the answer of this question is obvious for any experimented developer.

So, in one of my project I have this result while I run the project in the editor:

However, on runtime I get this result:

As you can see, several objects in the scene are no longer lighted. In fact, I noticed that ALL my static objects lost their illumination on runtime. I tried with Windows and WebGL as targets, same result.

As I'm hobbyist, I may provide any info about the project configuration. Better, I can provide the Git link of my project: https://github.com/Jeanmilost/Unity/tree/master/Survival%20Demo%20Scene

This is a demo project, but in the future I'm interested to create more serious projects, and thus I need to understand why this issue happen. So if someone can point me what I'm doing wrong, I would be very grateful, because I already spent some hours to search the solution, without success.

# Answer
> 1 votes
Ok I found the issue finally. I configured the quality to very low in the project settings, which ruined the lighting of my scene. Please forgive my ignorance but I'm a beginner :-)

---
Tags: unity, lighting, lightmap, global-illumination
---


# Question
Title: How do I set up the microphone for an Android device in Unity?
I'm developing a simple android app that needs to use the microphone. I'm able to load my app on my Android phone using developer mode, but I do not understand how to enable the mic. How can I enable the microphone and use the input?

I started with a brand new Unity 2D project. I created a TextMeshPro Text object to display logs and set this reference on the script via the inspector. I have attached the following script to the Main Camera.

```
using UnityEngine;
using UnityEngine.Android;
using TMPro;

public class RequestPermissionScript : MonoBehaviour
{
    public TextMeshProUGUI logs;

    void Start()
    {
        if (Permission.HasUserAuthorizedPermission(Permission.Microphone))
        {
            // The user authorized use of the microphone.
            logs.text = "has authorized";
        }
        else
        {
            // We do not have permission to use the microphone.
            // Ask for permission or proceed without the functionality enabled.
            logs.text = "has not authorized";
            Permission.RequestUserPermission(Permission.Microphone);

        }
    }
}

```

I then Build and Run this as Android and the app is loading on my Android phone attached via USB.

I expect a pop-up to appear asking for permissions to the mic, but this does not happen and the logs says "has not authorized". What am I missing or doing wrong?

# Answer
> -2 votes
with this line the pop-up opens: Permission.RequestUserPermission(Permission.Microphone);

you have to include: using UnityEngine.Android;

Hope this helps...

---
Tags: unity, android
---


# Question
Title: How do you allow joints in a character to fall freely based on gravity?
I am building a game in Unity in which a character falls down on death. Is it possible to make the joints fall and bend based on gravity? That is to leave the joints fully dependent on gravity and colliders and not any skeletal animation.

# Answer
> 0 votes
If you want to know how to use a RagDoll. First, you should try the Ragdoll wizard. You should also look at Brackley's video on this. Find a rigged body on the asset store and turn on the physics debugger and use the ragdoll wizard on it. Then just play around with the colliders and joints.

---
Tags: unity, collider, joints
---


title: Rotation of a 3D ball on a plane

text:
# Question
Title: Rotation of a 3D ball on a plane
This used to be on the physics stack exchange but I was told to put it here:

I'm making a game (with physics) and I have a 3D ball rolling down a flat plane. It moves perfectly fine, but the rotation is messed up. It seems way too fast, and the axis seems to be all wrong. Here's the code that runs every tick (20 times per second). (`normal` is the normal to the plane, `acceleration` is gravity vector projected onto the plane, in m/tick2, and velocity is the velocity in m/tick.)

```
vec3 rotationAxis = normalize(cross(normal, acceleration));
quat newRotation = rotate(oldRotation, length(velocity) / sphereRadius, rotationAxis); // rotate by v/r radians about the rotationAxis

```

I'm not sure why this doesn't work, since according to angular mechanics, v=rω and ∆θ=v∆t/r (and ∆t=1 since velocity is in meters/tick). Am I doing something wrong? Why is the rotation so much faster than it should be? And is my axis of rotation correct?

Rephrased in a more physics way, is this correct in 3D:

$$\hat{x} = \frac{\hat{N} \times \vec{a}}{|\hat{N} \times \vec{a}|}$$

$$\Delta \theta \textrm{ about } \hat{x} = \frac{v}{r} \Delta t$$

And if it is correct, then what’s wrong with my code?

# Answer
Your `rotationAxis` should be the cross product between your `velocity` vector and the surface `normal` vector as velocity contains the direction of movement whereas acceleration is not necessarily in the direction of movement. (E.g. Projectile motion where acceleration is always down.)

i.e. `vec3 rotationAxis = normalize(cross(normal, velocity));`

**∆θ = length(velocity) / sphereRadius** seems right since

$$ 2\pi Radius \ meters/tick = 1 \ (full) \ rotations/tick = 2\pi \ radians/tick $$

So, $$ x \ meters/tick = \frac{x}{Radius} \ radians / tick $$

You say velocity is per tick so length(velocity) is the speed in meters/tick. Hence, $$|Velocity| \ meters/tick = \frac{|Velocity|}{Radius} \ radians / tick $$

Therefore, every new tick, you should rotate by $$\frac{|Velocity|}{Radius} \ radians$$ which is what you're doing.

Make sure your sphereRadius is also in meters as length(velocity) is in meters/tick.
> 1 votes

---
Tags: physics, linear-algebra
---


# Question
Title: Ray casting through terrain mesh + Octree ( Mesh collision )
I'm currently in development of a terrain editor which i will use for my game. One thing that is partially stopping my development is that I don't have collision detection implemented between mouse ray cast and the terrain mesh.

The terrain is consisted of triangles and can be lowered and raised.Also the x and y values of the mesh don't change. Of course what i need to do is ray cast through my mouse positions and get intersected triangle. I would get the point on the triangle using Barycentric coordinates. Just I'm not quite sure how does octree come into play here. As far as I understand it it works like a 3d quadtree, splitting the box into smaller box that the ray intersects. But which box do i choose ? How do i know which box is the closest one to the terrain, if either raised or lowered terrain ? How many subdivisions would i have? I was thinking on having as much as i have tiles( basically the last level of subdivisions would correspond to a x^3 box).

Right now i'm just doing collision with the 0 Z-value plane, and it works okay, but if the terrain is a bit raised then this can give faulty results.

Other two methods that i found is to iterate through the mesh, which of course is insanely inefficient; the other is to project the terrain in reverse and then i guess do some checking with the mouse coordinates (think it's called z-buffer checking or something).

If anyone has any other ideas i'm all ears. Just note that the algorithm should be an efficient one (of course this depends on the implementation) and accurate.

Thanks !

# Answer
> 1 votes
I've managed to implement the ray cast-terrain mesh collision detection.

First I take the origin of my ray and just "project" it onto a XY plane (basically just take X and Y coordinates of the origin vector). Then I calculate the end vector based on the distance I want and the direction (unit vector) from my ray struct.

When that's done, I use that newly formed line (origin-\>end) to intersect my terrain quad and **only** keep the line that is inside the quad; at the same time I am able to calculate my intersection points using the Line-Edge intersection (https://stackoverflow.com/a/1968345/9200518 \- the one I used).

Since I've got the point I need, thus the start and end tile of my line, as a reference I've used this, which is similar to Bresenham's line algorithm.

Upon getting all the quads that my line intersects I just checked each triangle per quad if It intersects.

I haven't tested this as far as performance goes, but it might help out someone!

---
Tags: rendering, terrain, mesh, terrain-rendering, editors
---


title: URP PostProcessing doesn't work?

text:
# Question
Title: URP PostProcessing doesn't work?
I'm trying to get postprocessing work again after updated to URP. But it does not work !!

Could anyone help me with any solution or clue ?

# Answer
> 1 votes
In the Main Camera component put the tick in Rendering \> Post Processing. You also don't need to have a separate layer for the volume and camera any longer as far as I know. Should not make a difference for whether it's working or not, though.

If you're working with volume triggers do not forget to put a collider on the object.

---
Tags: unity, post-processing
---


# Question
Title: How do you handle entity life-time and entities without all components in an ECS?
I'm just starting to implement my own ECS and am drawing everything down on paper to make sure I understand it all before tackling the implementation in code. However I'm getting stuck on entity-lifetime and nothing I've read really answers my question.

Just to be sure I'm not missing something, my understanding so far is:

1. Components of the same type all sit next to each other in memory
2. Entities are just an ID, which Components refer to (i.e. Components have an "owner")
3. Components all have a unique Id

Great! So for example, say I have a `PositionComponent`, `VelocityComponent`, and `VisibleComponent`.

```
struct PositionComponent {
    vector2f position;
};

struct VelocityComponent {
    vector2f velocity;
};

struct VisibleComponent {
    Image imageToRender;
};

```

Great. Now let's say I have two types of Entity:

1. **EntityA** has a position, velocity, and visible components
2. **EntityB** has a position and velocity component, but is not visible

(let's hypothetically say that the `Image` in the visible component is the actual image data because every entity is super unique or something)

Say I have an `PhysicsSystem` which wants to iterate over all the Position and Velocity components and update the Position. This works, because every entity I've created has both of these components.

And so we're using EntityID as an index into the component arrays, we can easily know we're accessing the correct ones.

But then if there was a `RenderSystem` that wants to iterate over all the Position and Visible Components, the problem is that the EntityId can no longer be an index into the arrays, because not every Entity has every component.

So; the way I've thought to address this is by having an "Entity to Index Map" for each component. Basically, this EntityID has a `PositionComponent` in index 232 of the array.

But because of this, now any system that needs two or more Components to act, will lose out on all the benefits of an ECS, right?

I dismissed giving all components arrays empty space to keep them all "in sync", but that means I could have a lot of wasted data, which only gets worse the more different components I create.

There's then the problem of lifetime. If EntityID 232 is killed, I ideally would shift all the components in these arrays down to fill the gap, which again means I can't use EntityId as an index into the arrays.

A solution I thought of here was to re-use EntityIDs when they're no longer needed, maybe by using a 16bits of a 32-bit ID as the actual array index, and the other 16-bits as some sort of random guid to keep it clear that it's a new entity (and not the old one who's EntityID is being reused). This means I don't need to shift the data around, and wouldn't need to keep a map from ID to Index; but it doesn't solve the problem where not all entities have all components, so none of the arrays can ever be assumed to be "in sync".

So in summary my questions are: 1. **How does a System in an ECS handle iterating over two separate components, when it's not guaranteed both component arrays will have the same entities components in the same indices?** 2. **Is it more beneficial to keep the data compact, or keep the arrays in sync?**

# Answer
> 1 votes
One way this can be solved is with the notion of Archetype.

An Archetype is the set of components a particular entity needs. So in your example you have two archetypes: (position, velocity, visible) and (position, velocity).

For each archetype, you store an array of each component it needs, densely packed, representing all entities of that one archetype.

So here you have one trio of arrays for one archetype, and a separate pair of arrays for the second archetype.

Your entity ID can be a combination of high bits that indicate its archetype, and low bits that represent its index in that archetype's arrays.

Since each archetype stores entities that use every component of the archetype, you don't have to contend with mismatched or gappy collections.

A system then acts by iterating over all the archetypes that match its component needs, and churning through their arrays of its components of interest. You'll typically have lots of entities of each archetype, so you still get good cache coherency this way, taking a miss only when you switch to a different archetype.

To contend with destruction, a solution I've seen is to...

* Defer any destruction of entities to the end of an update frame, so it doesn't interfere with fast iteration the rest of the time.
* Handle deletion by swapping to and deleting from the end of the collection, so that the active entities stay densely packed.
* Forbid any script from holding onto an entity index/pointer longer than one frame. Instead, entites that need cross references have a stable long-term ID stored separately. Scripts can hold this stable ID, and when they need to actually look up a component, ask to translate it into the correct index/pointer to use this frame, then discard and re-request next frame (when it might have moved to a different spot).

Updating the mapping of this stable ID to an index can be done lazily by memoized search (if you expect to delete often and reference rarely), or proactively by book-keeping during swaps (if you expect to reference often)

---
Tags: architecture, entity-system, entity-component, entity-component-system
---


title: Webgl build error in unity

text:
# Question
Title: Webgl build error in unity
I get an error while trying to build a game for webgl. I have created a new 3d project with only a cube in it and have not created any scripts. When I try to build and run the webgl option, these are the errors I get.

```
    Failed running "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" -E "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"G:\webgl\Assets\..\Temp\emcc_arguments.resp"

```

```
stdout:
stderr:INFO:root:Checking JS engine ['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096'] failed. Check your config file. Details: [Error 5] Access is deniedCRITICAL:root:The JavaScript shell (['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096']) does not seem to work, check the paths in the config file
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

```

```
UnityEditor.BuildPlayerWindow+BuildMethodException: 3 errors
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002bb] in <480b5a3bd3214ce5831f6dd8c68fdc55>:0
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <480b5a3bd3214ce5831f6dd8c68fdc55>:0
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

```

This is what the editor log shows:

```
C:\Program Files\Unity\Hub\Editor\2019.3.13f1\Editor\Data\il2cpp/build/deploy/net471/il2cpp.exe exited after 228169 ms.
Filename: "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe"
Arguments: -E "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"G:\webgl\Assets\..\Temp\emcc_arguments.resp"
index: -1
Failed running "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" -E "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"G:\webgl\Assets\..\Temp\emcc_arguments.resp"

stdout:
stderr:INFO:root:Checking JS engine ['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096'] failed. Check your config file. Details: [Error 5] Access is deniedCRITICAL:root:The JavaScript shell (['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096']) does not seem to work, check the paths in the config file

```

I'm not sure how to resolve this....Can someone please help...

# Answer
This is what worked for me:

1. Uninstalled nodejs from the system along with the path from environment variable.
2. Reinstalled nodejs in the C drive program files and added the new path in environment variable.
3. Restarted the system and created new unity project and ran the webgl build.
> 1 votes

---
Tags: unity-webgl
---


title: Detecting "Any Button Press"

text:
# Question
Title: Detecting "Any Button Press"
I'm trying to allow the player to press any button to continue from the main page. I was able to do this by making a List of Buttons and looping through these and checking for one of them being down; however, I feel like this code is kind of ugly and wonder if there's a simpler way to do it that I'm just not thinking of?

Here's my what my code looks like now:

```
            if (GamePad.GetState(PlayerIndex.One).IsConnected)
            {
                var buttonList = new List<Buttons>()
                {
                    {Buttons.A},
                    {Buttons.B},
                    {Buttons.Y},
                    {Buttons.X},
                    {Buttons.Start},
                    {Buttons.Back},
                    {Buttons.RightShoulder},
                    {Buttons.LeftShoulder},
                    {Buttons.RightTrigger},
                    {Buttons.LeftTrigger}
                };

                foreach (var button in buttonList)
                {
                    if (GamePad.GetState(PlayerIndex.One).IsButtonDown(button))
                        ExitMainMenu= true;
                }
            }

```

# Answer
> 11 votes
This should do the job. In the end of every update loop, save state of `previousGamePadState`. Then you can compare em. This is fast way to detect changes. No need to loop.

**GamePadState.PacketNumber**:

You can use PacketNumber to determine whether input state has changed. If the value of PacketNumber remains the same between two sequential calls to GetState, then there has been no change in input.

```
public bool HasInputChanged(GamePadState previousGamePadState, bool ignoreThumbsticks)
{
    GamePadState currentState = GamePad.GetState( PlayerIndex.One );
    if ((currentState.IsConnected) && (currentState.PacketNumber != previousGamePadState.PacketNumber))
    {
        //ignore thumbstick movement
        if ((ignoreThumbsticks == true) && ((currentState.ThumbSticks.Left.Length() != previousGamePadState.ThumbSticks.Left.Length() )&&(currentState.ThumbSticks.Right.Length() != previousGamePadState.ThumbSticks.Right.Length()) ))
            return false;
        return true
    }
    return false;
}

```

**EDIT:** Changed to method. It's not guaranteed to work right as is, but should work. Also, because this really detects changes in input, so if user releases button, it is seen with this also. I also added `if` to detect thumbstick movement, so you can ignore those at least.

Hope this helps you. Let me know, if it does not suit your needs, I'm sure we can work this out.

How to: Detect Whether a Controller Button Has Been Pressed This Frame GamePadState.PacketNumber Property

# Answer
> 2 votes
You could manually construct an empty `GamePadState`, and then check it for (in)equality with the current real one, which you fetch by calling `GamePad.GetState`.

```
playerInput = GamePad.GetState(PlayerIndex.One);
emptyInput = new GamePadState(Vector2.Zero, Vector2.Zero, 0, 0);
if (playerInput != emptyInput){

    // yay!!!!, a button push!
    //
    // P.S., remember to allow any PlayerIndex to take control of the the game
    // from the main menu.  It sucks when you pick up controller2 and it doesn't work.

}

```

# Answer
> 1 votes
If you don't mind the use of Reflection, you can use something sort of like this (possibly even this exactly):

```
        var properties = typeof(GamePadButtons).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var property in properties)
        {
            var value = property.GetValue(GamePad.GetState(PlayerIndex.One).Buttons);
            if (value is ButtonState && (ButtonState)value == ButtonState.Pressed)
                ExitMainMenu = true;
        }

```

# Answer
> 1 votes
Since Buttons is an enumaration you can use the Enum.GetValues method like this:

```
var buttonList = (Buttons[])Enum.GetValues(typeof(Buttons));

foreach (var button in buttonList)
{
    if (GamePad.GetState(PlayerIndex.One).IsButtonDown(button))
        ExitMainMenu= true;
}

```

# Answer
> 0 votes
Riffing off @Katu's original answer, this seems fastest/cleanest. Just check for GamePad input. Done.

```
    bool GamePadInputChanged(GamePadState previousGamePadState)
    {
        var currentState = GamePad.GetState(PlayerIndex.One);
        return currentState.IsConnected && currentState.PacketNumber != previousGamePadState.PacketNumber;
    }

```

---
Tags: xna, monogame
---


# Question
Title: Animation is delayed after few play attemps even though all transition times' are zero
I am trying to play animation forward and backward when player press the same button again and again. I have a straight line and I want to convert it to 8 while moving it. I want to play animation backward or forward from the exact frame where I pressed the button again.

When I pressed the button, animation starts playing and moving and If I pressed the button again in the middle of animation it is played backward from the exact frame. However, after a few try my animation starts playing with a delay or it stops playing completely.

I am sending speedMultiplier parameter to make the speed -1 to play backward my animation.

This is the video of the problem

```
private Animator eightAnimator;
private bool isLine;
private bool isMoving;
private bool becomingEight;
private bool becomingLine;

private Vector3 nextPosition;
private Vector3 startPosition;

// Start is called before the first frame update
void Start()
{
    isMoving = false;
    isLine = false;
    becomingEight = false;
    becomingLine = false;
    eightAnimator = GetComponent<Animator>();

    startPosition = this.transform.position;
}

// Update is called once per frame
void Update()
{
    if(Input.GetKeyDown(KeyCode.M))
    {
        eightAnimator.SetBool("isMoving", true);

        if (isLine)
        {
            isMoving = true;
            isLine = false;
            becomingEight = true;
            becomingLine = false;
            nextPosition = new Vector3(this.transform.position.x + 6, this.transform.position.y, this.transform.position.z);
            eightAnimator.SetFloat("speedMultiplier", 1f);

        } else
        {
            isMoving = true;
            isLine = true;
            becomingLine = true;
            becomingEight = false;
            eightAnimator.SetFloat("speedMultiplier", -1f);
        }

    }

    if(becomingEight)
    {
        this.transform.position = Vector3.MoveTowards(this.transform.position, nextPosition, Time.deltaTime * 10);

        if (Vector3.Distance(nextPosition, this.transform.position) < 0.01f)
        {
            isMoving = false;
            becomingEight = false;
            eightAnimator.SetBool("isMoving", false);
        }
    }

    if(becomingLine)
    {
        this.transform.position = Vector3.MoveTowards(this.transform.position, startPosition, Time.deltaTime * 10);

        if (Vector3.Distance(this.transform.position, startPosition) < 0.01f)
        {
            isMoving = false;
            isLine = true;
            becomingLine = false;
            eightAnimator.SetBool("isMoving", false);
        }
    }

}

```

I am adding here unity package, video, screen shot and my simple code.

So how can I play my animation when I pressed the button with the exact frame and exact time without delay

This is the project unitypackage file

# Answer
> 1 votes
In your move.cs file, add this at the very top of the Update() method:

```
if(!becomingEight && !becomingLine){
    eightAnimator.SetFloat("speedMultiplier", 0f);
}

```

Although I have to say, this is all quite a bit of a hack. A much better way would be to have 2 animation states (eight and line) and toggle between them in the animator using animation transitions. But that would be almost a complete rework of your project and far outside the scope of your question.

P.S. Not in your question, but I noticed the very first time pressing "M" after running the project nothing happens. To fix this, change "isLine = false" to "isLine = true" in your Start() method.

---
Tags: animation, animator
---


title: Infinite loop ping test for each player

text:
# Question
Title: Infinite loop ping test for each player
For my Unity game I have a Client-Server model, and I want both sides to ping each other repeatedly to make sure I know what latency between players is. In the server's case, a client connects and their details are logged. Their details are then used when the game creates coroutines. This coroutine starts a loop which pings and waits and pings and waits, etc, until the game ends.

However, it doesn't work. The debug messages are throwing up strange results. It attempts to ping to IP "**::ffff:192.168.0.10**", and then is waiting forever. I don't suppose the fact I am running this via Unity editor and another app window on the same machine should be an issue? What is the "::ffff" about in the IP it saves when a client connects? Is that the issue? If so, how can I best format it properly?

Yes, I need to add another loop in the coroutine to make it go forever. Once would be a nice start though.

**CLIENT CONNECTS TO SERVER**

```
    // Recieve data from all.
    NetworkEventType recData = NetworkTransport.Receive(out socketId, out connectionId, out channelId, buffer, bufferSize, out dataSize, out error);

    switch (recData)
    {
        case NetworkEventType.ConnectEvent:
            if (localConnectionId == connectionId)
            {
                // My active connect request approved.
                Debug.Log("Connection request approved.");
            }
            else // New client.
            {
                string outIp;
                int outPort;
                UnityEngine.Networking.Types.NetworkID outNetwork;
                UnityEngine.Networking.Types.NodeID dstNode;
                byte outError;
                NetworkTransport.GetConnectionInfo(socketId, connectionId, out outIp, out outPort, out outNetwork, out dstNode, out outError);
                AllocateNewLobbyPlayer(socketId, connectionId, channelId, outIp, outPort);
            }
            break;
   }

```

**CREATE PING LOOP COROUTINES**

```
    for (int i = (Game.isServer) ? 1 : 0; i < lobbyPlayers.Length; i++)
    {
        if (lobbyPlayers[i] != null)
        {
            Debug.Log(" STARTED PING FOR " + i);
            StartCoroutine(PingTest(lobbyPlayers[i].ip));
        }
    }

```

**PING LOOP COROUTINE**

```
protected IEnumerator PingTest(string ip)
{
    Ping ping = new Ping(ip);
    Debug.Log(" SENT PING " + ip);
    while (!ping.isDone)
    {
        Debug.Log("WAITING");
        yield return new WaitForFixedUpdate();
    }
    Debug.Log(" PING COMPLETED " + ping.time);
    yield return new WaitForFixedUpdate();
}

```

**DEBUG OUTPUT**

```
 STARTED PING FOR 1
 SENT PING ::ffff:192.168.0.10
 WAITING
 WAITING
 WAITING

```

etc, etc, etc...

# Answer
> 1 votes
Ping is implemented differently on different platforms.

On some platforms, it's an ICMP Echo Request (the thing that happens when you enter `ping [ip-address]` in your command shell). These might be blocked by firewalls or routers which do not block the normal game traffic. On others it tries to open a HTTP connection to port 80, which of course doesn't do much if the target IP does not run a webserver.

If what you actually want to do is check the quality of the game connection, you are better off implementing your own Ping message as part of your game's network protocol.

# Answer
> 0 votes
To add to @Philipp answer,

don't forget that there is `NetworkTransport.GetCurrentRTT()` that allows you to get milliseconds that it takes to travel to destination and back. Notice, you have to be already connected for this to work.

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


title: Mesh turns black after baking light

text:
# Question
Title: Mesh turns black after baking light
I had to port a project from Unity to Unreal which relied mostly on baked lighting.

When I baked the light (StaticMeshActor set to Static), the 3D model in the map turned black.

Without bake (dynamic lighting):

After baking the light:

# Answer
It turns out the 3D model had not been unwrapped.

You can check this by going into the Static Mesh Editor, double-click on the mesh:

Take a look at the UV channels for the mesh:

My model had an empty panel, like below, so I had to unwrap it in Blender.

It makes sense that Unreal can't determine where to put the light data without the UVs. I'm not sure why this worked in Unity though.

For 3D models that received proper baked light, this view looked like this:
> 2 votes

---
Tags: unreal-4, lightmap
---


# Question
Title: How to implement a mechanic of entering a town
I am planning a game played on a 2-D map, where some spots are "towns". When the player walks into a town, he enters a high-resolution map of this town; when he exits the town, he returns to the low-resolution map of the world (as in e.g. Ultima 4). My question is how to implement this enter/exit mechanism in Unity? I thought of two approaches:

1. The world map and each of the town maps is a different scene. Entering/exiting a town is implemented by loading the appropriate scene using the scene manager.
2. There is a single scene, but the maps are geographically separted. For example, the world map is in coordinates 1...256, town A map is in coordinates 301...364, town B map is in 401...464, etc. Entering/exiting a town is implemented by moving the player and the camera to the appropriate map.

Is there a better approach? What approach is commonly used to implement this mechanism?

# Answer
> 1 votes
There is never a best solution. Only the solution which is best for your game and your personal workflow.

However, I would suggest a third solution.

1. One scene only
2. Store every map as a prefab (The Grid object with the tilemaps and all the objects on the map)
3. When the player switches maps, destroy the old map and instantiate the new one.

Why only one scene? I am generally not a fan of creating levels as scenes. The reason is that you usually have a lot of stuff you want to have in every level, like the UI, gameplay-controllers and the player game-object. Keeping all that stuff consistent between all levels can be a real pain. And then you also have the problem of passing data between scenes which can be another source of headache. Sometimes you won't get around it. If you want to use baked GI, for example (which you usually won't use in a 2d game). But when I can, I try to keep all levels in the same scene.

Why maps as prefabs instead of one large map? Performance *could* be a concern, but with today's hardware and Unity's optimized tilemap rendering you really have to try hard to create a 2d tilemap which is so large that you get performance problems (Believe me, I tried). No, the reason for this is mostly convenience. When you can edit every map in isolation, then you don't have to worry about keeping gaps large enough that the player doesn't get to peek. And you don't need to move stuff around (probably breaking a few triggers) when it turns out your estimations were off. And then there is the problem that active game-objects on other maps still do their stuff when the player is on a different map, which might lead to side-effects you don't expect. It also makes it easier to collaborate between multiple map designers, because they can work on different maps in parallel without interfering with each other.

# Answer
> 0 votes
The first solution is a widely accepted standard, but the second solution works best for immersion and continuity. However, it may not be viable from a performance standpoint, depending on how large your map will be and how much computing power you are using elsewhere.

It is also important to consider the player's means of travel. It is never a good idea to require the player to travel very long distances at a slow pace. If I'm understanding your ideas correctly, the first solution would effectively reduce the map size and thus reduce the distance between any two given points on the world map.

---
Tags: unity, 2d, game-mechanics, tilemap
---


# Question
Title: Retro-game development - how did 8-bit computers store large level maps and build a screen from them?
Not sure whether this would be better in the retro-computing exchange, but I'm trying in game development first. During the 80s I played a lot of what would now be called "arcade adventures" on the BBC Micro; games like Citadel, Camelot, Jet Set Willy, etc. Jet Set Willy could support 64 rooms, Citadel had over 100.

Presumably, some form of **encoding** was used to compress the maps to fit in the limited storage space that these machines had, but does anyone have any information on how these games actually managed to cram screen layout and object types and locations into this limited space, then decode these into a tilemap and game objects?

# Answer
> 4 votes
Bit of a history lesson... I'll give you some ideas of how this would have worked *in general*.

Bear in mind that in those years there weren't really canonical ways of developing games - it tended to be a one or two person endeavour that depended entirely on the ingenuity of the programmers involved. They didn't have access to the internet or, typically, to academic texts. You had the manual / specification for your language of choice (often C or Basic); that was about it.

Some approaches, like RLE for byte or bit-level compression (for secondary storage), were certainly more common. More complex algorithms like ZIP, were still years away.

**Binary-level data: nibbles**

The idea here is that you can use less than a single byte, to store some element of data. A fraction of a byte was historically termed a *nibble*. One used to hear this term used often, since it was crucial to use every last bit of your 16-128kb (typically) of memory.

For example, for a typical roguelike, which in the present day would typically use 1 whole byte or 4 byte word for each map cell, a game constructing a similar map then might have used 1-4 bits for a wall. If all you have is one type of wall + empty space, then 1 bit per wall suffices; but if you needed 8 different types of wall, you'd use 3 bits (2 to the power of 3). So 0 might be empty space, 1 a stone wall, 2 a wooden wall, etc.

If you need to store multiple dimensions of data, for example if a wall has up to 4 hit points, then you would need an additional 2 bits to represent those 4 values.

For the sake of ease and reduced instructions to decode this data (remember, \< 2Mhz was not uncommon at the time), the nibbles would usually be a power of two: 2^0 = 1 bit nibble, 2^1 = 2 bit nibble, 2^2 = 4 bit nibble.

The reason for this is the way CPUs access data on byte (now word) boundaries. For example, for 5 bit nibbles, two in a row would anyway take up 2 bytes (10 bits and then another 6 unused or part of the next nibble), but sit at different offsets, meaning you have to do that much more (conditional) processing just to get at your 2nd element's data - even today, this is not worthwhile. At that time, it would have been a waste of a very limited resource - processor cycles.

**Primitive compression: RLE**

The idea here is that the more large, solid or empty, contiguous spaces you have, the better compression you will get. Instead of looking at some fruit and going, "**A**pple, **A**pple, **P**ear, **B**anana, **B**anana, **O**range", you say **2A1P2B1O**. The more apples and bananas next to each other, the better the compression.

When bringing data in from the disk for each new level, RLE or other primitive forms of compression were used. But for in-memory data,aAt 320x160 full screen resolution, a full screen of 8x8 tiles = 40x20 = 800 tiles. 800 x 4 bits = 3.2bk - already a considerable amount for the time. Depending on the characteristics of that *part* of the map, you might compress down to 30%, so 1kb in a good case.

This was why games of the open world type tended to have far fewer terrain details than they do today: examples include BattleZone and Koronis Rift. The Eidolon and Rescue on Fractalus stored a jaw-dropping amount of terrain detail for their time, using heightmaps similar to more modern voxel engines such as that in the Novalogic games like Comanche, or even Minecraft.

**Sparse data structures**

The idea here is that empty space need not be specified: only things that exist are specified with a position in otherwise empty space.

The Apshai series by Epyx used exclusively (screen) axis-aligned, rectangular rooms, so for this sort of level description, you can expect much better compression than for cell-based maps, as all you need store is the x, y, width and height of a limited number of rooms. Width and height could even be specified in 4-bit nibbles as 1 single byte, giving you just 3 bytes per room! (excluding monsters and treasures). These values could then further be subjected to bit-level compression.

This an example of *sparse* data specification, which comes in many forms, specifying just the centre position and radii of circles or spheres for example, which is how 1990's game Ecstatica specified its 3D geometry to its renderer.

Note that sparse data can also be used as an intermediate format, which is then expanded before the level begins. Perhaps we need map cells / tiles to walk on; that is what the sparse data will then be expanded to, so that the player can move around. The moment the level completes, this expanded data is discarded and only the sparse data remains (in memory or, more likely, in secondary storage).

Today's sparse data structures include octrees and point clouds.

**Generation at runtime from minimal "seed" data**

This is what we today call *procedural generation*. Various mathematical, bitwise and logical operations are used to expand a relatively small series of bits into *vast* quantities (in some modern games, enough to form an entire galaxy of detailed systems and planets) of data. Or in the original Rogue and its follow-ups, enough data to create countless fairly sized, well detailed maps of terrain, creatures, traps, vaults, treasures etc. The only limitation was how much "map" the machine could hold in memory at one time, once generated just before entering a level.

Probably the seminal release was Rogue (1980), which offered the player multi-screen maps on your typical 80x40 ASCII terminal display of the time. ProcGen took 8-bit architectures to the limit with David Braben's Elite, which was ported to many 8- and 16-bit platforms, due to its success.

The main issue with this approach is that it is hard to control exactly what it creates, so programmers have to give up a degree of control in order to gain an endless variety of possible levels without the need to actually store them - instead being generated at runtime, just before the level commences. There was a fascinating article on the web a few years ago, where David outlined the *many* complex hoops that had to be jumped through in code to "reign in" and amend the original, procedurally-generated world (one of millions that they could have chosen, mind you) to the relatively sensible galaxy that Elite eventually shipped with.

And as with the other approaches, you can only expand as much into data as you have space for, which in those days was limited indeed. So this limits the amount of data you the player can read before some more loading/expansion takes place.

---
Tags: algorithm, compression
---


# Question
Title: How do I display the next speaker image in my dialogue?
I am working on a dialogue system and while the text part works, the UI for the Dialogue Boxes does not.

When I click on the Continue button, I want the script to go down the Elements \[\] and use the Image that I have selected there, similar to what the sentences\[\] feature does.

This is my script:

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

public class TextDialogueScript : MonoBehaviour
{
    public TextMeshProUGUI textDisplay;
    public TextMeshProUGUI ContinueDialogue;
    public Image UIDisplay;
    public string[] sentences;
    public Image[] CharacterNames;
    public Sprite[] CharacterDialogueBox;
    public Image[] CharNames;
    //public List<Image> DialogueBoxes = new List<Image>();
    // public List<Image> CharacterName = new List<Image>();
    private int index;
    private int DBindex;
    public float typingSpeed;
    public GameObject DialogueTrigger;
    public GameObject DialogueEventController;
    public GameObject NormalEeventController;

    // Start is called before the first frame update
    void Start()
    {
        NormalEeventController.SetActive(true);
        DialogueEventController.SetActive(false);
        UIDisplay.enabled = false;
        ContinueDialogue.enabled = false;
    }

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

        if(textDisplay.text == sentences[index])
        {
            ContinueDialogue.enabled = true;
        }

    }

    public void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Player"))
        {
            NormalEeventController.SetActive(false);
            DialogueEventController.SetActive(true);
            StartCoroutine(Type());
            ContinueDialogue.enabled = true;
            UIDisplay.enabled = true;
            UIDisplay.sprite = CharacterDialogueBox[DBindex];
        }

    }

    public void OnTriggerStay(Collider other)
    {
        if (ContinueDialogue == true)
        {

        }
    }

    public void OnTriggerExit(Collider other)
    {
        NormalEeventController.SetActive(true);
        DialogueEventController.SetActive(false);
        ContinueDialogue.enabled = false;
        UIDisplay.enabled = false;
    }

    IEnumerator Type()
    {
        foreach(char letter in sentences[index].ToCharArray())
        {
            textDisplay.text += letter;
            yield return new WaitForSeconds(typingSpeed);
        }
    }

    public void NextSentence()
    {

        ContinueDialogue.enabled = false;

        if(index < sentences.Length - 1)
        {
            index++;
            textDisplay.text = "";
            StartCoroutine(Type());
        }
        else
        {
            textDisplay.text = "";
        }

        if (DBindex < CharacterDialogueBox.Length - 1)
        {
            DBindex++;
        }

    }

}

```

I was using a List that grabbed sprites, but the problem is, it would only use Sprites from the Assets and not the Hierarchy. This is a problem because I have messed with the colours using Unity and played around with the Alpha to get the exact effect I want that cannot be replicated with my image program.

(I do not know what the term is for adding \[\] on the end of items to add elements that can be expanded. I have been stuck on this dialogue system for a *very* long time and I am very tired yet excited because I am so close to getting this to work, that it's painful)

# Answer
It looks to me like you might want to use some custom data structures for this.

First, one for your character:

```
[CreateAssetMenu(fileName="NewDialogueCharacter.Asset", menuName = "Dialogue/Character")]
public class DialogueCharacter : ScriptableObject {
    public Sprite portrait;
    public Sprite nameTag;
    public Color32 colour;
}

```

That will give you the ability to define new characters in your Asset folder using the Create menu, and set them up with a name, portrait, and tint colour that all fit together. This way, if you need to change something about the character, you can change it in one places, rather than having to search through every line of dialogue they speak to keep the changes in sync.

Next we'll define a type to store one beat of our dialogue:

```
[System.Serializable]
public struct DialogueBeat {
    public string text;
    public DialogueCharacter character;
}

```

Now your dialogue script can specify an array of `DialogueBeat`s:

```
public class Dialogue : MonoBehaviour
{
    public Image portrait;
    public Image namePlate;
    public TextMeshProUGUI textBlock;

    public DialogueBeat[] beats;
    int _currentBeatIndex;

    // ...
}

```

Which looks like this:

This packages-together everything we need to display a particular part of the conversation in a single array, so we don't need to juggle multiple arrays and keep them in sync.

Your NextSentence method can then stay quite similar:

```
public void NextSentence()
{
    ContinueDialogue.enabled = false;

    textBlock.text = "";
    if(_currentBeatIndex < sentences.Length - 1)
    {
        _currentBeatIndex++;
        var beat = beats[_currentBeatIndex];
        textBlock.text = "";
        ShowCharacter(beat.character);
        StartCoroutine(Type(beat.text));
    }
}

```

With minor teaks to typing sentences and displaying a new character:

```
IEnumerator Type(string text) {
     for(int i = 0; i < text.Length; i++) {
         textBlock.text = text.Substring(0, i);
         yield return new WaitForSeconds(typingSpeed);
     }

     // No need to check this in Update, just set it when we're done.
     ContinueDialogue.enabled = true;
}

void ShowCharacter(DialogueCharacter character) {
    if(character == null) {
        portrait.enabled = false;
        namePlate.enabled = false;
        return;
    }

    portrait.enabled = true;
    namePlate.enabled = true;
    portrait.sprite = character.portrait;
    portrait.color = character.colour;
    namePlate.sprite = character.nameTag;
}

```
> 1 votes

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


# Question
Title: Unable to launch Unity due to license glitch
A few hours ago, Unity crashed on me. When I went to re-launch it from Unity Hub, that's when the nightmare started.

Any time I try to launch a project from the Unity Hub, the Unity Hub disappears, the Unity splash screen opens, and then about 3 seconds later the Unity Hub reappears, followed shortly by the Unity splash screen disappearing. I can't get the editor to actually load!

I looked in the Unity Editor log and found this:

```
[LicensingClient] ERROR Failed to connect to local IPC
[Licensing::Module] Failed to connect to channel: LicenseClient-Mason
[Licensing::Module] Successfully launched the LicensingClient
[Licensing::Module] Successfully connected to LicensingClient on channel: LicenseClient-Mason
[Licensing::Module] Successfully launched and connected to LicensingClient
Entitlement-based licensing initiated
[LicensingClient] Licenses Updated successfully in LicensingClient

LICENSE SYSTEM [202059 16:58:48] Next license update check is after 2020-05-10T19:18:29

Built from '2019.3/staging' branch; Version is '2019.3.10f1 (5968d7f82152) revision 5859543'; Using compiler version '191627012'
OS: 'Windows 10  (10.0.0) 64bit' Language: 'en' Physical Memory: 16332 MB
[Licensing::Module] License is not active (com.unity.editor.ui). HasEntitlements will fail.
BatchMode: 0, IsHumanControllingUs: 1, StartBugReporterOnCrash: 1, Is64bit: 1, IsPro: 0
No valid Unity Editor license found. Please activate your license.

```

I do, in fact, have a valid Unity Editor license. It was working just fine this morning, and it doesn't expire for several months yet. Looking at the "Manage license" function in Unity Hub confirms this. A bit of Googling suggests doing some of the following things, all of which I have tried, to no avail:

* Reboot the computer.
* Delete the Unity license file in C:\ProgramData\Unity and recreate it in Unity Hub.
* Uninstall and reinstall Unity.
* Update to the latest Unity version.

There was no Windows Update, driver update, or hardware change that could have provoked this. It happens no matter which version of Unity I attempt to open, and no matter which project I attempt to open, and nothing I do to attempt to fix it actually works!

The one thing that does work, for whatever reason, is creating a new Unity project. This creates a new project as expected, but the Unity theme is reverted to a light gray background, rather than the dark mode I'm accustomed to with my license, and once that project is closed, attempting to reopen it is just the same as attempting to open any other Unity project.

I tried opening Unity on my old, broken computer that has the same license, and it opens just fine... but that computer is old and broken, and will take several times longer to do anything on. Apparently there's some serious issue, *specific to my dev machine*, that came out of nowhere this morning and is causing license verification to fail.

Anyone have any idea how I can fix this or, failing that, how I can reach someone at Unity Technologies to get their help fixing it? Try as I may I can't find any option anywhere on their web site to reach a human being for customer service, at a time when I urgently need a live human being, rather than a "open a ticket and we'll try to respond to it within 3 days if you're lucky". I'm just finishing up something that I was hoping to have ready today, and this has disrupted everything!

# Answer
> 1 votes
Hit the same thing this week. Apparently newer versions of Unity Hub are just completely broken. There is a link to version 2.0.4 in this thread. Just downloaded it myself and verified everything works now. I would just avoid upgrading and follow that thread as well as the Unity Hub Release Notes.

---
Tags: unity
---


# Question
Title: Generating interesting water using perlin noise
I use `Mathf.PerlinNoise` to generate grass/water in a 2d square. It works as intended, however I am not really getting very interesting water, and at times it can look very bare or unrealistic, here is a sample of a bad generation:

Unfortunately it took me about 20 tries to find an interesting one, what I want is something along these lines:

Or something like this, but I don't want any tiny areas of water:

You can copy/paste the components below and try urself with 1x1 cubes (if you don't have Odin just delete that part):

```
using UnityEngine;
using Sirenix.OdinInspector;

public class GenerateMap : MonoBehaviour
{
    [Range(0, 40)]
    public int mapWidth = 20;
    [Range(0, 40)]
    public int mapHeight = 20;
    [Range(0, 20)]
    public float noiseScale;

    [Space]
    public GameObject parent;
    public GameObject grassTile, waterTile;

    [Button("Generate map")]
    public void GenerateMap()
    {
        for (int i = 0; i < parent.transform.childCount; i++)
        {
            Destroy(parent.transform.GetChild(i).gameObject);
        }

        float[,] noiseMap = Noise.GenerateNoiseMap(mapWidth, mapHeight, noiseScale);

        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                Debug.Log(noiseMap[x, y]);

                if (noiseMap[x, y] >= .3)
                    Instantiate(grassTile, new Vector3(x, 0, y), Quaternion.identity, parent.transform);
                else
                    Instantiate(waterTile, new Vector3(x, 0, y), Quaternion.identity, parent.transform);
            }
        }
    }
}

```

Noise:

```
using UnityEngine;

public static class Noise
{

    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, float scale)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];

        Vector2 offset = new Vector2(Random.Range(0, 100), Random.Range(0, 100));

        if (scale <= 0)
            scale = .0001f;

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float sampleX = x / scale + offset.x;
                float sampleY = y / scale + offset.y;

                float perlinValue = Mathf.PerlinNoise(sampleX, sampleY);
                noiseMap[x, y] = perlinValue;
            }
        }

        return noiseMap;
    }
}

```

# Answer
Try lowering the scale, and adding multiple octaves.

Also I wouldn't suggest Mathf.Perlin, because it generates its namesake Old Perlin noise, which has visible square alignment. I would import Unity.Mathematics and use Unity.Mathematics.noise.snoise(float2) for a good 2D Simplex noise implementation instead.

Take any tutorial or project, which uses "Perlin" noise, with a grain of salt. Most times Perlin is used, are because a library included the function, or because the author heard about its iconic-sounding name first. Rarely is Perlin chosen because it was carefully thought out to be the best algorithm for the purpose.

You could do the following:

* Use a bigger number for `scale`
* `float2 pos = new float2(sampleX, sampleY);`
* `float noiseValue = noise.snoise(pos) + 0.5f*noise.snoise(pos * 2f + new float2(35f, 66f) + 0.25f*noise.snoise(pos * 4f * 2f + new float2(75f, 104f);` where the frequency doubles but the amplitude halves each time. The offset is to prevent the same features from overlapping at the origin of the noise. You can also experiment with frequency and amplitude values that aren't exactly double / half the previous.

EDIT: Re-reading the part of your post that discusses what you're looking for, maybe what you want to do is choose 1-3 randomized points in your map that designate water bodies, choose a radius, compute the squared euclidean distance from each (plus the radius), and add a simplex noise onto that to give it some interesting boundaries. Make sure the frequency is low enough and amplitude high enough to deviate it enough from circular. In the case of lakes overlapping, you can make them join together smoothly if you use a formula like `float lake1 = (1f - (dx*dx + dy*dy) / (radius + smallPadding)); lake1 *= lake1;` where `dx = (input point).x - (lake center).x` and the same for `dy`, then doing `float totalLake = lake1 + lake2 + lake3 + snoise` and `block = totalLake > smallThreshold ? water : grass`
> 1 votes

---
Tags: unity, perlin-noise
---


# Question
Title: Trying to to hold animation while jumping then end it when he hits the ground
What I want is the single frame of animation to hold while in the air then for it to go back to idle when my character hits the ground.

my script right now is

public class CharacterAnim : MonoBehaviour { private Animator anim;

```
void Start()
{
    anim = GetComponent<Animator>();
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        anim.SetTrigger("jump");
    }
}

```

}

Anything is appreciated

# Answer
> 0 votes
You haven't provided much information to go on, but assuming you have already set up your animation controller, I have the falling state set up as below

As you can see in my movement layer, I have three blend tree's for Idle(Not moving) Upright Movement (Walking, Running) and Crouched Movement, but more importantly for your question as you see off to the left I have my **falling** and **landing** state, you can enter the **falling** state (which is just a small very animation set to loop) from **any** other state while the condition **IsGrounded** is **false**.

This means I can Trigger the jump animation (then somewhere physically move my character up) and the animation plays 'automatically' because grounded is now false, this works well because now even if you didn't jump but walked off the edge of something tall you would still transition into the falling state.

To check if I am grounded I do a small raycast down from my character to see if I hit anything with a collider, if I do, **IsGrounded** equals **true**, otherwise I must be falling

*(this isn't entirely the case as I could have my character positioned in such a way I am actually stood on something but the ray hits nothing such as standing near a ledge you can fix that by firing a raycast from each foot and checking the results of both)*

```
public override bool IsEntityGrounded()
{
    if (Physics.Raycast(transform.position, -Vector3.up, out RaycastHit hitInfo, groundCheckLength))
    {
        isGrounded = true;
        return true;
    }
    else
    {
        isGrounded = false;
        return false;
    }
}

```

Then when **IsGrounded** becomes **true** again(because the raycast is now hitting the ground) it transitions to Landing which plays a small animation showing the character going from the falling animation to the landing animation.

---
Tags: unity
---


title: How can I stop infinite jumping?

text:
# Question
Title: How can I stop infinite jumping?
I've got my jump down but I can't find a way to stop infinite jumping.

Here is my code:

```
public class Jump: MonoBehaviour
{
    public float speed = 5f;
    public float jumpSpeed = 8f;
    private float movement = 0f;
    private Rigidbody2D rigidBody;

    private bool isGrounded;
    public Transform groundCheck;
    public float checkRadius;
    public LayerMask whatIsGround;

    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();
    }

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

        movement = Input.GetAxis("Horizontal");
        if (movement > 0f)
        {
            rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
        }
        else if (movement < 0f)
        {
            rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
        }
        else
        {
            rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
        }
        if (Input.GetButtonDown("Jump"))
        {
            rigidBody.velocity = new Vector2(rigidBody.velocity.x, jumpSpeed);
        }

        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround  );

```

# Answer
> 1 votes
You aren't checking if you are grounded before jumping, try something like this

```
void FixedUpdate()
{
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
    movement = Input.GetAxis("Horizontal");

    if (movement > 0f)
    {
        rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f)
    {
        rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
    }
    else
    {
        rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
    }

    if (Input.GetButtonDown("Jump") && isGrounded == true)
    {
        rigidBody.velocity = new Vector2(rigidBody.velocity.x, jumpSpeed);
    }
}

```

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


# Question
Title: Handling input from an ECS input system into actions in another system/actions on a entity?
Some background on my engine, each system stores a reference to an entity which has the relevant components for that system. For example movement system has only entities which possess position components, render system takes positions and textures etc.

I'm working on an Entity-Component-System Game Engine for a project and I've hit a bit of a brick-wall in regards to how I'm going to handle input for the entities. I'm unsure of how I would translate say a "W" press input into the movement of a single entity(the player)? I don't want to move the entity inside the input system. I'm unsure of how to go about taking input and getting it to result in a response.

This is my first question, if there's anyway I can improve it or if theres any additional information needed I'd be happy to oblige.

# Answer
This is just a short answer, since many details of your engine are unknown to me.

You need to remember that your `InputSystem`should not cause the movement directly, as it may be context dependent when you press 'W'. Are you in a menu and your button selection should move up, character should move forward and in a vehicle accelerate. Additionally, your `InputSystem` does not know about the surrounding. Is a wall infront of the player, is the player in the air etc.
What it should do is change the acceleration of the player or the object. It should write this in a component that both the `InputSystem`and the `MovementSystem`can access, e. G. the `MovementComponent`.

The `MovementSystem`in this case is more like a `PhysicsSystem`. It reads in the `MovementComponent` that the entity wants to move in the 'W'-direction. It checks, if that is possible. Is there a wall? Is the player on the ground (or ice, conveyer belt etc.) and then calculates the new position. This is then written in the `PositionComponent`.

Of course the context of your input can be checked in another sytem than your `InputSystem`, like the system that sort of is the game, some `GameruleSystem`. In this case the `InputSystem` writes the command in the `MovementComponent`, `GameruleSystem`reads this and reads the context, then writes in the `PhysicsComponent`what should happen. Moving forward, moving upwards, jumping. This is dependent on the game type.
> 1 votes

---
Tags: c#, xna-4.0, input, entity-component-system
---


# Question
Title: how to track point on object with rotation
I'm working on a top down shooter in C++ and need to have a fire point on the player and npc's so that when they rotate bullets come out of the fire point and not the actual position

here's what i mean(red is the fire point):

# Answer
You're looking for:

```
offset_x = cos(angle) * radius
offset_y = sin(angle) * radius

```

This is the offset of the red point relative to the center of the circle.

For `angle = 0` this results in `offset_x = radius, offset_y = 0`, and for `angle = pi/2` the result is `offset_x = 0, offset_y = radius`. This is merely a convention, and by swapping `sin` and `cos`, or negating one or both offsets, or negating angle, it's possible to invert the rotation direction and/or change what direction `angle = 0` represents.
> 1 votes

---
Tags: c++, mathematics
---


# Question
Title: How big can a background file in Unity be?
I want to start a new 2D top-down project in Unity and want to figure out how to organize my background (one big file or a lot of files joined together).

So how big can a background file get in Unity?

The target platform is Windows.

# Answer
Since it is for your actual world, you want to go by tiles. That means you have a sprite sheet and build your world of multiple of small pieces by it.

There are a lot of tutorial on how to build them out there, the documentation has a few examples as well (https://docs.unity3d.com/Manual/class-Tilemap.html) and for prototyping you can find a lot of free assets out there as well.

Usually a tile is 16x16, 32x32 or 64x64px per tile, bigger would be highly unusual and impractical.

A tile map sheet (multiple of your tiles), are packed together in one file and they can get as big as needed, though normally you don't want to have tiles in it that you dont actually use in your level.

In case you want to create a realistic street network as from your screen shot link, check out this good answer How to generate a city street network?

Since your city is static, you will get the best result if you handcraft it with segments. Compared to using one big image for all streets, it will make it easier to fit your buildings in or if you want to change later part of the streets. You can still use tiles for most of the straight and curves (which will speed up your building process a lot). For more complex curves you might want to take a look at splines.
> 1 votes

---
Tags: unity, file
---