# Question
Title: Responsive (dynamically changing) Grid Layout Group cell sizes in Unity3D UI
I am trying to get my hands on the (not that) new UI system by experimenting a bit.

I tried to do some Sudoku style layout. (cause lets start simple). Well, seems not that simple for me right now.

For the namings: the game field of Sudoko holds 9 (3x3) cells where each cell holds 9 (3x3) fields.

It is basically a Panel (game field) which has a Grid Layout Group with column count fixed to 3. Adding 9 child panels gives me the 3x3 cells. Now each cell gets another Grid Layout Group with column count fixed to 3. Adding another 9 panels (fields) to each cell panel results in the Sudoku style layout with 3x3 cells and each cell has 3x3 fields.

Now if the screen gets resized the cell sizes do not scale. After googling a bit I found (here or on Unity answers) the answer to a different setup to add a little script calculating the cell sizes dynamically. The content of UpdateCellSizes() is based on the other question.

I ended up with this little script:

```

[RequireComponent(typeof(RectTransform), typeof(GridLayoutGroup))]
public class UIFlexibleGridController : MonoBehaviour {

     private RectTransform rt;
     private GridLayoutGroup glg;
     private float lastWidth;
     private float lastHeight;
     private float cellAspectRatio;
     public bool scaleOnlyOnStartup = true;
     public bool keepAspectRatio = false;
     public bool keepSpacingZero = true;

     void Start () {
         rt = GetComponent();
         glg = GetComponent();
         if (rt == null || glg == null) {
             Debug.LogError("UIFlexibleGridController couldn't find a RectTransform or a GridLayoutGroup");
             return;
         }
         lastWidth = rt.rect.width;
         lastHeight = rt.rect.height;
         cellAspectRatio = rt.rect.width / rt.rect.height;
         if (glg.constraint == GridLayoutGroup.Constraint.FixedColumnCount || glg.constraint == GridLayoutGroup.Constraint.FixedRowCount) {
             UpdateCellSizes();
         } else {
             Debug.LogWarning("GridLayoutGroup contraints do not make this UIFlexibleGridController necessary. Consider removing it.");
             return;
         }
     }

     void Update () {
         if (scaleOnlyOnStartup) return;
         if (!HasSizedChanged()) return;
         lastWidth = rt.rect.width;
         lastHeight = rt.rect.height;
         UpdateCellSizes();
     }

     private bool HasSizedChanged() {
         return lastHeight != rt.rect.height || lastWidth != rt.rect.width;
     }

     private string GameObjectPathName(Transform t) {
         if (t.parent == null) {
             return t.name;
         } else {
             return GameObjectPathName(t.parent) + "/" + t.name;
         }
     }

     private void UpdateCellSizes() {
         float w = 0f;
         float h = 0f;
         float sx = 0f;
         float sy = 0f;
         w = (rt.rect.width / (float)glg.constraintCount);
         h = (rt.rect.height / (float)glg.constraintCount);
         if (w == 0 || h == 0) {
             Debug.LogError(string.Format("Invalid width ({0}) or height ({1}) at {2}", w, h, GameObjectPathName(this.transform)));
             return;
         }
         if (!keepSpacingZero) {
             w = (int) w;
             h = (int) h;
         }
         if (keepAspectRatio) {
             h = w * cellAspectRatio;
         }
         Vector2 newSize = glg.cellSize;
         newSize.x = w;
         newSize.y = h;
         glg.cellSize = newSize;
         if (!keepSpacingZero && glg.constraintCount != 1) {
             sx = (rt.rect.width - (w * glg.constraintCount)) / (float)(glg.constraintCount-1);
             sy = (rt.rect.height - (w * glg.constraintCount)) / (float)(glg.constraintCount-1);
         }
         Vector2 newSpacing = glg.spacing;
         newSpacing.x = sx;
         newSpacing.y = sy;
         glg.spacing = newSpacing;
     }
}

```

But when I ran it it states that width and height are zero for each cell holding the nine fields. I try to extract the scenario from my project where this message appears only on each second start and works on the other starts.

Does anyone know if that should work or it can't work by the UI system design?

# Answer
> 2 votes
Myself, I wouldn't use any scripts for this at all. Just the anchors built into the RectTransform.

Add 9 empty game object children to your canvas (or the container within your canvas that should contain the play field).

Set the horizontal anchors for them three at a time:

* for the left three: min X = 0, max X = 0.3333333
* for the middle three: min X = 0.3333333, max X = 0.66666666
* for the right three: min X = 0.6666666, max X = 1

Then set the vertical anchors again three at a time:

* for the bottom three: min Y = 0, max Y = 0.3333333
* for the middle three: min Y = 0.3333333, max Y = 0.66666666
* for the top three: min Y = 0.6666666, max Y = 1

Set their left, right, top, bottom position offsets to zero.

These anchors are positioned as fractions of the parent size, so this ensures we get 3 equal-width columns and equal-height rows filling the parent. (You can enforce a square aspect ratio on just the parent, and the benefit will apply to these without any additional scripting)

You can repeat this same trick for the number fields inside each sub-grid container. Again, since the anchors are relative to the parent, this will fractally nest a 3x3 grid inside the 3x3 grid.

# Answer
> 0 votes
This line..

```
(float)glg.constraintCount);

```

You're checking there is a constraint with:

```
if (glg.constraint ==  GridLayoutGroup.Constraint.FixedColumnCount ||
glg.constraint ==
GridLayoutGroup.Constraint.FixedRowCount) {

```

But `UpdateCellSizes();` is dividing by `glg.constraintCount`, which doesn't exist. Try checking which constraint is active and passing to `UpdateCellSizes(int constraint)`.

Thanks for the script, good stuffs, asides from that I think! :)

---
Tags: unity, gui
---


# Question
Title: How to keep track of (count) vertices processed so far in GL ES SL 2.0 vertex shader?
I'm trying to learn how to use GLSL ES 2.0.

In OpenGL ES 2.0, there is no `gl_VertexID` keyword to obtain the number of vertices processed so far. So I was wondering if there's a way to make my own counter. I know the vertex shader is executed "per vertex," so if I can increase a counter which persists between executions then that will meet my case.

Now I know I can't use a `uniform` because by definition they cannot be altered.

So I thought about using an `attribute`, assuming the value will persist between vertex shader executions, but when I write

```
attribute int a_vertexCounter;

```

in my vertex shader, the shader compiler says that an attribute cannot have the type `int`.

So I thought maybe if I make `a_vertexCounter` a `vec3` for example, and increment the first component of that vector instead... This works, except that when I try

```
gl_Position = u_MVPMatrix * u_canPos[int(a_vertexCounter.x)];

```

the compiler says

```
Error compiling shader: 0:23: S0027: Cannot modify an input variable

```

I also tried setting my `attribute` variable to be of type `ivec3` but the shader says that's not allowed either.

Maybe there's no way to do this without ES 3.0, where I could simply use `gl_VertexID` ?

# Answer
Given @DMGregory's comment I realised I couldn't just count the current vertex number inside the vertex shader, because GPU's run in parallel, and can have 100's or 1000's of cores working all at once so there could be any number of vertices being processed simultaneously.

To solve this I passed in an `attribute float a_vertexId`, where the corresponding VBO is:

```
vertexIdBuffer = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...}

```

Inside the vertex shader you can then do something like the following:

```
int spriteId;
int vertexId;

void main()
{
    spriteId = int(a_vertexId) / 6;
    vertexId = int(a_vertexId) - spriteId * 6;

    ...
}

```

I can then use the `spriteId` to access some `uniform` canonical vertices for a square (representing the sprite), without the need to upload 6 `vec3`/`vec4`'s (a square is two triangles, 3 + 3 = 6 vertices)

Note I could not pass in an `attribute int` which would be preferable because GL ES SL 2.0 does not support it, nor does it support the `%` operator, hence the elaborate modulo math in the `main()` function.
> 0 votes

---
Tags: glsl, opengl-es2
---


title: Edit existing editor inspector?

text:
# Question
Title: Edit existing editor inspector?
I want to write custom inspector for one of my scripts. All I want to change is input method for one of the strings to popup (so instead of writing whole string everytime I choose it from premade list of strings, like enums, the list is different for every dialogue). But the thing is it's VERY long inspector with a lot of variables and rewriting everything just for this one input doesn't click for me. Other problem is that this string is nested deep in the serializable object arrays, it look like so

I'm very happy with how default inspector shows all the fields, expect this one string I want to change. I tried playing around with SerializedProperty but no luck.

If it comes to available options I populate public string array with the names in the inspector (every dialogue has different list of participants) so the options should vary between different dialogues. What's the best way to set options?

Is there a way to do it without rewriting whole inpector on your own?

# Answer
> 2 votes
You can use a PropertyDrawer to control how a field is rendered, based on its type or attributes you've attached to it. This lets you target your changes to individual fields, wherever they might show up in a bigger nested set of types, without writing a custom inspector to handle drawing the whole hierarchy.

Here, we could define a \[CharacterName\] attribute that serves to mark fields we want to treat as character names. We'll also give it a static variable to keep track of which names should be options for the current batch of fields it's drawing.

```
using UnityEngine;

public class CharacterNameAttribute : PropertyAttribute
{
    public static string[] CurrentOptions;
}

```

Next, we define a custom property drawer (in an Editor folder) to draw fields marked with this attribute as a dropdown, using these options.

```
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(CharacterNameAttribute))]
public class CharacterNameDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {

        if (property.propertyType != SerializedPropertyType.String) {
            EditorGUI.LabelField(position,
                "[CharacterName] can only be used on strings.",
                (GUIStyle)"ErrorStyle");
            return;
        }

        var names = CharacterNameAttribute.CurrentOptions;

        if (names == null || names.Length == 0) {
            EditorGUI.LabelField(position,
                "No [CharacterName] options available.",
                (GUIStyle)"ErrorStyle");
            return;
        }

        int index = Mathf.Max(0, System.Array.IndexOf(names, property.stringValue));
        index = EditorGUI.Popup(position, property.displayName, index, names);

        property.stringValue = names[index];
    }
}

```

Lastly, we need to somehow populate the list of items that are valid for the current entry that we're drawing. Let's say you have a Dialogue script that looks something like this...

(Note that we've used our shiny new \[CharacterName\] attribute to mark our speaker name string)

```
using UnityEngine;

public class DialogueExample : MonoBehaviour
{
    [System.Serializable]
    public struct DialogueLine {
        [CharacterName]
        public string speaker;
        public Sprite expression;
        [TextArea(1, 4)]
        public string text;
    }

    [System.Serializable]
    public struct DialogueSection {
        public DialogueLine[] lines;
    }

    public string[] characterNames;

    public DialogueSection[] dialogues;
}

```

We can use a custom editor for this type (again in an Editor folder) to set the available character names, then let Unity handle drawing the standard inspector fields for all the contents of this instance:

```
using UnityEditor;

[CustomEditor(typeof(DialogueExample))]
public class DialogueExampleEditor : Editor
{
    public override void OnInspectorGUI() {

        // Set the names we're allowed to use in this dialogue.
        var dialogue = (DialogueExample)target;
        CharacterNameAttribute.CurrentOptions = dialogue.characterNames;

        // Ask Unity to draw all our inspector fields, handle saving/undo/etc...
        DrawDefaultInspector();

        // Clean up after ourselves, so we don't leak into the next use of [CharacterName]
        CharacterNameAttribute.CurrentOptions = null;
    }
}

```

All told, we get an inspector that looks like this:

---
Tags: unity, gui
---


# Question
Title: What advantage do OpenGL, SFML and SDL have over software rendering?
I started watching the Handmade Hero stream, where Casey Muratori creates a game engine without using frameworks or such. Yesterday I got to the part where he showed how an image is drawn onto the screen. As far as I understood it he just allocated some memory as big as the size of the screen he wants to draw to. And then he created a bitmap which he passed to the buffer memory he allocated and drew it to the screen using a os specific function.

This seems quite straight forward. I used GameMaker, changed to Love2D, worked a little bit with Sprite Kit but I was always wondering what was really happening beneath this sometimes confusing layers.

Given that, why even bother using graphics libraries (OpenGL, SFML, SDL, …) when all you have to do is simply allocate some buffer, pass a bitmap and draw it to the screen?

If you then want to draw distinct things to you screen you just write them to your bitmap which then gets passed into the buffer. I'm quite new to programming, but this seems quite simple to me. Please correct me if I'm wrong.

# Answer
> 41 votes
It's not just about speed of execution, but also about simplicity. Although the software rendering used in this example would be a lot slower than using hardware acceleration (i.e. a GPU), drawing a few bitmaps on screen is such a trivial task that you would not notice the performance drop.

However, low-level activity like triangle rasterisation, depth sort and the like are well-understood concepts that the GPU can handle implicitly with a few commands. Re-implementing those in software mode is essentially reinventing the wheel. This is fine if you want to gain a low-level understanding of how rendering is done, I myself wrote a 3D software renderer just to explore it a bit, but for most circumstances it's a waste of time when OpenGL can do it faster out of the box.

The example you've given sounds extremely basic, just drawing a single image on the screen, hence the implementation is easy. Once you start layering on complexity though, you'll find it becomes increasingly complicated to get everything rendering correctly. The stuff people had to do back in the Quake days of 3D software rendering was insane, though I appreciate you're not going THAT far (yet).

# Answer
> 25 votes
> My question is: why even bother using something like open gl, sfml, sdl when all you have to do is simply allocate some buffer, pass a bitmap and draw it to the screen?

Short: Because its fast (OpenGL, DirectX).

Long:

You may think you can do this all yourself. Draw pixels to a screen. You might write a small library to draw shapes, like quads or triangles. This will work, of course. There are a lot of libraries out there to do exactly this. Some of them even implement the OpenGL-spec (so they are like a software-side for opengl) which will do exactly what Casey Muratori does. They calculate everything on software-side, set the pixels on software-side and write the result to the screen.

However this is **slow**. The CPU which will eventually execute all these things wasn't made for this scenario. Thats what GPUs are for. What OpenGL does (unless it's a software-implementation of course) is take everything you tell it to do and push all data, all draw-calls, almost everything to the graphics-card and tell the **GPU** to do the work. The GPU is made specifically for this kind of job. Multiplying floating point numbers (Thats what you do *a lot* when drawing a 3D-scene) and executing shaders. And this in parallel. Just to get you a sense of how fast the GPU is, think about a simple scene in 3D in fullscreen with 1920x1080 pixels. These are, multiplied, 2,073,600 pixels to draw. For **every single** pixel, the GPU will run the fragment-shader *at least once*, most of the times more than once. Now, lets say we run at 60 frames per second. This means, the GPU runs the fragment-shader 2,073,600 * 60 = **124,416,000 times per second**. Do you think you can do something like this on your CPU? (Thats a pretty simplified explanation, there are a lot more things to consider like how many pixels you overdraw by nearer objects, how much MSAA you use and so on, however the *124,416,000 times per second* are probably the lowest you can get, and you'll easily have a lot more than 60fps with a simple scene)

Thats what OpenGL and Direct3D do, for what engines do see @Uri Popovs answer.

# Answer
> 11 votes
What he does is called **software rendering**, what OpenGL does is called **GPU rendering**

What's the difference between them? Speed and memory.

Rasterization (filling out triangles on screen) takes some time. If you do it on the CPU, you essentially take that time away from game logic, especially if it's not optimized well.

And doesn't matter, how small the image is, he needs to allocate certain amount of memory for it. GPUs have a video memory for this.

# Answer
> 8 votes
While the answers from others are more correct than any answer I could give, I want to point out the fundamental misunderstanding about how software development works that I think underlies your question. While it's always possible to do things "by yourself" without a framework, and there's often great educational benefit from doing so, the reality is that's not how modern software is created.

Somebody created the hardware and the machine languages that run on it. Somebody else creates higher level languages and compilers, drivers and operating systems, graphics libraries and on and on. We each build upon the work of our predecessors. That's not only "okay", it's a requirement.

You're drawing the line of what's "acceptable" or not at an arbitrary point in the toolchain. You could just as easily say "why use C++ when you could do the same thing in assembly?", or "why rely on the keyboard drivers when you could just as easily read the voltages coming off its wires and calculate it yourself?" There aren't enough hours in the day, or years in a lifetime for everyone to do everything themselves.

This doesn't apply just to software development, but to modern life in general. Have you ever heard of the guy that built a toaster himself, from scratch? http://www.thomasthwaites.com/the-toaster-project/. It took a really long time and a whole lot of effort. For a toaster. Try building *everything* that's required to actualize a video game out of the ether all on your own!

# Answer
> 3 votes
Engines do much more that just draw a picture to the screen. They handle lighting, shadows, input , collision detection. Even just the rendering part is way more complex than just pushing a buffer onto the screen. For 3d scenes especially you need to do a lot of calculations on far more complex data than a bitmap. Let me give you a analogy with a car: What you are describing as simple is the exhaust of the car. You just make a pipe with the right size and then you push the gas from one end to the other. However this is far from the only thing happening in the mechanism of the car.

# Answer
> 3 votes
The above answers are excellent, but none really goes over the most important reason as to why OpenGL and such are preferred. The main reason is to make use of **dedicated hardware** designed especially to work with things like rendering millions of pixels on a screen, the **GPU**.

With software rendering, using the CPU, the renderer will be looping, one by one, over all the pixels on a bitmap and issue orders to show each on the screen. So if you're rendering a 1000x1000 sized image, that 1,000,000 loops for your CPU to go over. They are designed with control in mind after all; lots of if conditions, jumping from one set of instructions to another and a strict direction of flow of control. However, a GPU is designed with knowledge that it'll be doing **a lot of similar looping over pixels on the screen.** A GPU would take a for loop with a 1000000 iterations and divide the work over its huge number of cores for each to work\** in parallel, and independent from one another\**. So unlike the CPU, every time a GPU comes across an if-else condition, it'll handle both code branches to two cores of itself AND THEN, at the very end, it'll look at what the condition evaluates to and discards the result of the unneeded branch (that's why lots of if-else conditions in GPU shaders are frowned upon; they're always responsible for a waste).

So yes, GPUs are built around **parallelism**. That makes working on pixels for them much faster compared to CPUs.

# Answer
> 0 votes
See Do I really need to use a graphics API?

Sure, you can ask for a buffer, set some bits in it and write it to the screen. That was essentially the only way to do graphics programming on the PC until the availability of graphics accelerators in the mid-90s from 3DFX. Even in Windows, DirectX was developed to give direct access to video memory.

But on non-PC hardware, dedicated games machines, there have always been techniques for speeding up graphics by offloading work from the processor. Even the Atari 2600 had "hardware sprites", partly because it didn't have enough RAM for a framebuffer.

Later (mid 80s) games consoles were optimised for platform games. Again, no framebuffer; instead the programmer could specify grids of tiles:

> The Genesis graphics hardware consists of 2 scrollable planes. Each plane is made up of tiles. Each tile is an 8x8 pixel square with 4 bits per pixel. Each pixel can thus have 16 colors. Each tile can use 1 of 4 color tables, so on screen you can get 64 colors at once, but only 16 in any specific tile. Tiles require 32 bytes. There is 64K of graphics memory. This would allow for 2048 unique tiles if memory were used for nothing else.

# Answer
> -2 votes
Modern CPUs are fast enough to do any 2d game in software, so for 2d graphics OpenGL/DirectX would offer no advantages, beside adding yet another dependence and a layer of complexity to your project, like i.e. setting a 3d projection matrix to draw a bunch of sprites and uploading data to GPU.

OpenGL would also force you to pack all your sprites inside 512x512 textures (an artifact of old consoles, like PSX, packing graphics into video memory pages), requiring you to write rather complex sprite packing code.

On the other hand, if you're doing 3d, rendering millions of triangles with complex shading, then GPU is unavoidable. Long ago there was simpler 2d only version of Direct3d, called DirectDraw, which GPU accelerated sprite drawing, but now Microsoft no longer supports it, possibly because CPUs are fast enough to do 2d without any acceleration, if you don't care about energy saving.

---
Tags: opengl, sdl, graphics-programming, sfml, software-rendering
---


# Question
Title: Which is a better way for moving 3d objects in OpenGL?
I'm learning OpenGL, and I'm a bit confused. I've just learned about projection and modelview matrices which can be used for moving things. This is the first way, which is convenient if I want to move everything. The other way is to calculate the new coordinates, and rebuffer the data. The second one seems a bit inefficient, because I have to rebuffer every single moved objects 60 times per frame. This has an advantage: I know the exact coordinates, and I can check collision, and other stuffs. If I move my character with manipulating the matrix, how do I know if I hit the wall or not? Should I make the same calculation as the shader, and get the 'real' position?

Which is more practical and efficient solution?

# Answer
> 2 votes
Mix of the both: move object for game logic, move the origin/camera (modify modelview matrix) for drawing.

As you said, recalculating the vertex buffer every frame is not going to be efficient, to put it lightly. Imagine a 3D RTS game with hundreds of units on the map. One way is to create vertex array for each unit. You'll need to prepare and send \[number of vertices\] x \[number of units\] values to GPU. Other way is to store the model in GPU RAM buffer, and tell the GPU to draw the contents of the buffer at specific coordinates/rotation (so you only send 4x4 matrix for each unit, regardless of its model's number of vertices).

First one should be fine for a small game, but if you scale it up, second is the way to go (especially if you start using shaders, uniforms, skeletal animation and other nice looking stuff).

---
Tags: opengl, matrix
---


title: AABB Collision Detection Confusion

text:
# Question
Title: AABB Collision Detection Confusion
I am trying to understand and implement AABB collision to learn simple 2D game physics. I'm following a tutorial and its method is a bit different to other websites. It uses the center of the object and its "half-size" to determine collision. This is its code:

```
public bool Overlaps(AABB other)
{
    if ( Mathf.Abs(center.x - other.center.x) > halfSize.x + other.halfSize.x ) return false;
    if ( Mathf.Abs(center.y - other.center.y) > halfSize.y + other.halfSize.y ) return false;
    return true;
}

```

And this is the seemingly more popular option:

```
if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.y + rect1.height > rect2.y) {
    // collision detected!
}

```

Which one is more efficient? And for the first option, would I define the center and half-size like this:

```
AABB = new AABB(new Vector2(Width / 2, Height / 2), new Vector2(Width / 2, Height / 2));

```

Center and half-size method source: https://gamedevelopment.tutsplus.com/tutorials/basic-2d-platformer-physics-part-1--cms-25799

Position and width/height source: https://developer.mozilla.org/en-US/docs/Games/Techniques/2D\_collision\_detection

# Answer
> 1 votes
Efficiency of both depends on how do you use AABBs. Center/half-size pros:

* Easy and fast retrieval of AABB's position
* Collision detection may be easier to understand
* Easier to understand calculation of AABB's border position

Center/half-size cons:

* Each collision detection will have more operations (subtraction/addition)
* Multiplication when retrieving AABB's size

Position/size pros:

* Collision detection has less operations (which doesn't necessarily mean it will be faster, probably not much unless you do millions of them during single frame)

Position/size cons:

* Heavier calculation of AABB's center (division by 2, so nothing scary though).

If you often need to update/retrieve AABB's center position, first option might be faster. If not, second one. Best way would be to implement both and profile the application, or just use the one is easier for you to understand and use.

# Answer
> 2 votes
There's actually a third option: storing AABBs as mins and maxs. That is, a Vector2 as the minimum x and minimum y, and another as the maximum x and maximum y values that the AABB occupies.

This allows for the representation of the AABB as a pure math concept and to not be dependent on how the screen or world space is set up. It's more flexible but can require more work for the user to calculate things like camera bounds and such.

In terms of collision it is exactly the same as your "more popular" option 2.

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


# Question
Title: Multiplayer oriented game engine object (C++)
for a personal project i started making a 2d game engine in C++ that uses sfml. The idea is having base "game object" classes from which a game will inherit.

Right now i have:

**Game\_engine** class which has a run method that takes care of the game loop (fixed timestep loop). The loop consists in:

* dequeuing SFML window events
* step
    + dequeue networking events
    + call step function for each Object instance
* draw
    + call draw update function for each Object instance
    + call draw function for each Object instance

**Resource\_manager** class which takes care about loading and holding resources and holding animations.

**Animation** and **Animated\_sprite**, where animation exists only once per animation, has a pointer to the texture and a list of the frames, while animated sprite is a child of sf::Sprite and there's one instance per each instance of a game object. Animated sprite points to its animation and frames are updated when Object's draw\_update is called.

**Logger** class, which queues up strings from the engine thread and uses a second thread to write the strings to file without the main thread suffering from write-to-disk delay

**Networking\_client** class, which queues up networking packets in a secondary thread, and returns the queue to the Game\_engine when it requires it for the networking part of the step.

**Object** class which is the basis on which an actual game's objects will be built. It has by default vertical and horizontal speed variables, and function to set them both as vertical and horizontal components or as speed and direction. It has both a sprite with its coordinates and its own coordinates. Sprite's coordinates are used by sfml to draw and will be updated with interpolation when draw\_update is called. The own coordinates are updated when the step function is called, which in an actual game will take care of checking collisions and stuff like that.

Up until that point i really did everything kinda by instinct, but now i don't know how to design networking managed objects. Ideally i would have a server which runs the game without the drawing part, only the fixed steps, and holds information about all connected clients. My issues are not about lag compensation right now, but about how to deal with these classes.

When i shoot on my client, i would tell the server i shot, the server creates a projectile and its creation is sent to all clients together with an id that identifies the networking object for future updates (changes in direction, destruction). However this adds a delay in the client when it's shooting its own projectile. If i create the projectile in the client first and tell the server about its creation, the client can cheat about its coordinates. If i create the projectile individually in both, once the client receives the information "create projectile" from the server it can't tell it's its own already existing projectile and not someones else's. Same issue when a client is changing it's controlled object's direction...

Can i get help designing that? I did something like that in javascript (without lag compensation it was a teleporting fest) but idk i'm finding it harder to design now, because i'm making it more generic, while my javascript project was directly with the actual game objects.

---

Before anyone tells something like "use an existing engine", part of my interest is actual making my own, after all it's an hobby and i'll likely never publish any game with that, i just enjoy writing such things and overcomplicating my life in a way that ends in never having any concrete result whatsoever.

# Answer
> 1 votes
AFAIK, many commercial MMORPGs use a kind of lock-step execution, with a modification of being able to "undo" changes. Each client executes its part of game's code, predicting NPCs, PCs and projectile movement, then consults server to see if the prediction of game state is correct and corresponds with actual movement. So on a laggy low bandwidth connection it is possible to see characters jerking back and forth, and hits not landing in time. True lock-step would be impossible when player count gets really high.

---
Tags: architecture, software-engineering, synchronization
---


# Question
Title: How do i add a rain effect to a top down design game in Java, using no external libraries?
I'm creating a top-down game for my A-level/college computer science project, and I'm trying to implement rain. The game needs to be usable on any platform, so the use of external libraries is out of the question. I currently have the GUI running off Java's Graphics package, and the game is rendered pixel-per-pixel from an array of pixels. The aim would be to have a rain effect that looks something like this http://d2436y6oj07al2.cloudfront.net/spff/previews/vbme0577.jpg. If this is possible, this would be really good. Currently I also have a particle class and particle spawners', which add the blood effect and effect of projectiles "exploding" when they hit a wall.

Is there a way to implement some rain from what I already have? I attempted to implement a Rain class, which spawns particles in a random place within bounds on an area of the screen, to make it look like it was coming from the perspective of the blocks.

Here is the rain i've tried to add (blue particles):

The issue is it moves and looks nothing like the image linked above. Also, here is my Rain class, which is added currently by the player just for testing, but the end game will be to have a "WeatherManager" class that handles all the weather changes and weather spawning (rain, snow etc).

```
package com.ritcat14.GotYourSix.entity.particle;

import java.util.Random;

import com.ritcat14.GotYourSix.Game;
import com.ritcat14.GotYourSix.entity.Entity;
import com.ritcat14.GotYourSix.graphics.Sprite;
import com.ritcat14.GotYourSix.level.Level;

public class Rain extends Entity {

    private int     time      = 0;    //time it is raining for
    private int     currTime  = 0;
    private boolean timeOfDay = false; //if it is night or day (false - night, true - day)
    private Level   level     = null;
    private Sprite  drop      = null;
    private int     amount    = 0;

    public Rain(int time, boolean timeOfDay, Level level) {
        init(level);
        this.time = time;
        this.timeOfDay = timeOfDay;
        this.level = level;
        if (timeOfDay) {
            drop = new Sprite(1, 0x87F7FF);
        } else {
            drop = new Sprite(1, 0xEFFBFF);
        }
    }

    public void update() {
        currTime++;
        if (currTime > time) {
            remove();
        } else {
            Random ran = new Random();
            if (time % (ran.nextInt(120) + 1) == 0) {
                int x = ran.nextInt(Game.getWindowWidth());
                int y = ran.nextInt(Game.getWindowHeight() / 4) + 100;
                level.add(new Particle(x, y, 1000, drop));
                amount++;
            }
        }
    }

    public void setDay(boolean dayTime) {
        this.timeOfDay = dayTime;
    }

}

```

Here is my particle class:

```
package com.ritcat14.GotYourSix.entity.particle;

import java.util.Random;

import com.ritcat14.GotYourSix.entity.Entity;
import com.ritcat14.GotYourSix.entity.mob.Player;
import com.ritcat14.GotYourSix.entity.projectile.Projectile;
import com.ritcat14.GotYourSix.graphics.Screen;
import com.ritcat14.GotYourSix.graphics.Sprite;

public class Particle extends Entity {

    private Sprite   sprite = null;

    private int      life = 0;
    private int      time = 0;

    protected double xx = 0, yy = 0, zz = 0;
    protected double xa = 0, ya = 0, za = 0;
    private Random   ran = new Random();

    public Particle(int x, int y, int life, Sprite sprite) {
        this.x = x;
        this.y = y;
        this.xx = x;
        this.yy = y;
        this.life = life + (random.nextInt(50) - 25);
        this.sprite = sprite;
        this.xa = random.nextGaussian();
        this.ya = random.nextGaussian();
        this.zz = random.nextFloat() + 2.0;
        int col = ran.nextInt(4);
        if (sprite != Sprite.particle_blood) {
            if (Projectile.weapon == Projectile.Weapon.FIREDCANNON || Projectile.weapon == Projectile.Weapon.FIREDARROW) {
                if (col == 0)
                   this.sprite = new Sprite(2, 0xff000000);
                if (col == 1)
                    this.sprite = new Sprite(2, 0xffF8A800);
                if (col == 2)
                    this.sprite = new Sprite(2, 0xffF8F8C8);
                if (col == 3)
                    this.sprite = new Sprite(2, 0xffF8A800);
            } else if (Projectile.weapon == Projectile.Weapon.FIREBALL || Projectile.weapon == Projectile.Weapon.FIREWALL) {
                if (col == 0)
                    this.sprite = new Sprite(2, 0xffF86800);
                if (col == 1)
                    this.sprite = new Sprite(2, 0xffF8A800);
                if (col == 2)
                    this.sprite = new Sprite(2, 0xffF8F8C8);
                if (col == 3)
                    this.sprite = new Sprite(2, 0xffF8D840);
            } else if (Projectile.weapon == Projectile.Weapon.ICEDCANNON || Projectile.weapon == Projectile.Weapon.ICEDARROW) {
                if (col == 0)
                    this.sprite = new Sprite(2, 0xff427AFF);
                if (col == 1)
                    this.sprite = new Sprite(2, 0xff607BFF);
                if (col == 2)
                    this.sprite = new Sprite(2, 0xff7C9BFF);
                if (col == 3)
                    this.sprite = new Sprite(2, 0xff000000);
            } else if (Projectile.weapon == Projectile.Weapon.ICEBALL || Projectile.weapon == Projectile.Weapon.ICEWALL) {
                if (col == 0)
                    this.sprite = new Sprite(2, 0xff427AFF);
                if (col == 1)
                    this.sprite = new Sprite(2, 0xff607BFF);
                if (col == 2)
                    this.sprite = new Sprite(2, 0xff7C9BFF);
                if (col == 3)
                    this.sprite = new Sprite(2, 0xffD3DEFF);
            }
        }
    }

    public void update() {
        time++;
        if (time >= Integer.MAX_VALUE - 100)
        time = 0; //Safety check
        if (time > life)
            remove();
        za -= 0.1;

        if (zz < 0) {
            zz = 0;
            za *= -0.55;
            xa *= 0.4;
            ya *= 0.4;
        }

        move(xx + xa, (yy + ya) + (zz + za));
    }

    private void move(double x, double y) {
        if (collision(x, y)) {
            this.xa *= -0.5;
            this.ya *= -0.5;
            this.za *= -0.5;
        }
        this.xx += xa;
        this.yy += ya;
        this.zz += za;
    }

    public boolean collision(double x, double y) {
        boolean solid = false;
        for (int c = 0; c < 4; c++) {
            double xt = (x - c % 2 * 16) / 16;
            double yt = (y - c / 2 * 16) / 16;
            int ix = (int)Math.ceil(xt);
            int iy = (int)Math.ceil(yt);
            if (c % 2 == 0)
                ix = (int)Math.floor(xt);
            if (c / 2 == 0)
                iy = (int)Math.floor(yt);
            if (level.getTile(ix, iy).solid())
                solid = true;
        }
        return solid;
    }

    public void render(Screen screen) {
        screen.renderSprite((int)xx - 1, (int)yy - (int)zz - 1, sprite, true);
    }

}

```

Any ideas as to how to improve and/or make it appear to "fall" to the ground? I managed this with standard particles, but I can't get my head round how "Rain" would appear to "fall" in a 2D world. Any ideas? Thanks

# Answer
I would say first, your problem is more one of deciding on an artistic style, and not as much about code. Like with a lot of things artistic, there is no right answers, but there are definitely ideas and approaches.

Second, your game is not 2D - it's 2.5D in a pseudo 3D way, just like isometric is 2D, but also 3D'ish. Your characters are not drawn from a top down view for example, which hugely changes the artistic approach.

**Focusing on Artistic Style**

You could just do animations of rain drop splashes on the ground, but that could look wrong. The player sees the drop hit the ground, but they don't see the drop fall. So based on that, I think you have to animate rain falling before you have it hit the ground.

You could have all drops "fall" from the top of the screen, but it might not quite look right. It does not match the pseudo 3D/isometric stye.

**Solutions**

Personally what I would do is manage this with two sprites for each raindrop: one sprite for a falling drop, and another sprite for a drop splash on the ground.

Falling rain drop sprites would be spawned randomly across the map at X/Y locations, and be assigned a starting altitude (pseudo Z coordinate). Then the sprite is animated with the following conditions...

* Sprite initial spawn coordinates should be the entire space of your game screen, plus additional space so that some drops can spawn off the top of the screen and eventually fall into view from the top
* Falling sprites are drawn with the Y axis of the screen treated as a pseudo Z axis
* The altitude controls how far down the screen the drop will fall before it hits the ground
* A drop sprite starts off invisible, and fades in fairly quickly as it falls so that they don't simply appear suddenly
* When a drop sprite reaches zero altitude, it is remove and replaced with a "splash" sprite

Splash sprites work as follows... * It is a simple, non looping animated sprite of a rain drop splash * They are spawned when a drop reaches zero altitude * If a drop falls off the screen, then no splash sprite is drawn

**Stylistic Control and Improvements**

This approach will give you a lot of control over the rain style both visually and programmatically, and you've got some interesting space here to do things.

If artistically it's not right, work on your sprites.

If you want heavier rain, increase the random chance of a drop being spawned, or decrease it if you want lighter rain.

Have raindrops hit objects and not the ground. So rain hits the branches of a tree (with no splash) and not the ground under. Or give the player an umbrella.

Acoustically, you can also do some great audio effects based on rain intensity. Technically you could trigger a little "splash" sound on each drop falling, so the sound of the rain fully matches what is drawn visually. This might be a problem with a lot of raindrops, but it definitely would work for light rain, or when a rainstorm is just starting.

Have clouds (sprites) drift across the screen, and have drops spawn only in clouds.
> 1 votes

# Answer
Try creating a 3-4 frame animation of a semi-transparent blue-white dot that moves downward a few pixels before expanding out to a 1-2 pixel radius circle. Then just create random instances of this animation all over the map. Should give the appearance of rain droplets. From there you can adjust it by maybe adding more frames or adjusting the shape when it hits the ground. Try adjusting the transparency of the rain droplet throughout the animation so it's more opaque at the start.
> 2 votes

---
Tags: java, 2d, graphics, algorithm, effect
---


# Question
Title: Creating animation by script with animation assets
I'm very new to Unity (not to C# and programming as well) but I managed to achieve some goals very fast. But some concepts I still don't get in their full aspects.

I'm developing a small multiplayer game called skeet. It's about clay pigeon shooting. I have a static 2D scene, with 3 assets: A gun, a bullet and a pigeon. These sprites I'm able to deploy on the scene by an event driven script and I'm able to react on collisions between objects.

I reached the point I have to animate the pigeon and the bullets. First I have to animate the pigeon moving from border to border in a random direction on a random height. Second if a player presses its key to shoot its bullet must be animated from the bottom of the screen straight upwards.

My current idea is to create some animations as assets and to assign them to the sprites I'm creating dynamically. But I don't know what I need in the Unity GUI and in the script.

I'm not looking for a ready to run solution but an ordered list of concepts and advices I have to take a look into.

**Edit:**

The bullets and pigeons are created dynamically and should be destroyed after the animation finished (by reaching any border of the screen or a collision). So I need to create an animation with assignable position parameters.

# Answer
1. Make sprite sheets for both your animation needs.Like flying animation for pigeon.
2. Next thing you need is to look into Instantiating Game Objects in Unity, refer Instantiate a GameObject.Its an easy to code randomize spawn position for pigeon using Random.range
3. There are tons of ways you can move your bullet and pigeon in the scene ,one of them being altering transform.position of the object.You can again randomize the direction using Random.range or random.value.

This pretty much covers everything you need to do for your project.Also refer Unity script manual time to time. Good Luck !
> 0 votes

# Answer
There is no need to do that when unity offers sprites and spline based animation for you to do your animation it would be a right approach for you to follow the already suggested way to animate rather than thinking of new methods to do stuffs you could probably do those things when you go higher level and ask these doubts to unity folks themselves.:D
> 0 votes

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


title: Marching Cubes Vertex Normals

text:
# Question
Title: Marching Cubes Vertex Normals
I understand how to generate geometry using marching cubes at an isosurface, but I haven't been able to find a clear explanation on how to calculate the vertex normals for a mesh produced using marching cubes.

Right now, for each triangle generated during the lookup phase, I can calculate a *face* (not vertex) normal simply by taking the cross product of two of the vectors in the triangle ie:

```
Triangle = [p1, p2, p3];
normal[face] = (p2 - p1).cross(p3 - p1).normalized();

```

But how do I compute the *vertex* normals at `p1` `p2` and `p3` to allow for smooth shading? The only way I can think of is to sample the density function to produce an estimate of its gradient -- but is there a faster way?

# Answer
> 4 votes
Essentially, the normal of the vertex would be the average of the adjacent faces' (triangles) normals.

In pseudocode:

```
for each face adjacent to vertex[n]
    sum = sum + face.normal
normal[n] = NORMALIZE(sum / COUNT(adjacent faces))

```

Repeat for each vertex.

# Answer
> 1 votes
Calculate normals at the grid vertices as following:

```
Grid[cx,cy,cz].Normal.X := (Grid[cx-1, cy, cz].Value-Grid[cx+1, cy, cz].Value)
Grid[cx,cy,cz].Normal.Y := (Grid[cx, cy-1, cz].Value-Grid[cx, cy+1, cz].Value)
Grid[cx,cy,cz].Normal.Z := (Grid[cx, cy, cz-1].Value-Grid[cx, cy, cz+1].Value)

NormalizeVector(Grid[cx,cy,cz].Normal);

```

then interpolate along the segment...

# Answer
> 0 votes
If you have indices, vertices and triangles you can do the following:

* Create a struct of vertexes\_ and put inside a Vector3 normal and an int faceCount
* Create a dynamic list of vertexes\_ and whenever you add a vertex to your mesh add also an empty element of vertexes\_
* In your Triangle class besides storing the vertices v1, v2, v3, store also their indices i1, i2, i3
* Now iterate through your triangles ti and add to the vertexes\_\[i1\].normal, vertexes\_\[i2\].normal, vertexes\_\[i3\].normal the face normal and increase the vertexes\_\[i1\].faceCount, vertexes\_\[i2\].faceCount, vertexes\_\[i3\].faceCount by 1
* Then iterate through your vertices vi and divide every vertexes\_\[vi\].normal by the vertexes\_\[vi\].faceCount

Hope this helps!

---
Tags: normals, mesh, marching-cubes
---


# Question
Title: Character doesnt move along with his rotation
Decided to change my character movement from transform.Translate to a rigidbody movement, the only problem is that my character is not moving to where he is facing, also it falls really slowly in the Y axis. Heres the code related to the movement:

```
    float moveHorizontal = Input.GetAxis("Horizontal") * rotSpeed;
    float moveVertical = Input.GetAxis("Vertical") * speed;

    rb.velocity = new Vector3(0, 0, moveVertical);
    transform.Rotate(0,moveHorizontal, 0);

```

# Answer
Velocities are specified in the world coordinate system. So `(0, 0, moveVertical)` means a velocity pointing along the world's Z axis, not the character's Z axis.

If you want to specify your velocity in local coordinates, all you have to do is convert them to world coordinates before you assign the velocity, something like this:

```
var localVelocity = new Vector3(0, 0, moveVertical);
var worldVelocity = transform.TransformVector(localVelocity);

// Preserve jumping/falling.
worldVelocity.y = rb.velocity.y;

rb.velocity = worldVelocity;

```

Though for a single axis you can take a shortcut:

```
worldVelocity = transform.forward * moveVertical
              + Vector3.up * rb.velocity.y;

```

One unrelated error here is that you're changing your position using the rigidbody's velocity, but changing your rotation using the transform. Combining physics- and non-physics movement can confuse the physics engine and cause bugs, and will disable interpolation which can make your movement look jerky. So, it's better to keep all rotation under the control of the rigidbody:

```
// transform.Rotate(0, moveHorizontal, 0);
var rotation = Quaternion.Euler(0, moveHorizontal, 0) * rb.rotation;
rb.MoveRotation(rotation);

```

You'll probably also want to scale your rotation by `deltaTime` to keep it smooth and consistent under varying framerates. (You don't need to do this with velocity since it's already a rate over time, integrated over the time step by the physics engine)
> 2 votes

---
Tags: unity, movement, rigidbody
---


# Question
Title: Errors when building game to any platform
As a newer Unity user, I've never had this problem before. I looked around on the internet and didn't find any help except to reimported all my assets which did not help.

I get these errors when building to any Platform:

> Assets/Scripts/MainMenuManager.cs(41,21): error CS0234: The type or namespace name `EditorApplication' does not exist in the namespace` UnityEditor'. Are you missing an assembly reference?
>
> Error building Player because scripts had compiler errors
>
> Build completed with a result of 'Failed' UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
>
> UnityEditor.BuildPlayerWindow+BuildMethodException: 2 errors at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (BuildPlayerOptions options) \[0x0021f\] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:187 at UnityEditor.BuildPlayerWindow.CallBuildMethods (Boolean askForBuildLocation, BuildOptions defaultBuildOptions) \[0x0007f\] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:94 UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
>
> NullReferenceException: Object reference not set to an instance of an object UnityEditorInternal.AnimationWindowControl.GetAnimationModeDriver () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:474) UnityEditorInternal.AnimationWindowControl.get\_previewing () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:340) UnityEditorInternal.AnimationWindowControl.get\_recording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:390) UnityEditorInternal.AnimationWindowControl.StopRecording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:421) UnityEditorInternal.AnimationWindowControl.StopPreview () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:361) UnityEditorInternal.AnimationWindowControl.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:105)
>
> NullReferenceException: Object reference not set to an instance of an object UnityEditorInternal.AnimationWindowControl.GetAnimationModeDriver () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:474) UnityEditorInternal.AnimationWindowControl.get\_previewing () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:340) UnityEditorInternal.AnimationWindowControl.get\_recording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:390) UnityEditorInternal.AnimationWindowControl.StopRecording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:421) UnityEditorInternal.AnimationWindowControl.StopPreview () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:361) UnityEditorInternal.AnimationWindowControl.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:105) UnityEditorInternal.AnimationWindowState.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowState.cs:315)
>
> NullReferenceException: Object reference not set to an instance of an object UnityEditorInternal.AnimationWindowControl.GetAnimationModeDriver () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:474) UnityEditorInternal.AnimationWindowControl.get\_previewing () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:340) UnityEditorInternal.AnimationWindowControl.get\_recording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:390) UnityEditorInternal.AnimationWindowControl.StopRecording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:421) UnityEditorInternal.AnimationWindowControl.StopPreview () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:361) UnityEditorInternal.AnimationWindowControl.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:105) UnityEditorInternal.AnimationWindowState.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowState.cs:315) UnityEditor.AnimEditor.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimEditor.cs:363) UnityEditor.AnimationWindow.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindow.cs:72)
>
> NullReferenceException: Object reference not set to an instance of an object UnityEditorInternal.AnimationWindowControl.GetAnimationModeDriver () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:474) UnityEditorInternal.AnimationWindowControl.get\_previewing () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:340) UnityEditorInternal.AnimationWindowControl.get\_recording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:390) UnityEditorInternal.AnimationWindowControl.StopRecording () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:421) UnityEditorInternal.AnimationWindowControl.StopPreview () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:361) UnityEditorInternal.AnimationWindowControl.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowControl.cs:105) UnityEditorInternal.AnimationWindowState.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimationWindowState.cs:315) UnityEditor.AnimEditor.OnDisable () (at C:/buildslave/unity/build/Editor/Mono/Animation/AnimationWindow/AnimEditor.cs:363)

I don't know what any of this means and I can't find any other information on it. I haven't upgraded Unity or anything like that.

# Answer
The main blocker here looks like:

> Assets/Scripts/MainMenuManager.cs(41,21): error CS0234: The type or namespace name EditorApplication' does not exist in the namespace UnityEditor'. Are you missing an assembly reference?

It states that you have a script (MainMenuManager.cs) attempting to call code (`EditorApplication`) from the namespace `UnityEditor`, which does not exist.

It does not exist for your *built game* because the UnityEditor library, which contains that namespace, is not included in built games.

A workaround is using preprocessor define checks if you must have edit-time and runtime code in the same script, e.g.:

For editor-only code:

```
#if UNITY_EDITOR
using UnityEngine;
#endif

```

For using different code in the editor to any other platform (build target):

```
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif

```

*(note that in the above examples, the syntax highlighter colours lines beginning with `#` as comments. They are in fact the pertinent parts of the examples)*

Unity has documentation on the support and use of these preprocessor defines for platform-dependant compilation. The preprocessor modifies the code sent to the compiler. When you build, `#if UNITY_EDITOR` is false and the compiler will never even see the code inside that block.

---

To explain why all may seem okay, Unity will share project files with Visual Studio which allow it to use the Visual Studio C# compiler for it's own functionality, e.g. error checking. To enable this functionality in VS for editor scripts, Unity includes a reference to the UnityEditor library for an 'editor' project to VS - making VS report that there are no errors because it's tools have a reference to the UnityEditor library whereas the Unity compiler that builds your game does not.
> 2 votes

---
Tags: unity, build-process
---


title: Fastest Software Gamma=2.2 for RGB?

text:
# Question
Title: Fastest Software Gamma=2.2 for RGB?
With gamma=2.0 you can use that Carmack's inverse sqrt hack or a lookup table. Yet all standard graphic formats mandate the use of gamma=2.2, and SVGA framebuffer also requires it. Unfortunately, for gamma=2.2 a linear lookup table doesn't fit into CPU cache (it is a whooping 192 kilobytes). So should one work with gamma=2.2 directly or convert it into gamma=2.0?

The question of course assumes that everything is done in software, because modern GPUs support gamma=2.2 in hardware. I want to avoid using OpenGL, because it is non-portable unstable API, and a total overkill for a simple 2d indie game.

# Answer
> 0 votes
I think I have found a solution to compress any large gamma magnitude back to 8-bits.

First one has to convert said magnitude to a custom floating point format, and then use it as an index into a small lookup table.

Loss of precission is not a huge problem, because values are mapped to 8-bit RGB components anyway.

Here is the code for a custom 16-bit float:

```
#define CFP_MANTISSA_BITS  11
#define CFP_MANTISSA_MASK  ((1<<CFP_MANTISSA_BITS)-1)
#define CFP_EXPONENT_BITS  (16-CFP_MANTISSA_BITS)
#define CFP_POINT (CFP_MANTISSA_BITS-1)
uint16_t int2cfp(uint32_t n) {
  int e = log2(n) - CFP_POINT; //log2 is basically x86 BSF's or ARM's CLZ
  if (e < 0) return n; //can be replaced by a table
  return (e<<CFP_MANTISSA_BITS) | (n>>e);
}

uint32_t cfp2int(uint16_t n) {
  return ((uint32_t)n&CFP_MANTISSA_MASK)<<(n>>CFP_MANTISSA_BITS);
}

```

That way the size of a lookup table can be made to match cache size perfectly.

Half-floats can also be used for that purpose, but they have a max value of (float)0xFFFF, so one must normalize them before lookup. Both ARM and x86 have fast float-to-half float conversion instructions, which can be accessed from C/C++ using the following code:

```
#include <smmintrin.h>
__attribute__ ((__target__("f16c"))) uint16_t x86_f2h(float value)
{
  return _mm_cvtsi128_si32(_mm_cvtps_ph(_mm_set_ss(value), _MM_FROUND_CUR_DIRECTION));
}

```

---
Tags: graphics-programming, srgb
---


# Question
Title: How would I run a VR game that depends on external hardware?
I have a VR game idea which is being built on Unity with external hardware (Arduino, Gyroscopes, etc).

I have thought of ways to connect the Arduino to Unity but what I am now struggling with is thinking of a way to play the VR game. I've created VR games before for iOS where the user can use Google Cardboard, however, I feel like that would not be possible due to the external hardware.

Are there any other ways that you know are possible?

# Answer
This is actually a very common scenario, it may be less recognizable because you have custom hardware. The more commonly recognized scenario is a wireless input controller, like an XBox controller. An XBox controller sends and receives data. It tells an application that a button is being pressed, and an application tells it to vibrate.

Your custom hardware talks to your application via some defined data standard, like serialized JSON data. This enables them to send data back and forth, respond to commands, provide input, etc.

The medium for that data is dependent on your platform, it could be WiFi or Bluetooth or USB. The medium you use will dictate the connection process and how transparent that process is to the user.

Since this is your application, with your custom hardware, the decisions about what will work *best* are up to you as the developer. Just know that you'll need to decide on a data format and a medium (or you can support multiple mediums if you're feeling ambitious).

As an example. I worked on a project for the HoloLens that communicated with a Raspberry Pi. The Pi application hosted a web server, which exposed various endpoints for collecting data and receiving commands. It also broadcast itself as a host on the WiFi network it was connected to. The HoloLens would then connect to the same WiFi network, and the HoloLens application would listen for host broadcasts, and connect. Then the HoloLens app would show a Mixed Reality interface to read data from and control various bits of hardware that were attached to the Pi. The HoloLens application also had an alignment phase, allowing you to align to the Pi. This enabled the holograms to be appropriately placed over the components they were getting data from or sending commands to.
> 1 votes

---
Tags: unity, virtual-reality, google-cardboard
---


# Question
Title: What is the difference between AR, VR and MR?
Please explain clearly and in short about the differences and boundaries between AR, VR & MR.

# Answer
**Virtual Reality**: where the user is completely ‘immersed’ in a virtual environment. Nothing of the outside world is visible.

**Augmented Reality**: information is added to the real world by overlaying graphics over the real world the user sees.

**Mixed Reality**: a combination of the above where the user sees the real world, but virtual objects are placed in this world (often anchored) as if these were real. These virtual objects have the illusion of being part of the real world and can be interacted with. At a higher level, a virtual lightswitch could for example control real lights: therefore ‘mixed’ reality.
> 6 votes

# Answer
Virtual Reality and Augmented Reality actually exist on a spectrum, so the definition between them can get blurry. The distinction right now is mostly driven by hardware.

The easiest factor to determine the difference today is **immersion**. How much of the user's experience is virtual content? At one end of the spectrum is an entirely virtual world. At the other end is the physical world.

Microsoft's name for this spectrum is "Mixed Reality".

Where physical space is on one end, containing AR experiences. The other end is virtual space, where VR experiences happen. This is why Microsoft calls their VR headsets "Mixed Reality" headsets, with a further classification of "Immersive devices".

Others will define the gap between AR and VR as MR, and the entire spectrum as XR (either as Extended Reality or where X is a variable replacement for A,V,M):

There's another spectrum to consider as well, **spatial understanding**. This spectrum adds another dimension to the immersion spectrum. It goes from understanding nothing about the physical environment, like Google Glass or Vive to understanding a lot about the environment, like the HoloLens or Magic Leap.

At the moment, spatial understanding is less important for VR devices, other than for automatically setting boundaries, so the user doesn't walk into a wall or other physical obstacle when in VR. It's much more important for AR devices like HoloLens or Magic Leap, to know how virtual objects should be occluded or where flat surfaces are for dynamic content.

At some point in the future, there will be a device that can span this entire spectrum. But right now we're hardware limited to multiple devices to cover just tiny parts of the entire spectrum.
> 5 votes

# Answer
According to Peter Patterson (XR Architect / Developer), Unity officially stands by the Consumer Technology Association definition of the terms which read as follows.

**Virtual Reality** creates a digital environment that replaces the users real-world environment.

**Augmented Reality** overlays digitally created content into the users real-world environment.

**Mixed Reality** is an experience that seamlessly blends the users real-world environment and digitally created content where both environments can coexist and interact with each other. For instances, Jaron Lanier defines Pokémon GO as the heart of mixed reality.

---

According to Milgram et al.

**Virtual Reality:** artificial simulations, usually recreation of a real-life environment, that enhance an imagery reality or situation.

**Augmented Reality:** a form of virtual reality where the participant's head-mounted display is transparent, allowing a clear view of the real world.

**Mixed Reality:** when real world and virtual world objects are presented together within a single display, that is, anywhere between the extrema of the RV continuum.

---

According to Kassahun et al.

**Virtual Reality:** aims at enhancing our presence and interaction with a computer-generated environment without a means to interact with or see the real world.

**Augmented Reality:** aims at enhancing our perception and understanding of the real world by superimposing virtual information on our view of the real world.

**Mixed Reality:** aims at blending real and virtual environments.
> 4 votes

---
Tags: terminology, virtual-reality, augmented-reality
---


# Question
Title: Changing the 3D model of the Unity ARkit face tracking demo
I was able to get the Unity ARkit face tracking demo working with an iPhone X to animate a face model in realtime:

I then tried to get it to work with my own 3D model, and imported the FBX file with the same blendshapes (though each blendshape has a different name from the original sloth model). By using the hierarchy, ARFaceAnchorManager, and changing the Anchor Prefab I was able to select the model to use:

The problem is:

* the rendered model is flipped along the z axis (it faces away from the camera, as shown below). I've tried to apply a 180 degree rotation to the model in Unity's transform window, but it doesn't seem to do anything.
* I'm unsure how to map the blendshapes coming from the iPhone app to the blendshapes in the FBX model - where is that done? I couldn't find code that references these blendshapes.

# Answer
It looks like the code that manipulates the blend shapes is here, in the aptly-named `BlendshapeDriver` class:

```
SkinnedMeshRenderer skinnedMeshRenderer;
Dictionary<string, float> currentBlendShapes;

// ...

void FaceUpdated (ARFaceAnchor anchorData)
{
    currentBlendShapes = anchorData.blendShapes;
}

void Update () {

    if (currentBlendShapes != null) {
        foreach(KeyValuePair<string, float> kvp in currentBlendShapes)
        {
            int blendShapeIndex = skinnedMeshRenderer.sharedMesh.GetBlendShapeIndex ("blendShape2." + kvp.Key);
            if (blendShapeIndex >= 0 ) {
                skinnedMeshRenderer.SetBlendShapeWeight (blendShapeIndex, kvp.Value * 100.0f);
            }
        }
    }
}

```

You can find the list of blend shape names that will come in as `currentBlendShapes`' `kvp.Key` field here in Apple's documentation.

With this in hand, we can prepare our own remapping table like so...

```
[System.Serializable]
public struct Rename {
    [HideInInspector]
    public string originalName;
    public string mappedName;
    public Rename(string originalName) {
        this.originalName = originalName;
        this.mappedName = "";
    }
}

public Rename[] nameRemapping = new Rename[] {
    new Rename("eyeBlinkLeft"),
    new Rename("eyeLookDownLeft"),
    new Rename("eyeLookInLeft"),
    new Rename("eyeLookOutLeft"),
    new Rename("eyeLookUpLeft")
    // ... (Completing this table is left as an exercise for the reader)
};

```

This gives you a list of strings in the inspector that you can use to specify what the corresponding blendshape names are in your model, like this:

To save some searching, we can boil this down to a fast index lookup at runtime:

```
Dictionary<string, int> indexLookup;

void Start() {

    // Contents of existing Start method goes here.

    indexLookup = new Dictionary<string, int>(nameRemapping.Length);

    foreach(var map in nameRemapping) {
        int index = skinnedMeshRenderer.sharedMesh.GetBlendShapeIndex(remapping.mappedName);
        indexLookup.Add(remapping.originalName, index);
    }
}

```

Now we can replace this line inside Update:

```
int blendShapeIndex = skinnedMeshRenderer.sharedMesh.GetBlendShapeIndex ("blendShape2." + kvp.Key);

```

With this line:

```
int blendShapeIndex = indexLookup[kvp.Key];

```

As a bonus, by avoiding string concatenation inside our update loop, we've slightly reduced the garbage allocation and improved the efficiency. :)

---

As for why the head appears facing away, and why rotating it had no effect, I'm not sure what to tell you. The code looks like it's only rotating/repositioning the camera. Two thoughts:

1. Is it possible you applied your `y = 180` rotation to the prefab in your assets folder, instead of the instance in your scene? Prefab orientation is often ignored/overwritten when spawning a scene instance. The symptom of this would be that the 180 you set changes to 0 when you select the scene instance.
2. Is it possible your SkinnedMeshRenderer has an animation playing a key that's telling it to face forward, overriding the rotation you set? The symptom of this would be that even if you rotate the object at runtime, it resists and resets itself.

If so, you can either remove the animation, or put the head inside an empty parent object then rotate the parent.

Or the most robust solution might be to open the head in your 3D modelling software and spin it around there, then re-export.
> 1 votes

---
Tags: unity, animation, 3d-meshes, augmented-reality
---


# Question
Title: Pause Tiled animation during game in LibGDX
I’m using Tiled with LibGDX and I have some animated tiles. When the game is paused I would like their animation to be paused as well. Is this possible?

The map is drawn with `mapRenderer.render()` and if I'm not mistake, this is the class responsible for getting the corresponding animation. There doesn't seem to be a way to freeze time. Any help appreciated, I've been searching for a couple of hours and cannot find anything.

# Answer
> 1 votes
It is not supported, but you can implement it. If you use an OrthogonalTiledMapRenderer than extend it and override the beginRender method (it updates animation time) (similar you can do for other TiledMapRenderer-s). Magic of open source is that you can inspect the code and find a way.

```
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;

public class OrthogonalTiledMapRendererStopStartAnimated extends OrthogonalTiledMapRenderer {
  private boolean animate=true;
  public OrthogonalTiledMapRendererStopStartAnimated(TiledMap map) {
    super(map);
  }

  public OrthogonalTiledMapRendererStopStartAnimated(TiledMap map, Batch batch) {
    super(map, batch);
  }

  public OrthogonalTiledMapRendererStopStartAnimated(TiledMap map, float unitScale) {
    super(map, unitScale);
  }

  public OrthogonalTiledMapRendererStopStartAnimated(TiledMap map, float unitScale, Batch batch) {
    super(map, unitScale, batch);
  }

  @Override
  protected void beginRender () {
    if (animate)
      AnimatedTiledMapTile.updateAnimationBaseTime();
    batch.begin();
  }

  public void setAnimate(boolean animate) {
    this.animate = animate;
  }

}

```

And to use it:

```
mapRenderer = new OrthogonalTiledMapRendererStopStartAnimated(tiledMap, UNIT_SCALE);
//...
mapRenderer.setAnimate(false); //TODO when you need

```

---
Tags: libgdx, animation, tiled
---


# Question
Title: Instead of using yield wait for seconds can I use a UI button for async?
the code below is the code I use to load my game scene ater the intro animation plays. The way it works is that it preloads the game scene because it is big enough it takes time to load and activates it after 15 seconds.

I want to use this code in a similar manner for my main menu, but instead of preloading and waiting for seconds I want it to preload and wait for UI button.

```
public class IntroToForest : MonoBehaviour
{
    public float WaitToLoad = 14.0f;

    void Start()
    {
        StartCoroutine(LoadScene(WaitToLoad));
    }

    IEnumerator LoadScene(float WaitToLoad)
    {
        yield return null;
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync("Forest Map");
        asyncOperation.allowSceneActivation = false;

        while (!asyncOperation.isDone)
        {
            if (asyncOperation.progress >= 0.9f)
            {
                yield return new WaitForSeconds(WaitToLoad);
                asyncOperation.allowSceneActivation = true;
            }
            yield return null;
        }
    }
}

```

Side note: I incorporated DmGregory's answer into my menu controller script and got this:

```
public class MenuController : MonoBehaviour
{
    public string SceneName;

    AsyncOperation preload;

    void Start()
    {
        preload = SceneManager.LoadSceneAsync(SceneName);
        preload.allowSceneActivation = false;
    }
    public void Go_to_game()
    {
        if (preload.progress < 0.9f)
        {
            if (PlayerPrefs.HasKey("HasSeenIntro"))
            {
            preload.allowSceneActivation = true;
            }
            else
            {
                PlayerPrefs.SetInt("HasSeenIntro", 1);
                SceneManager.LoadScene("Intro");
            }
        }
    }
}

```

The problem is that the UI button will not work.

# Answer
Rather than running this as a coroutine, ticking every frame waiting to see if the button is pressed, I'd just store the AsyncOperation and let the button give it a kick when the player finally presses it.

```
public class ScenePreloader : MonoBehaviour {

    public string sceneName;

    AsyncOperation preload;

    void Start() {
        preload = SceneManager.LoadSceneAsync(sceneName);
        preload.allowSceneActivation = false;
    }

    // Call this from your UI button.
    public void BeginTransition() {
        preload.allowSceneActivation = true;

        if(preload.progress < 0.9f) {
            // Here, you might want to display a loading spinner,
            // so you have coverage if the user is very fast / load is slow.
        }
    }
}

```
> 2 votes

# Answer
Just use a boolean flag.

```
public class IntroToForest : MonoBehaviour
{
    public bool buttonPressed = false;

    void Start()
    {
        StartCoroutine(LoadScene("Forest Map"));
    }

    IEnumerator LoadScene(string scene)
    {
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(scene);
        asyncOperation.allowSceneActivation = false;

        while (!asyncOperation.isDone)
        {
            if (asyncOperation.progress >= 0.9f)
            {
                if(buttonPressed)
                    asyncOperation.allowSceneActivation = true;
            }
            yield return null;
        }
    }
}

```

Configure your button in the Inspector to set `buttonPressed` to true when pressed.
> 1 votes

# Answer
You can use `WaitWhile` to define a condition for the coroutine's yield. Something like this could work, with a button configured to update the value of `buttonPressed` accordingly.

```
public class IntroToForest : MonoBehaviour
{
    public bool buttonPressed;

    void Start()
    {
        StartCoroutine(LoadScene());
    }

    IEnumerator LoadScene()
    {
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync("Forest Map");
        asyncOperation.allowSceneActivation = false;

        while(!asyncOperation.isDone)
        {
            yield return new WaitWhile(() => !buttonPressed);
            if (asyncOperation.progress >= 0.9f)
            {
                asyncOperation.allowSceneActivation = true;
            }
        }
    }
}

```
> 1 votes

---
Tags: unity, c#, scene, async
---


# Question
Title: How to launch Libgdx cross-platform (Android, HTML, Desktop) multiplayer client with socket?
So i'm struggling with making my cross-platform client side to work, specifically on HTML part. I have java server that is responsible for all the controls and events, and I control it via netty-socketio. Client is Libgdx, and desktop version works flawlessly when using `io.socket.client.IO` class and `Gson` for json serialization. The implementation of game is clunky, but everything works and multiple clients can join, move and play.

Everything went south when i tried to launch html client. Nothing seems to be working and i have ran out of ideas of what to do. This is the errors i get

```
[ERROR] Line 4: The import org.json cannot be resolved
[ERROR] Line 5: The import org.json cannot be resolved
[ERROR] Line 11: JSONObject cannot be resolved to a type
[ERROR] Line 12: JSONException cannot be resolved to a type

```

together with

```
[ERROR] Line 15: No source code is available for type io.socket.client.Socket; did you forget to inherit a required module?
[ERROR] Line 17: No source code is available for type com.google.gson.Gson; did you forget to inherit a required module?
[ERROR] Line 20: No source code is available for type com.google.gson.GsonBuilder; did you forget to inherit a required module?
[ERROR] Line 45: No source code is available for type io.socket.client.IO; did you forget to inherit a required module?
[ERROR] Line 47: No source code is available for type java.net.URISyntaxException; did you forget to inherit a required module?

```

Quick googling says, that i cannot use `io.socket.client` and `gson` in `GWT`. So i'm here, trying to find some guidance, because everything I run into seems to be old and outdated. I hope someone can help me:

1. Is it possible to run single libgdx code for all platforms and communicate with server via socket (or anything at this point)
2. What libraries/repositories should I use to achieve this.
3. How exactly do i configure my html part to work correctly (I failed to find a single decent tutorial when using libgdx socket with html)

# Answer
> 1 votes
For web support (support cross platforms) you need to use libraries that do not use Java features such as reflection (Gson problem). If possible use libraries implemented in libgdx. In your case, use Reading and Writing JSON.

There is always some piece of platform-specific code. For this, write a Java interface class and implement it for every specific platform (also test it ;)). Pass this object through your game constructor in your core game.

For more, see Interfacing with Platform-Specific Code.

---
Tags: java, libgdx, websocket
---


# Question
Title: JNI Error when Wrapping Jar with JOGL using Launch4j
I have been trying to wrap my fat JAR file into an EXE using Launch4j, but I have been running into problems when I try to execute the EXE. Here is the error log I get from Launch4j:

```
Executing: E:\Downloads\CasualCaving.exe
JNILibLoaderBase: Caught IllegalArgumentException: No Jar name in <jar:file:/E:/Downloads/CasualCaving.exe!/jogamp/common/Debug.class>
Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: E:\Downloads\natives\windows-amd64\\gluegen-rt.dll
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.load0(Unknown Source)
    at java.lang.System.load(Unknown Source)
    at com.jogamp.common.jvm.JNILibLoaderBase.loadLibraryInternal(JNILibLoaderBase.java:624)
    at com.jogamp.common.jvm.JNILibLoaderBase.access$000(JNILibLoaderBase.java:63)
    at com.jogamp.common.jvm.JNILibLoaderBase$DefaultAction.loadLibrary(JNILibLoaderBase.java:106)
    at com.jogamp.common.jvm.JNILibLoaderBase.loadLibrary(JNILibLoaderBase.java:487)
    at com.jogamp.common.os.DynamicLibraryBundle$GlueJNILibLoader.loadLibrary(DynamicLibraryBundle.java:421)
    at com.jogamp.common.os.Platform$1.run(Platform.java:317)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.jogamp.common.os.Platform.<clinit>(Platform.java:287)
    at com.jogamp.opengl.GLProfile.<clinit>(GLProfile.java:147)
    at org.graphics.Render.<init>(Render.java:20)
    at org.engine.Main.main(Main.java:18)

```

I am using JOGL 2.3.2 imported through Maven, with the assembly plugin to compile it to a fat JAR. Here is a picture of my library configuration:

I am not sure what is wrong, as the JAR file works fine.

# Answer
I figured out that you need to include all native DLLs need for each platform. Just go to the library location and extract the natives from the jar file for the desired platform.
> 0 votes

---
Tags: opengl, java, jogl
---


title: What is a raycast?

text:
# Question
Title: What is a raycast?
I use this script to build buildings on my terrain, and it works with the collider somehow. But I don't understand what it is that the raycast does to find the right place to put my building.

```
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
    farmhide.transform.position = hitInfo.point;

    farmhide.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}

```

What is it that this code is doing?

# Answer
> 4 votes
A raycast is like shining a laser pointer in your scene, to see what the laser hits.

It takes a starting point and a direction as input (together, they make a "ray").

The physics engine takes this point and sweeps it along that direction. As it goes, it searches through all the physics colliders in your scene to check whether the point hits any of them during its travel.

(This is a simplification - in reality the engine has lots of clever acceleration structures and math so it can do this efficiently without looking at every collider or checking every point along the line one by one)

If it finds a collider that's in the path of the travelling point, it returns "true," meaning "yes, I found a hit." If you've provided an `out RaycastHit` parameter, it will store information about the first hit - the closest object along the ray.

From that `RaycastHit`, you can learn a lot about the intersection:

* `hitInfo.collider` will give you the `Collider` component that the ray hit. You can use this to get the hit object's `GameObject` and check its tag with `hitInfo.collider.gameObject.CompareTag("someTag")`, for example.
* `hitInfo.point` will tell you the position in world space where the ray hit the surface of the collider.
* `hitInfo.normal` will tell you the direction that the surface of the collider is facing at the point you hit. Your script uses this to orient the buildings to point directly out from the ground, instead of diagonal to the surface.
* `hitInfo.rigidbody` will give you the physics `Rigidbody` that owns the collider you hit, if it was a dynamic or kinematic object.
* etc.

If you don't want to search every collider in your scene, one of the best ways to control the raycast is to use Physics Layers.

You can expose a `public LayerMask raycastLayers;` variable in your script, so you can choose in the Inspector which physics layers you're interested in.

Then you can modify your raycast like so:

```
bool hitSomething = Physics.Raycast(
                     ray,                           // Point + direction to sweep
                     out hitInfo,                   // Destination for hit information
                     float.positiveInfinity,        // Change this to limit the ray length
                     raycastLayers,                 // Only hit colliders on these layers
                     QueryTriggerInteraction.Ignore // Ignore trigger colliders
                   );

if (hitSomething) {...

```

This is more efficient than checking for specific tags, because it lets you filter out false positives at the source.

---
Tags: unity, c#, raycasting, collider
---


# Question
Title: Can I use different Tile/Sprite Sizes on the same Tilemap?
My partner and I are creating a 2D RPG with D&D elements with Unity.

I am very new to Unity and making games in general, apart from 2 games which I created with Java and the rougelike tutorial which I did with Unity. For this university project we have 4 months and my partner has the job creating tiles, sprites, sound and music. I will program the game.

My question is:

Can we create 32x32 tiles and 64x64 sprites in the same tilemap or does everything need to be the same size?

If we can combine them, will a 64x64 sprite on a 32x32 tilemap take 4 tiles, or can we scale it down to one tile?

# Answer
> 0 votes
Yes, you can have both 64x64 tiles and 32x32 tiles. If you want both of them to take only one square, you will have to adjust the **pixels per unit.** If you don't know what that is, please comment and I'll help you.

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


title: Top-down 2D push angle velocity

text:
# Question
Title: Top-down 2D push angle velocity
I'm trying to determine the angle NPCs are pushed in when the PLAYER collides with them, like how 'Retro City Rampage' and 'Shakedown Hawaii' do when you bump in pedestrians.

Here the PLAYER (green) is coming in at an angle of -45, what's the math or formula I need to be looking at to decide the new angle each NPC (red) should adopt?

# Answer
> 1 votes
The two options are:

1.) NPCs run away from the player. With this one you just need to take the vector going from the player to the NPC, normalize it and set the NPCs velocity to this vector

2.) NPCs run perpendicular to the player's direction. To achieve this, you need to take the direction of the player and rotate it 90 degrees. Since there are two solutions to this (rotate it clockwise or counterclockwise) you need to decide which one to use (it can be random). For any vector \\$\vec v(x,y)\\$ the two vectors, that are perpendicular to it are \\$\vec v'(-y, x)\\$ and \\$\vec v''(y, -x)\\$

---
Tags: 2d, collision-detection, angles
---


title: Player going out of boundaries

text:
# Question
Title: Player going out of boundaries
So, I been following up the Space shooter tutorial on Unity, I had an issue where the project was acting up with an alpha version, so I was able to get a version that worked on a old release and applied all the new things I developed

But suddenly, my ship is acting up when getting closer to the boundary of its movement

This is the player movement code

```
public class playerMovement : MonoBehaviour
{
public float speed = 0.0f;
public float tilt;
public Boundary boundary;

void FixedUpdate ()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    var movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    var rigidBody = GetComponent<Rigidbody>();
    rigidBody.velocity = movement * speed;

    rigidBody.position = new Vector3
        (
            Mathf.Clamp(rigidBody.position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp(rigidBody.position.z, boundary.zMin, boundary.zMax)
        );

    rigidBody.rotation = Quaternion.Euler(0.0f, 0.0f, rigidBody.velocity.x * -tilt);
}

}

[System.Serializable]
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

```

And this is the player boundary properties

It used to work previously moving forward to the alpha, now I'm working on 2019.2.0f1, but since working on the alpha this is the behaviour I'm having

As you can see, getting closer to the player boundary, takes the player out of the play area, and I can't determine why this might be happening.

I already tried removing the Math.Clamp, as I though there migth be bug with the function in this version, but even without it, the problem is present.

# Answer
So, in the end, the culprit was a box collider I use to do memory management, taking out my player when it gets near to it

The killBox is a box collider with which I deactivate objects that reach to it in order to maintain a certain ammount of memory dedicated to bullets and hazards

So, making this object bigger, to better envolve my play area, well, solved my issue. I tried make it fit more properly the play area, and given I worked on something else, never though this might had caused an issue here, so once again, I made it bigger and my problem was solved
> 0 votes

# Answer
Let's step through this, assuming your boundary is at 10, your speed is 50, and your fixed timestep is the default 0.02 s. You're holding the stick to the right:

1. You're at x = 9 when FixedUpdate runs
2. You clamp the position. It's less than 10 so nothing changes.
3. The physics step runs. It moves the object 50 * 0.02 = 1 unit to the right. Now it's at x = 10.
4. The frame is rendered with x = 10. So far so good.
5. You're still at x = 10 when the next FixedUpdate runs.
6. You clamp the position. It's exactly at the boundary so nothing changes.
7. The physics step runs. It moves the object 50 * 0.02 = 1 unit to the right. Now it's at x = 11. Remember, your clamping happened *before* the physics step, so we don't get a chance to fix this until *next* FixedUpdate.
8. The frame is rendered with x = 11, out of bounds.
9. You're at x = 11 when the next FixedUpdate runs.
10. You clamp the position, snapping to x = 10.
11. The physics step runs. It moves the object 50 * 0.02 = 1 unit to the right. Now it's at x = 11 again.
12. We'll stay at x = 11 in every subsequent rendered frame until we back off the input.

So, if you want your physics integration to respect your boundaries, make them visible to the physics engine: add a collider to represent the boundary (you can have it absorb all bounce energy so you don't ricochet off of it, and use layers to ensure it doesn't interact with other scene content), or use a joint constraint to limit the physics motion of the object.
> 2 votes

# Answer
Are you using Rick's udemy course? It's a great one!

my question is, what is the rigidbody.rotation part about?

also, your problem could be this.

Your supposed to use: Rigidbody2D, not Rigidbody. Rigidbody is used for 3D, while Rigidbody2D is used for, well, 2d.

hope this helps.
> 0 votes

---
Tags: unity
---


# Question
Title: How to compute the forward, up and right vectors from a single quaternion?
Given a quaternion

```
float x, y, z, w;

```

How does one the forward, up and right vector from a single quaternion?

```
vec3 up;
vec3 forward;
vec3 right;

quat_get_all_axis(&quat, &up, &forward, &right);

```

This seems useful to accomplish things like move forward/back, strafe and jump.

# Answer
You can simply apply the quaternion to the (0,1,0) (0,0,-1) and (1,0,0) vectors for `up` `forward` and `right` resp.
> 4 votes

# Answer
What I believe @ratchet freak means when he says "apply" is to rotate each of the original front, right and up vectors around the orientation quaternion. I'll just leave this implementation based off this OpenGL FPS Camera Quaternion tutorial here for future reference. (I had to invert the quaternion to get working camera controls, others may not need to).

```
glm::mat4 Camera::GetViewMatrix()
{
    glm::quat qPitch = glm::angleAxis(glm::radians(-Pitch), glm::vec3(1,0,0));
    glm::quat qYaw = glm::angleAxis(glm::radians(Yaw), glm::vec3(0,1,0));
    // omit roll
    orientation = qPitch * qYaw;
    orientation = glm::normalize(orientation);
    glm::mat4 rotate = glm::mat4_cast(orientation);
    glm::mat4 translate = glm::mat4(1.0f);
    translate = glm::translate(translate, -Position);

    return rotate * translate;
}

void Camera::updateCameraVectors()
{
    Front = glm::rotate(glm::inverse(orientation), glm::vec3(0.0, 0.0, -1.0));
    Right = glm::rotate(glm::inverse(orientation), glm::vec3(1.0, 0.0, 0.0));
    Up = glm::vec3(0.0, 1.0, 0.0);
}

```
> 2 votes

---
Tags: transformation, quaternion
---


# Question
Title: Unity 2D launch player towards mouse location
few notes:

1. I'm new to game development
2. I'm not new to developing (1 year of front end web development)

I'm trying to get my character to launch towards mouse left click button (which I understood to be translated into screen onclick once its exported to mobile) I've got the following code down (used the web for help)

move speed is a float that's equal to 10 in this example

```
if (Input.GetMouseButton (0)) {
        mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        direction = (mousePosition - transform.position).normalized;
        rb.velocity = new Vector2 (direction.x * moveSpeed, direction.y * moveSpeed);
    }

```

Which works great, but has 2 issues: If I keep holding leftMouseButton my character is pinned to the cursor I want a single, gravity affected, launch (jump of sort) towards my mouse button.

This is all under the Update() function.

# Answer
Your condition, `Input.GetMouseButton(0)`, will be true for as long as that button is held down. Your code therefore updates the velocity of your Rigidbody2D to move it towards the target (tap position) while the button is held down / a tap on the screen is held, which is what produces your 'pinned to the cursor' behaviour.

---

Depending which phase (input started / completed) you want to trigger on, `GetMouseButtonDown` or `GetMouseButtonUp` can be used for reading button state changes. These will only return true once per press, unlike the ongoing `GetMouseButton`.

---

To perform an immediate change in velocity, *"...such as forces from explosions or collisions."* `ForceMode2D.Impulse` is useful, in conjunction with `Rigidbody2D.AddForce` (also applicable to the other similar methods on Rigidbody2D). The default ForceMode2D (`ForceMode2D.Force`) is for applying force continuously, each FixedUpdate.

As an example, to make a Rigidbody2D `rb2d` jump towards some point `target` with a magnitude of `jumpMagnitude`, you could use:

```
Vector2 heading = target - rb2d.position;
Vector2 direction = heading / heading.magnitude;
rb2d.AddForce(direction * jumpMagnitude, ForceMode2D.Impulse);

```
> 1 votes

---
Tags: unity, 2d, movement, mouse
---


# Question
Title: My script to play the intro scene the first time the player hits play from the main menu wont work
The script I am using determines if it is the players first time hitting the play button and if it is it will load the intro scene, but if they have played before it will take them strait to the game scene. The problem is that it just takes them strait to the game scene.

```
public class SeenBefore : MonoBehaviour
{
    public string SceneName;

    AsyncOperation preload;

// Start is called before the first frame update
    void Start()
    {
        preload = SceneManager.LoadSceneAsync(SceneName);
        preload.allowSceneActivation = false;
    }

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

    }

    public void before()
    {
        if (PlayerPrefs.HasKey("HasSeenIntro"))
        {
        preload.allowSceneActivation = true;
        }
        else
        {
            PlayerPrefs.SetInt("HasSeenIntro", 1);
            SceneManager.LoadScene("Intro");

        }
    }
}

```

# Answer
I'm unable to reproduce this problem.

In my tests with this code, the first time I click the button I go to the "Intro" scene.

Any subsequent run of the game, I go to the scene named in the `SceneName` variable.

So, this is likely due to incorrect setup in your project/scenes/inspector.

Things you can try:

1. Verify that both scenes have been added to your Build Settings.
2. Check that you are calling the scenes by the correct names - be sure you have strict character-for-character equivalence, or look them up by ID instead. (In particular, make sure you haven't set `SceneName = "Intro"`, else all roads lead to Rome)
3. Add a button to your project to delete all PlayerPrefs on demand, so you can ensure you're not getting data from past runs.
4. Ensure you have no other scripts that are also firing off their own scene loads - try setting up a new, empty project with just three scenes: a start scene, a first-time-only scene, and a second-time-and-after scene, and only this one script.

For testing convenience, here's a version of the script with a function to reset your preferences key.

I've verified this works as desired, going to `firstTimeScene` the first time `Transition()` is called, and to `fallbackScene` the next time the button is pressed on a subsequent return to the menu or fresh run of the game. Calling `ResetPlayerPrefs` correctly resets this behaviour, so it behaves as the first time again.

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class ScenePreloader : MonoBehaviour
{
    public string firstTimePrefsKey = "HasSeenIntro";

    public string firstTimeScene = "SceneA";
    public string fallbackScene = "SceneB";

    AsyncOperation _preload;

    void Start() {
        _preload = SceneManager.LoadSceneAsync(fallbackScene);
        _preload.allowSceneActivation = false;
    }

    public void ResetPlayerPrefs() {
        PlayerPrefs.DeleteKey(firstTimePrefsKey);
        PlayerPrefs.Save();
    }

    public void Transition() {
        if (PlayerPrefs.HasKey(firstTimePrefsKey)) {
            _preload.allowSceneActivation = true;
        } else {
            PlayerPrefs.SetInt(firstTimePrefsKey, 1);
            SceneManager.LoadScene(firstTimeScene);
        }
    }
}

```
> 2 votes

---
Tags: unity, c#, scene, preload, async
---