# Question
Title: World & client listening, use multi-threading or multi-process?
My game is based on a client / server architecture where client only sends input and receives server output.

Server has to keep track of the game, updating the world etc. But also listen to clients and their input. The server accepts input for 100ms and then processes all the input,sending the result (the output) back.

**What would be the most optimal in terms of performance.** Have two processes, one for the game and one for listening to clients for input and sending output back. Or go full multi-threading.

I read on how to communicate between processes and it didn't seem very optimal (Sockets, RMI, file sharing).

# Answer
First of all, you should see what your platform offers you. Most networking systems will offer some form of non-blocking socket API where the nasty multi-threading is left to the operating system. All you have to do is poll the sockets at one point of your game loop to see if they have received any data. This is really convenient for you, because it prevents a lot of headache resulting from debugging multithreading bugs.

When you can't or don't want to use these APIs (you should!), then you will have to use blocking sockets. In that case you will have to create two threads per client, one for sending data and one for receiving it. The receiving threads should write their results to thread-safe data structures which are then polled by the main game thread each tick. Do not let the receive-threads manipulate the gamestate directly. Manipulating data by multiple threads is a recipe for disaster, because you never know when they are going to do that. Expect weird bugs which only appear very occasionally and are impossible to reproduce, because they depend on rarely occurring microsecond timing conditions.

You might also have to use the "thread-safe receive buffers" in some APIs which handle network messages with callback functions. Check the documentation to verify that these callbacks happen from their own threads (as opposed to a specific point in your game loop which you can specify).

Regarding your question of threads vs. processes: A process can do everything a thread can do, but is more expensive to create and maintain and interprocess communication is more cumbersome than communicating between threads which can simply pass object references to each other. IF you want to use multithreading, use one process with multiple threads. Multiple processes only make sense if you either want to distribute them over multiple servers (which can be very useful to ensure future scalability of MMOs) or when these processes are optional components people might or might not need (like a specialized reverse proxy server).
> 1 votes

---
Tags: multiplayer, multithreading, socket, process
---


# Question
Title: What is glViewport for and why it is not necessary sometimes?
I develop my game most of time under ArchLinux. I have decided to try it on the Ubuntu 16.04 recently. The situation I came across was really strange:

1. No `glGetError()`s at all.
2. No errors, warnings, anything bad in the gl debug output.
3. All assertions that I made for all bad situations did not trigger.
4. `glClear` successfully cleared the buffers I specified, but:
5. `glDraw*` did not draw anything.

Luckily I have found a solution which was to set `glViewport`. However, I don't quite understand, why is it necessary for drawing in Ubuntu but not necessary in ArchLinux? The also difference is between graphics adaptors: on archlinux I use NVIDIA 1060, on Ubuntu I use integrated HD Graphics P530 (Skylake GT 2).

If it is important, I use SDL2 with opengl 4.4.

# Answer
You've got two good answers already but they may be hard to understand for a beginner so I'll tell you why do we really need `glViewport` function.

In typical rendering it may seem to have no sense - you just create some window or render target and draw on it, right? I'd say that 95+% of apps works that way.

But let's say your're writing an app like 3DS MAX, where you have you window split into 4 distinct renderings. You remember your current split position and you manage Mouse events, so when you hover over the split bar you may change mouse cursor to resizing one, etc. When you drag your split bar you remember its new position and so on.

When you want to render your 3D views you cal glViewport with position and size of your first 3D-subwindow and run typical GL commands to draw here. OpenGL will automatically scale the rendering so it fits into the given viewport. You do the same for the rest of your viewports and at the end you get one window with few different renderings, each with its own parameters. This way you can have as many distinct renderings on single window/render target as you want.

**Why it didn't work on one machine?**

GPUs and their drivers have a lot of implementation details and differences so in general you need to get used to such issues. One simple example: In GLSL shader you can create a 2D zero vector like that: `vec2(0.0,0.0)`, you may try also to write one value: `vec2(0.0)` and with this code some drivers will treat it as previous version while others will return error and render nothing. Bear in mind that drivers from two vendors will differ more that two versions of the same driver, so it's a good idea to test your code on nVidia, ATI and Intel GPUs. In this very case I suspect that in nVidia drivers, when you don't set the vieport by yourself they assume you want to use entire render target, while Intel drivers don't do that.
> 7 votes

# Answer
glViewport lets opengl know how to map the NDC coordinates to the framebuffer coordinates.

By default it is set to the full size of the screen buffer. So you only need to call it when the window gets resized or you actually want to change it.
> 3 votes

# Answer
glViewport specifies the affine transformation of xx and yy from normalized device coordinates to window coordinates. Let (xnd,ynd)xndynd be normalized device coordinates. Then the window coordinates (xw,yw)xwyw are computed as follows:

* 'xw=(xnd+1)(width2)+xxw=xnd+1width2+x'
* 'yw=(ynd+1)(height2)+yyw=ynd+1height2+y'

Viewport width and height are silently clamped to a range that depends on the implementation. To query this range, call glGet with argument 'GL\_MAX\_VIEWPORT\_DIMS'

The x and y parameters specify the lower left corner of the viewport in pixels, while width and height specify the width and height of the Viewport
> 2 votes

---
Tags: opengl
---


# Question
Title: How can i color each wall in another color?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsGrid : MonoBehaviour
{
    public GameObject gridBlock;

    public int worldWidth = 10;
    public int worldHeight = 10;

    public List<Vector3> positions = new List<Vector3>();

    private List<GameObject> GameObjects = new List<GameObject>();

    void Start()
    {
        GenerateGrid();

        GetPositions();
    }

    private void GenerateGrid()
    {
        for (int x = 0; x < worldWidth; x++)
        {
            for (int z = 0; z < worldHeight; z++)
            {
                GameObject block = Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.name = "Block";
                block.transform.tag = "Block";
                block.transform.localPosition = new Vector3(x, 0, z);

                GameObjects.Add(block);
            }
        }
    }

    private void GetPositions()
    {
        // Top wall

        for (int i = 0; i < worldWidth; i++)
        {
            positions.Add(new Vector3(0,0, i));
        }

        // Left wall

        for (int i = 0; i < worldHeight; i++)
        {
            positions.Add(new Vector3(i,0, 0));
        }

        // Right wall

        for (int i = 0; i < worldHeight; i++)
        {
            positions.Add(new Vector3(i,0, worldWidth -1));
        }

        // Bottom wall

        for (int i = 0; i < worldWidth; i++)
        {
            positions.Add(new Vector3(worldHeight -1,0, i));
        }

        for (int i = 0; i < positions.Count; i++)
        {
            for (int x = 0; x < GameObjects.Count; x++)
            {
                if (GameObjects[x].transform.localPosition == positions[i])
                {
                    GameObjects[x].GetComponent<Renderer>().material.color = Color.red;
                }
            }
        }
    }
}

```

I want to color each wall in another color. For example the Top wall in red.

Now it will color all the positions objects in red. But i want somehow to find in the loop when it's getting to the next wall positions and color it in another color.

Maybe i need to use dictionaries somehow ?

# Answer
Since the x and z are known in each case, simply check the value.

```
private void GetPositions()
    {
        // Top wall

        for (int i = 0; i < worldWidth; i++)
        {
            positions.Add(new Vector3(0,0, i));
        }

        // Left wall

        for (int i = 0; i < worldHeight; i++)
        {
            positions.Add(new Vector3(i,0, 0));
        }

        // Right wall

        for (int i = 0; i < worldHeight; i++)
        {
            positions.Add(new Vector3(i,0, worldWidth -1));
        }

        // Bottom wall

        for (int i = 0; i < worldWidth; i++)
        {
            positions.Add(new Vector3(worldHeight -1,0, i));
        }

        for (int i = 0; i < positions.Count; i++)
        {
            for (int x = 0; x < GameObjects.Count; x++)
            {
                if (GameObjects[x].transform.localPosition == positions[i])
                {
                     if(GameObjects[x].transform.localPosition.x==0)//TOP
                        GameObjects[x].GetComponent<Renderer>().material.color = Color.red;
                     else if(GameObjects[x].transform.localPosition.z == 0)//LEFT
                        GameObjects[x].GetComponent<Renderer>().material.color = Color.blue;
                     else if(GameObjects[x].transform.localPosition.z == worldWidth -1)//RIGHT
                        GameObjects[x].GetComponent<Renderer>().material.color = Color.green;
                     else if(GameObjects[x].transform.localPosition.x == worldHeight -1)//BOTTOM
                        GameObjects[x].GetComponent<Renderer>().material.color = Color.yellow;
                }
            }
        }
    }

```

Helpful Hint: It should be noted that there are better ways to look up game objects from the scene that prevent you from accidentally selecting an object that just happens to have the transform you're looking for. It also saves you the trouble of iterating over every object in the game. Do some reading on the FindGameObject methods.
> 1 votes

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


title: Unity Network Flip sprite renderer

text:
# Question
Title: Unity Network Flip sprite renderer
So my 2D characters turn by setting flipX on Sprite Renderer. I'm trying to turn them on other clients, but sprite is turning only on local client. And only host turns for all clients.

Here's my code:

```
RpcTurnChar(GetComponent<SpriteRenderer>().flipX, this.gameObject);

. . .

[ClientRpc]
void RpcTurnChar(bool flip, GameObject plr)
{
    plr.GetComponent<SpriteRenderer>().flipX = flip;
}

```

What am I doing wrong?

# Answer
\[ClientRpc\] functions are only called from the host. For the Client to send to the Host, you need a \[Command\] function, or serialize a variable.
> 2 votes

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


# Question
Title: render() can't seem to reference my sprite properly
This is driving me a little crazy. We use libGDX, working on making a simple side scroller for fun. I've got it switching from screens alright, loading from my main menu into my level one class, which implements screen.

```
public class levelOne implements Screen

```

Don't know if that effects this. When I try to initialize my sprite, my editor (AIDE) highlights it. Gives me an error saying that there is no access to the variable, as it does when you declare something but don't use it.

```
Texture faceTexture = new Texture(Gdx.files.internal("faceSprite.png"));
faceGuy = new TextureRegion(faceTexture, 50, 50, 95, 95);
Sprite player = new Sprite(faceGuy);

```

I do actually call up the sprite in `render()` though,

```
batch.begin();

// Background
batch.draw(backGround,0,0,2900,800);

// Player
player.draw(batch);

// Enemies
batch.draw(faceGuy, baddieOnePosition.x, baddieOnePosition.y, 150, 150);

batch.end();

```

It doesn't generate an error there, but trying to run it generates a crash. I can do a `batch.draw` of the texture, but every attempt at doing it as a sprite fails. I have it being initialized in `show()`, thought maybe making a new method to do so would help, but had the same result. The only way I've managed to make it work was to initialize it in `render()`, but that not only resets the sprites position multiple times a second, but I expect is also a memory hog. Help!

# Answer
> 1 votes
Solved it! I'm working on Android so logging is an issue, couldn't do that. And the local variable issue was correct, made the warning go away, thanks. Didn't solve the crashing.

What it ended up being was my screen switching. I have a spritebatch in a previous screen, which for convenience I also named `batch`. I wasn't handling my assets well, caused a crash when trying to reference the sprites. Solution was easy - on my previous screen, when I switch, make sure to also dispose of the spritebatch.

```
((Game)Gdx.app.getApplicationListener()).setScreen(new levelOne());

```

batch.dispose();

...managing resources is important.

---
Tags: libgdx, android, sprites
---


# Question
Title: How can I find out where a particular texture is being used in my Unity project?
I have a texture in my assets, and I need to find out where it's being used so that I can change some textures in my project.

**How can I find out where a specific texture is used in my project?**

The case is that the game needs to be updated to have a Christmas look, so there are a few game textures should be replaced.

---

This resource checker does not work for me. It shows that there are no textures even though there are:

# Answer
> 2 votes
To solve the problem just create a script that assigns a texture to a material based on a specific condition. The script should contain the two textures, and it should also get the object material. All you have to do is assign this script to each object you want to change the material's texture to.

If you want to see where a texture/ or a resource is currently being used in your game/scene here is a good tool which lets you do it: Unity Resource Checker

Also check out this thread for more information.

# Answer
> 2 votes
If you're comfortable with using the command line, you could look through every file in the project for the texture's guid. On my Mac, I have added these functions to my `.bash_profile` which helps in this regard:

```
function findasset(){
  LANG=C;
  guid=$(find . -iname "$1".meta -print0 | xargs -0 grep guid: | cut -d" " -f 2);
  echo $guid;
  findguid $guid;
}
function findguid(){
  LANG=C;
  guid=$1;
  find . -iname "*.unity" -print0 | xargs -0 grep $guid;
  find . -iname "*.prefab" -print0 | xargs -0 grep $guid;
  find . -iname "*.mat" -print0 | xargs -0 grep $guid;
  find . -iname "*.controller" -print0 | xargs -0 grep $guid;
  find . -iname "*.anim" -print0 | xargs -0 grep $guid;
  find . -iname "*.asset" -print0 | xargs -0 grep $guid;
}

```

Then, in my terminal window, I navigate to the project's root Assets folder, and simply type, for example, `findasset mytexture.png` and as long as that filename is unique within the project, it will print out all of the Scenes, Prefabs, Materials, Animatorcontrollers, Animations, and ScriptableObjects that reference said asset.

This was my approach because when I implemented something similar in Unity I found it to be unreliable at finding all the references. This may be tedious if looking for a large number of files, but in my experience it does find everything fairly reliably.

---
Tags: unity, assets, resource-management
---


# Question
Title: Determine height on Bresenham line algorithm path
I have path from Bresenham line algorithm, example for `A->B` vector:

Path is `[(0,5), (0,4), (1,4), (1,3), (1,2), (1,1), (2,1), (2,0)]`. Considering `A` height is 10 meters, `B` height is 5 meters and a tree at position `1,1` is 5,5 meters:

How to know if point `B` is visible from point `A` ? My real question is: How to know the `A->B` vector height when it is "above" specific position, so here `1,1` ?

# Answer
> 1 votes
You can get it using linear interpolation.

Basically, the y coordinate of the point on the **AB** vector at a specific x coordinate is:

$$y = \vec A\_y + (\vec B\_y - \vec A\_y)\space \cdot\space\frac{ x}{\vec B\_x - \vec A\_x}$$

If you need the tile height, then just floor the value

---
Tags: 2d, geometry
---


# Question
Title: UI Button OnClick not playing AudioClip on gameObject
Basically, I am loading an Audio Clip onto a game object's Audio Source in the Awake function when the game starts. When I click on the game object a UI comes up that basically has a Play button attached and all I want to do is play the Audio Clip on the Audio Source. The problem is I can see that there is an Audio Clip on the Audio Source at runtime and I can play it in the inspector at runtime but, when I click the button nothing happens. I have tried just referencing the gameObject in the OnClick() of the UI button and that doesn't work and I have also tried going through and getting the gameObject through `GameObject.Find`

```
public void PlayMe()
    {
        GameObject[] objs = GameObject.FindGameObjectsWithTag("Voice_log");
        foreach (GameObject obj in objs)
        {
            if (obj.layer == LayerMask.NameToLayer("Selected"))
            {
                Debug.Log("Found it");
                if (obj.GetComponent<AudioSource>().clip.loadState == AudioDataLoadState.Loaded)
                {
                    obj.GetComponent<AudioSource>().Play();
                    Debug.Log("Should Play");
                }
            }
        }
    }

```

Both of my Debugs print when I click the Play button.

# Answer
> 0 votes
Because I am changing the Audio Clip during runtime the normal `OnClick` method doesn't catch my updated variable and only gets the original empty `AudioSource`.

In order to solve this, I added a listener to the button `OnClick` method in a script attached to my game object.

```
button.onClick.AddListener(delegate { MethodToRunOnButtonClick(); });

```

# Answer
> -1 votes
Make sure you have an AudioListener on your camera. The Editor may be using a default listener when you manually play the sound, but in-game if there isn't a listener, you wont hear anything.

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


# Question
Title: Raycasting in three.js not working properly on ipad and touch devices
I am working on a 3D tool for desktop and iPad. Everything is working fine except for two issues:

Issue 1 - When I select a 3D object with the mouse and move it on an iPad (as opposed to on desktop, where it works just fine), it doesn't move. (You can add cabinet by selecting the cabinet panel in right).

Issue 2 - I want to spawn and drag an object with the click of a button like this. With this tool, you can add an object by selecting and dragging it to the scene.

Thanks in advance. :)

# Answer
To address Issue 1 - If raycasting works fine on desktop it should work fine on mobile (the THREE.js library/math code will be the same on each and runs without any sort of WebGL call as raycasting is done in the CPU in javascript).

I see though from the link that you're using `touchmove` which is correct but you're listening with your user creation function `onDocumentMouseMove` that reads `event.clientX`. This property doesn't look to be supported on iOS (See the compatibility table at the bottom).

It might be wise to use Hammer.js to normalize these events and properties into gestures for you or look into using a different property (like `.pageX`)
> 0 votes

---
Tags: javascript, three.js
---


# Question
Title: ExecuteNonQuery Memory Leaks without using unmanaged code implementations
I hate hate posting to ask for help. I can usually just figure this stuff out. I'm in over my head.

--How I arrived at my current conclusions (only read if you want my problem solving steps--

I discovered an application on which I was working had memory leaks. I endeavored to find them. I engaged in a process of trial-and-error removal of calls and functions until I eventually found a set of processes which appeared to be the culprit. It was a simple function which queried a sqlite database using an .ExecutableNonQuery(). More trial-and-error ensued to see if I could reproduce the error in a new function. I could. I tried to strip that function down to its absolute bare minimum and polished it to continue be more in line with best practices (as far as I can tell).

The problem persisted. Confused, I started trying to break the code altogether. I started taking out certain key components of the query to see if I could eliminate the memory leak. To be sure that the problem wasn't hidden somewhere else in the application, I built a new Unity Project with only one game object (no camera). It has one component on it (a C# script titled: Script; it's below). Nothing else. There are no other objects, scripts, functions, calls, references or anything in this project. The leak persists.

Here's the most minimal code I generated that works in full:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;
using System.Data;

public class Script : MonoBehaviour {

    string dbconnstring;

    void Start () {
        dbconnstring = "URI=file:" + Application.dataPath + "/civicismdb.sqlite";
    }

    void Update () {
        dbconnect();
    }

    void dbconnect()
    {
            using (IDbConnection conn = new SqliteConnection(dbconnstring))
            {
                using (IDbCommand cmd = conn.CreateCommand())
                {
                    conn.Open();
                    cmd.CommandText = @"select 1";
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
        }
}

```

This is the most minimal query I could possibly have. Two things stop the memory leak. If I comment out:

```
cmd.ExecuteNonQuery();

```

Or I adjust the query to be empty:

```
cmd.CommandText = @"";

```

In the latter case, I suspect .ExecuteNonQuery isn't actually running, but I'm unsure. Moreover, I've created a cmd.CommandText and assigned it the query value at this line:

```
cmd.CommandText = cmd1.CommandText;

```

Same result. The memory leak persists, of course, because that wouldn't really make much sense as a fix. Whatever, due diligence...

I tried to create my connections and commands once and simply reference them, but 1) that really isn't optimal *and* 2) it doesn't work anyway. The leak persists.

I tried to ensure that my cmd and conn were disposed of. Again, that 1) didn't fix the problem, and 2) doesn't make much sense as a fix because the using statement should ensure that they are disposed of anyway. But, I tried. To no avail.

Though explicitly calling GC.Collect() is a bad idea, I tried that as well given that it might be creating more connections/commands than it could dispose of given the update function calling the DB. No dice.

Also, I know querying the DB every update is a bad idea. I'm doing that for illustrative purposes. It makes the leaks clearer. In reality, I'm querying it often as called by a coroutine.

Now, I know that coroutines could cause their own memory leaks, but when running this with a coroutine, the leak stops if I comment out the .ExecuteNonQuery().

--My conclusion--

ExecuteNonQuery is leaking. Somewhere/somehow under the hood.

--My questions --

Am I missing anything?

Is this a known issue and I failed to find it in my googling?

Do you see a solution?

Thank you for reading. This has been a long and frustrating experience and my posting here is my conceding defeat.

---

EDIT -

I'm learning that I think SQlite does memoryleak a little bit at each invoke but for most applications this is just not relevant because the database is queried so infrequently. I'm also learning that sqlite does a ton to provide options to developers to manage memory more efficiently. See here for example:

https://www.sqlite.org/malloc.html

So, this isn't really a Unity problem. It's a user-error when using SQlite problem.

As far as I can tell, what I need to be doing is using unmanaged code to manage the memory myself. I'm only just learning how to do this and am struggling mightily to figure out how specifically to change configuration options, manage the heap, finalize connections, etc. any insights are very much appreciated.

At the moment, I'm trying to figure out how to call the sqlite3\_config option so that I can the configuration to MemSys5 instead of using malloc. No idea if that will actually solve the problem.

# Answer
Alright, I think I finally have this sorted. when wrapping these in using statements, the idea is that the garbage collector (GC) will collect all the discarded commands and connections no longer in use. something about this implementation is preventing the GC from doing that. I don't know what or why. In theory this implementation should have been stable. It isn't. So here's the plan instead:

Generally it is silly to create a pool of connections to be cycled through because I think sqlite already pools connections for you. But, again... something in this design is stopping it from pooling properly. Either that or the individual commands themselves are inflating. Either way, I'm building a pool of connections, readers, and commands and building a function to cycle through them to be constantly reused dynamically. I'll also build in a query cue so that no two queries can query at the same time.

Basically, build a query+command+reader combo, send it to the cue. Cue grabs the next one off the stack and runs it. Returns the result or null. That appears to be robust to inflation as long as I'm not closing the collections or commands. The readers can be closed without inflation.
> 1 votes

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


# Question
Title: How to use Java 8 with Lib GDX in IntelliJ?
I have set the jdk to Java 8 and I have modified all the build.gradle files in my project to have sourceCompatibility = 1.8 instead of 1.6. My problem is that while it does work on Desktop it doesn't when I run it on Android. Can someone tell me how to properly set up the project to use Java 8 so that it works on all platforms in IntelliJ?

# Answer
> 2 votes
I figured it out. Apparently Android does not support Java 8 yet, but you can use lambda expressions in Android. Here is a link to a page with a tutorial.

# Answer
> 0 votes
Android supports all Java 7 language features and a subset of Java 8 language features that vary by platform version. To enable those features add this to your build.gradle:

```
android {
  ...
  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

```

To read more about Java 8 and Jack Toolchain in Android go to this link.

# Answer
> 0 votes
Android Studio in version \> 3.0.0 natively supports some Java 8 features.

In Android Studio, go to File \> Project structure \> select android \> Tab properties \> Source compatibility \> 1.8.

You will also need to set the target compatibility to 1.7 (yes, 1.7 because there is some conversion process involved to translate Java 8 features to be compatible with Java 7 native code)

---
Tags: java, android, libgdx, ide
---


title: Precise punch animation for unity

text:
# Question
Title: Precise punch animation for unity
I'm using blender to model, rig and animate my character for a Unity game, but there is something that I can't figure out by myself neither find on the internet, for example:

Lets say the main character is able to punch npcs and I want that punch aimed to the face but not all npcs have the same height.

**How can the animation be adjusted to handle this?**

Inverse kinematics seems to be the solution but to this date I couldn't find any good example or information about this subject better than "Check this box to fix the animation for stairs" and so on.

# Answer
The only way I could think that will go well is to have the "joint"(I will call it joint1) that your arms are attached to and have it "lookAt"(in a script attached to it that says for it, in update, to use transform.LookAt) at an invisible object on the closes npc's head, OR if that don't work right, try having the joint1 calculate the height of the npc's head compared to the player's fist height and have the joint1 rotate accordingly and stop based with a raycast it has pointing foreward(I a not at my computer therefore I can't show code right now, but info on this can be found in the scripting API)
> 1 votes

# Answer
Make one animation for the lowest punch and one animation for the highest punch that you need. You can create multiple layers in the Animatior Controller in Unity and fade inbetween those layers. If the lowest animation is 1 meter and the highest animation is 2 meters you can crossfade between the layers. Set Layer Weight to 60% to punch someone at 1.60 metres.

Here's something I did for a boat:

Access the Animator and call

```
punchAnimator.SetLayerWeight(layerIndex, (targetpunch - lowpunch) / (highpunch - lowpunch);

```

Where targetpunch, lowpunch and highpunch are values for the height of the punch. I hope this helps you punch people with greater accuracy.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Working with Blender (Model individual objects or scenes?)
I've been working in Unity for awhile but I'm pretty new to making my own models. I'm using Blender since it seems like a pretty good tool for the job. Let's say I am making a simple scene in Unity with a table that has a cup and plate on it and some chairs. Assume I want to be able to move each of these objects around independently from the other objects. Does this mean that when modeling in Blender, I have to model each object individually and import them separately in Unity? It would be nice sometimes to be able to model entire scenes in Blender, but if stuff in the scene isn't intended to be static, then there is no way to treat parts of these scene as objects and manipulate them individually in Unity right?

# Answer
> 2 votes
Short answer:

**Yes**, if you don't want to deal with more complex stuff in Unity instead.

Long answer:

You don't really *have to* make them separate models, but you would have to separate their meshes inside Unity itself. This will involve much more effort on your side than just making them separately in Blender, or exporting the scene part by part (i.e. export a chair by copying and pasting that into a new model).

This way, you won't have to deal with splitting a mesh in Unity and moving things around that way.

In short, it's not impossible to do a whole scene in Blender then export that into Unity and move stuff around individually, but it's **really hecking hard** to do so. (Side note: you might also need to use some other assets from the asset store and maybe even some stuff that will cost money.)

---
Tags: unity
---


# Question
Title: Keep the timer counting after changing scenes
In my game you have 2 minutes to finish the whole game and after searching for an answer to my problem I think I should use `DontDestroyOnLoad` but I can't understand how to use it correctly. Here's the code:

```
public class countdownTimer : MonoBehaviour {

    public float myTimer = 120;
    public Text timerText;
    private bool timerIsActive = true;

    void Start () {
        timerText = GetComponent<Text> ();
    }

    void Update () {
        if (timerIsActive) {
            myTimer -= Time.deltaTime;
            timerText.text = myTimer.ToString ("f0");
            print (myTimer);

            if (myTimer <= 0) {
                myTimer = 0;
                timerIsActive = false;
                SceneManager.LoadScene ("lose");

            }
        }

    }
}

```

# Answer
You can just put the line in the Unity API of `DontDestroyOnLoad()` inside `Awake()` method and your object will not get destroyed when you load a new scene. This does mean that you need to manage the object separately or use a `Find()` method to find and access it in later scenes. Keep in mind that if you include this object in all your scenes, you will end up with duplicates.

In your case, to make this object persist through scenes, you can just change your code like so:

```
public class countdownTimer : MonoBehaviour {

    public float myTimer = 120;
    public Text timerText;
    private bool timerIsActive = true;

    void Start () {
        timerText = GetComponent<Text> ();
    }

    void Awake() {
        DontDestroyOnLoad(transform.gameObject);
    }

    void Update () {
        if (timerIsActive) {
            myTimer -= Time.deltaTime;
            timerText.text = myTimer.ToString ("f0");
            print (myTimer);

            if (myTimer <= 0) {
                myTimer = 0;
                timerIsActive = false;
                SceneManager.LoadScene ("lose");

            }
        }

    }
}

```
> 2 votes

---
Tags: unity, timer, scene
---


# Question
Title: How would I check the range against the entirety of an enemy object, and not just it's transform.position?
I want to be able to do range checks against the entirety of an enemy object, and not just it's transform.position. The enemy object can have it's side or nose within range, but range detection will not determine if it's close enough to be targeted unless it's transform.position is within range.

Right now I run a quick check against all nearby units to determine their distance from a turret on the friendly unit.

I was thinking raycasts, but I imagine raycasts every frame for up to 10 detected enemies per unit (Each unit will at max hold onto references of 10 nearby enemies. I could have 100 friendly units within range of 100 enemies) would chew up a fair bit more CPU than just checking their cached transforms.

Suggestions, ideas, or comments?

**Edit: More Detail**

Currently a Unit has a trigger spherical collider that defines it's view range. Any enemy unit within this view range is added to a collection based on priority, with a maximum of 10 objects referenced per collection (each Unit can only be aware of 10 enemy objects). From there, each turret on ship checks the distance from itself to each of the enemies within that collection. When the distance is \<= it's attack range, it will fire upon whichever enemy object gets within it's attack range first.

I used to use spherical colliders for each turret, which of course would detect the enemy as soon as any part of the enemy entered the trigger collider. The issue was the massive performance loss due to OnTriggerStay() begin called by hundreds of units, tens of thousands of times per frame when I have no need for the method. So I discarded the extra trigger colliders for a more performance friendly approach.

The issue is that the range check is that is checks the transform.position of the enemy. This does not take into account the collider that makes up the enemies shape, and will only trigger when the center of the object enters within range.

# Answer
> 2 votes
Two dot products, using the vector between their centers, tells you which corner is closest.
A positive "Forward" dot indicates a front corner; negative is rear.
A positive "Right" dot indicates a right corner; negative is left.
If the distance between the selected corner and the friendly is less than Range, it is in-range.

**Nearest-corner test:**

**This will detect collisions that aren't caught by the nearest-corner-test:**
(Diagramming purple was a mistake since it would have already passed the nearest-corner-test. The calculation will work for all cases, including perpendicular, as shown in white.
For the perpendicular, `(Width / 1.0) * 1.0 == Width`.)

Re-use the dots from the nearest-corner-test to find the nearest "cardinal" enemy direction (the larger of the two). Calculate the hypotenuse length and, if `(DistanceBetweenCenters - HYP) <= Radius`, the enemy is within range.

**Edited to include theory and attempted to make better use of color:**

# Answer
> 2 votes
Unity provides this functionality out of the box with Collider.ClosestPointOnBounds and Rigidbody.ClosestPointOnBounds (for compound colliders).

Testing whether an object is in range is as simple as:

```
bool IsInRange(GameObject target, Vector3 origin, float rangeSquared) {
    Vector3 closest = target.GetComponent<Rigidbody>().ClosestPointOnBounds(origin);

    return ((closest - origin).sqrMagnitude <= rangeSquared);
}

```

(Note that I'm using sqrMagnitude and compare the result to "range squared" because it's faster, especially if the range doesn't change often)

**Or**, as DMGregory pointed out, you could use Physics.OverlapSphere / Physics.OverlapSphereNonAlloc to check with a sinlge call:

```
void ProcessAllInRange(Vector3 center, float radius)
{
    Collider[] hits = Physics.OverlapSphere(center, radius);
    int i = 0;
    while (i < hits.Length)
    {
        //do work
        i++;
    }
}

```

It is worth mentioning that Physics.OverlapSphere (as far as I can tell) checks for actual collisions, while Rigidbody.ClosestPointOnBounds uses the compound collider's (axis aligned) bounding box.

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


# Question
Title: What is the difference between a Listener and a CaptureListener in LibGDX Scene2D
According to the documentaton.

Adding a listener : `Add a listener to receive events that hit this actor.`

Adding a capture listener : `Adds a listener that is only notified during the capture phase.`

I was not successfully able to find information on this so called `capture phase`. What is the difference between both listeners? When should I use one over the other?

# Answer
According to the official LibGDX wiki, capture listeners are called before "normal" listeners to give you a chance to intercept the events. (i.e. Active window cancels click on button under it)

> First, during the "capture" phase an event is given to each actor from the root down to the target actor. Only capture listeners are notified during this phase. This gives parents a chance to intercept and potentially cancel events before children see them. Next, during the "normal" phase the event is given to each actor from the target up to the root. Only normal listeners are notified during this phase. This allows actors to handle an event themselves or let the parent have a try at it.

To intercept an event, you must can either use `event.cancel()`, which will prevent propagation but also mark the event as cancelled or use `event.stop()` which will also prevent propagation but without cancelling the event.

When an event is cancelled the code that fired the actor will know and may respond accordingly. For example, if the click on a `Button` is cancelled, it will avoid changing its `isChecked` state. The details of what happen when an event is cancelled depends entirely on the actor or code firing the event.
> 6 votes

---
Tags: libgdx, scene2d
---


title: Quaternion Orientation / Sensor

text:
# Question
Title: Quaternion Orientation / Sensor
I am posting here even though this isn't technically a game development question, but involves quaternions.

I have a 9-axis sensor which gives me a world-frame (gravity, magnetic-north) quaternion representing it's orientation. It's mounted on the laces of a running shoe (meaning there is a 'pitch' offset for the sensor, relative to the shoe). Which means that the axis of rotation of the sensor and of the shoe are different. If I 'roll' the shoe along it's lengthwise axis, then the sensor traces out a cone, with the quaternion returning the x,y,z,w components for that cone.

What I'd like is the 'equivalent' quaternion for the axis of the shoe. Ultimately, deriving Pitch, Roll, Yaw for some of our (non)quaternion metrics, like pronation.

Appreciate any pointers, as what I've tried thus far doesn't seem to be working.

Thanks! -Tim

# Answer
> 1 votes
I would just convert the quaternion to a 4x4 or 3x3 matrix first.

The three rows in that matrix are the sensor's X-axis, Y-axis and Z-axis.

Let's say the shoe is tilted in the sensor's Y, then just multiply the matrix with a rotation matrix to undo that tilt.

In pseudo code:

```
mat44 sensormat = mat44( sensorquat );
vec4  sensory = sensormat.getRow( 1 );
mat44 rotmat = mat44::make_rot( sensory, tiltangle );
mat44 shoemat = sensormat * rotmat;
vec4  shoex = shoemat.getRow(0);
vec4  shoey = shoemat.getRow(1);
vec4  shoez = shoemat.getRow(2);

```

---
Tags: quaternion
---


# Question
Title: Parameter "MoveX" (and "MoveY") does not exist
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    public float moveSpeed;

    public Animator anim;

// Use this for initialization
void Start () {
    anim = GetComponent<Animator>();
}

// Update is called once per frame
void Update () {
    if (Input.GetAxisRaw ("Horizontal") > 0.5f ||
        Input.GetAxisRaw("Horizontal") < - 0.5f) {
            transform.Translate (new Vector3
        (Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
        }

        if (Input.GetAxisRaw ("Vertical") > 0.5f || Input.GetAxisRaw ("Vertical") < -0.5f) {
            transform.Translate (new Vector3 (0f, Input.GetAxisRaw ("Vertical") * moveSpeed * Time.deltaTime, 0f));
        }

        anim.SetFloat("MoxeX", Input.GetAxisRaw ("Horizontal"));
        anim.SetFloat("MoxeY", Input.GetAxisRaw ("Vertical"));

        }
    }

```

I an trying to run this with a basic 2D animation in unity personal and I keep getting Warning! - Parameter "MoveX" does not exist and Parameter "MoveY" does not exist but it is clearly in the animator as a float.

# Answer
> 1 votes
You typoed. `MoxeX` instead of `MoveX`, and `MoxeY` instead of `MoveY`

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


# Question
Title: Detecting which side of the collider is hit
We are trying to determine which side of the collider is hit in order to let the colliding object pass through or land on the other object.

Our previous failed attempts included detecting object velocity and changes on Y axis in our 3D game with locked Z axis (simulated 2D).

Currently, the detection is working by calculating the velocity - when the "Object in motion" hits the top of the black cube ("trigger collider") by the certain level of velocity (determined by gravity) the "collider" is activated. Otherwise, when the velocity is higher - the "object in motion" passes through. This, of course introduced a lot of issues and the solution itself is not elegant.

In the other scenario, we have tried adding trigger colliders around the "static object". This also complicates the process when "object in motion" has an arc when landing. Likewise, this solution is hard to maintain and prone to bugs.

On top of that, we implemented Raycasting. But we are not getting consistant "Top" and "Bottom" trigger indications when using it. Here is the gist of that code.

```
 void OnCollisionEnter(Collision collision)
 {
     if (collision.gameObject.tag.Equals("my_cube"))
     {
         var hit = HitDirection();
         Debug.Log(hit);
     }
 }

 bool IsRightOrLeftHit()
 {
     RaycastHit hit;

     Ray rayUp = new Ray(transform.position, Vector3.up);
     Ray rayDown = new Ray(transform.position, Vector3.down);

     Physics.Raycast(rayUp, out hit);
     Physics.Raycast(rayDown, out hit);

     return hit;
 }

```

We would appreciate any hint or help, and please ask me any questions if the explanations are not clear enough.

# Answer
If you are doing a 2d game, Unity already has this functionality built in. It’s called a platform effector. You can set it to work only one way, so that way collision from the top works but not the bottom. You just have enable use one way on the platform effector 2d component.

If you are doing a 3d game you can use a non convex mesh Collider Using a plane as the mesh. The collision will only work one side using this technique as well.
> 2 votes

# Answer
Assuming I'm understanding the intended behaviour correctly, you could simply compare the distance of, say, the raycast origin or its hit.point (both should work) to

1. the black cube's position and
2. its position offset by the normal of whatever direction you want to check.

So for example:

```
Vector3 middle = blackCube.transform.position;
Vector3 shifted = blackCube.transform.position + normal * 0.01f; //some small value

float x = (middle - origin).sqrMagnitude - (shifted - origin).sqrMagnitude;

if (x <= 0) {
  //handle one direction
}
else {
  //handle other direction
}

```

PS: The reason I'm using Vector3.sqrMagnitude here is that it's faster than Vector3.magnitude (https://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html)
> 0 votes

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


title: Requesting World from Server

text:
# Question
Title: Requesting World from Server
I'm creating a 2D Game in Java. The world is tile based with a multidimensional Array and i have the architecture for the Server-Client system. The Users/Connections to the Clients are multithreaded and i have also created the packages.

Now my question is : Should my Client send a package to the server to request the current world state(with entites etc...) in his view range or should i create another thread in my connection/user class just for sending the world every servertick? Or is there even a better solution for sending/requesting the world with his enteties ?

The Game should have less latency and is real Time with an open World.

# Answer
I think the most sensible approach would be to send data that is required immediately to the player specific to their current location. From there you only send updated values when something in the players area changes. For example when the player first connects send the health values for all NPCs in their immediate area, when an NPC is damaged, send an 'update health' packet for that NPC. In the end this approach is much more efficient (and secure in terms of ESP hacks) than sending everything all the time.
> 2 votes

---
Tags: maps, mmo, client-server, server, packet
---


title: What is a VAO in Opengl?

text:
# Question
Title: What is a VAO in Opengl?
i've just started out with Opengl, and i've got to know what Vertex Buffer Objects are, but i really don't understand what VAOs are. Can someone help me?

# Answer
A VAO (or Vertex Array Object) is basically an OpenGL object. They allow us to bind Vertex Buffers with a specification for the layout of that Vertex Buffer. A VAO can be bound just like a vertex buffer object and any subsequent vertex attribute calls from that point on will be stored inside the VAO.

This has the advantage that when configuring vertex attribute pointers you only have to make those calls once and whenever we want to draw the object, we can just bind the corresponding VAO. This makes switching between different vertex data and attribute configurations as easy as binding a different VAO.

One thing to remember is that Core OpenGL (OpenGL version 3.x and 4.x) requires that we use a VAO so it knows what to do with our vertex inputs. If we fail to bind a VAO, OpenGL will most likely refuse to draw anything.
> 9 votes

---
Tags: opengl, terminology, vao
---


# Question
Title: Synchronization between several glDispatchCompute with same SSBOs
Let's say I have one compute shader A which writes to an SSBO, and then a second compute shader B which reads from the same SSBO.

Do I need to do anything special to ensure that A has finished executing before B starts?

# Answer
Yes, otherwise B may read data A is currently writing to or hasn't even reached yet. It's simple however, just call `glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)` between both invocations.

You should basically always use a memory barrier after a compute shader dispatch if you plan on reading data the compute shader has written to. There are a number of possible flags for different types of memory, but those can be easily found in the spec for `glMemoryBarrier`. Their names are pretty self-explainatory.
> 3 votes

---
Tags: opengl, gpgpu
---


title: Setting Window Icon SDL2

text:
# Question
Title: Setting Window Icon SDL2
I've been playing around with SDL2 and have made a very nifty little program! Now, I'm trying to set my window icon - for the SDL Window. I have the following code in the main function of my program, right after SDL initialization stuff.

```
            SDL_Surface* icon = IMG_Load("assets/system/interface/icon.png");
        SDL_SetWindowIcon(window, icon);

```

However, the topbar icon and the toolbar icon remain the same, default application icon! What could I be doing wrong???

Thanks!

# Answer
So even though my question was never FULLY answered, (I never changed the taskbar icon) I was still able to change the topbar icon. My problem was simply that the image was sized wrong and had too much transparent space around it. When I deleted the transparent space, everything went perfectly.
> 1 votes

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


# Question
Title: Implementing a lexicon for a word-based game with C# or C++
In my game project I have a lot of word existance checks based on some word bank. As usual arrays or map/set are not realy appropriate for this due to their speed/memory usage, I want to use Ternary Search Tree. After some googling I've realised that there's not so much info or code ready to use there. So I want to implement it myself.

Question is - can I write it in C++ and then export to Unity with cross-platform support? To be more precise: will I be able to use this cpp library on Android and iOS? Or maybe I should just write it in C# which, I believe, will be slightly less efficient?

# Answer
> 1 votes
As the comments point out, **don't prematurely optimize**. What this means is either "test it with a prototype" or "do a believable back-of-napkin Fermi estimate based on known implementation features"

> Or maybe I should just write it in C# which, I believe, will be slightly less efficient

Why would you believe it is less efficient? What makes it less efficient? Finding out the answers to these questions should be way less effort than writing a Ternary Search Tree in C++ and then figuring out cross-platform native interop in Unity.

---

**Do you actually need it?**

I think between two sublinear algorithms, there won't be a noticesable difference. Just for fun, I took the TWL06 Scrabble dictionary as a text file (178,690 words). Linear search with `grep` takes like 10ms (I can't easily measure the precise time with `time`) , as measured on the command line and uses 1MB memory. Obviously, this is a terribly inefficient strategy to use repeatedly. But even this is "good enough".

# Answer
> 1 votes
If you need to search for words in a lexicon, then simply storing them pre-sorted and using a binary search algorithm can reduce the complexity to O(log2N), that's basically the best you can get.

Similar with the memory. An average english word is around 5.1 letters long, if you store 200,000 word, that takes up around 1 megabyte, which isn't much, even on cellphones.

Searching through these takes 18 checks. You can't even measure that in milliseconds.

---
Tags: unity, c++, cross-platform, dll
---


# Question
Title: Game Maker: How to check overlapping instances of the same object?
I want to make sure that no two instances of `obj_A` are overlapping, but can't seem to figure anything out, because `instance_position`, `instance_nearest` and the like will include the instance running it, so if I had something like:

```
if instance_position(x,y,obj_A)!=noone
{
    with(instance_position(x,y,obj_A))
    {
        instance_destroy()
    }
}

```

All instances of obj\_A will destroy themselves because they think they are overlapping with themselves.

# Answer
This is what worked for me:

```
with(obj_A){
    if (id!=other.id) and (place_meeting(x,y,other)){
        instance_destroy();
    }
}

```

As it turned out, I just needed to compare the instances' `id`'s.
> 1 votes

---
Tags: collision-detection, game-maker
---


# Question
Title: Unitys [SerializeField] and parallel inheritance
I have the following:

```
public class Item
{
    [SerializeField]ItemData _data;

    public ItemData data { get { return _data; } }
}

public class Weapon : Item
{
    [SerializeField]WeaponData _data;

    public WeaponData data { get { return _data; } }
}

public class ItemData : ScriptableObject { }
public class WeaponData : ItemData { }

```

It seems like a pretty common setup to me, data is separated from logic classes - and I can use single scriptable objects to define stats for alot of items.

However, Unity gives me this error message:

> The same field name is serialized multiple times in the class or its parent class. This is not supported:

I understand what's going wrong, but I don't get how to work around it, I want the data objects to inherit so I don't need to keep two (or more, further into inheritance) separate data objects per weapon.

I also need the item inheritance for inventory/merchant list management. Using hiding screws up the serialization of the baseclass, which means I can't create default items - not feasible.

The issue is the same when using public instead of \[SerializeField\].

Any pointers?

# Answer
> 2 votes
It looks to me like you might actually want an `IItem` interface, or abstract class, a bit like this:

```
// Establish the contract that any "Item-ish"
// object must be able to provide ItemData
// through a standard property (could be abstract
// instead of an interface if you have code or
// members you want to share between item types.
public interface IItem
{
   public ItemData data { get; };
}

public class Item : IItem
{
    // Expose an inspector field of the concrete
    // type we want - this will accept ItemData
    // or any type inheriting from it.
    [SerializeField] ItemData _data;

    // Return this inspector-set property as our
    // IItem-mandated data property
    public ItemData data { get {return _data; } }
}

public class Weapon : IItem
{
    // Expose an inspector field of the concrete
    // type we want - this will accept only WeaponData
    // not ItemData instances that aren't weapon-specific.
    [SerializeField] WeaponData _data;

    // Return this specialized WeaponData as an ItemData
    // when requested.
    public ItemData data { get {return _data; } }
}

```

Now any code can work with a mixed group of Items and Weapons by treating them all as items. It can also use casts or the `as` keyword to get at Weapon/item-type-specific data when it knows it has a particular item type.

If you go much further with this, you may want to consider applying the principle of Composition Over Inheritance. Especially in Unity's setup, this can give you a lot more flexibility - letting you make things like a spiked shield that has both a DefensiveItem component and a WeaponItemComponent, without needing to refactor two separate branches of the inheritance hierarchy to handle such exceptions and hybrids.

---
Tags: unity, serialization, inheritance
---


title: Modifying GLFW callbacks

text:
# Question
Title: Modifying GLFW callbacks
I'm currently using Imgui for the GUI part of my OpenGL/C++ engine with the GLFW binding. The problem is though that this binding has encapsulated the input callbacks in a global .cpp file which makes it impossible to access for other classes. Now I could always use the regular routine to handle input without the callbacks like:

```
if(glfwGetKey(m_window, GLFW_KEY_A) == GLFW_PRESS)
   ...

```

but yet this won't give me the one-to-one mapping like the key callback provides as the conditional code is processed more than once. I have tried using static booleans without success to see if I could overcome the problem by setting the boolean to true when the key is pressed in the callback and then handling the outcome elsewhere. I also know that you can override callbacks with different ones but that would not make any sence in this case.

Does anyone know how to solve this problem?

# Answer
> 1 votes
> The problem is though that this binding has encapsulated the input callbacks in a global .cpp file which makes it impossible to access for other classes.

The imgui+GLFW backends have callback exposed in the imgui\_impl\_glfw\_xxx.h file:

```
void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow* window, unsigned int c);

```

And when you call ImGui\_ImplGlfwGL3\_Init() you can set install\_callbacks=true to install your own callback from where you can call the above functions if you need to.

---
Tags: opengl, c++, gui, glfw, imgui
---


# Question
Title: How to change the scene in Unity after all enemies have been killed?
I have a script that counts how many enemies are left and changes the scene when there are no more enemies. However, it doesn't work, and I can't find the error. I have a really similar script (it's almost the same to be honest) that works perfectly, but I can't figure out how to make this script work.

Here's the code:

```
public class enemyCountt : MonoBehaviour {

    public static int enemiessCount = 5;

    void Start() {}

    void Update(){
        print("Enemy count is " + enemiessCount );

        if(enemiessCount <= 0)
        {
            SceneManager.LoadScene ("bonus");
        }
    }
}

```

and this is attached to the bullet script:

```
if (collision.gameObject.tag == "Enemy") {
    enemyCountt.enemiessCount --;
}

```

# Answer
You are using 2 different scripts, so just enemyCountt.enemiessCount --; wont work. if both scripts are on the same gameobject, then you can use gameObject.enemyCountt.enemiessCount --;

if these arent in the same gameobject, then you can make a reference from the other gameobject with the other script

```
     public GameObject OtherObject;

     void Update(){
     if (collision.gameObject.tag == "Enemy") {
         OtherObject.enemyCountt.enemiessCount --;
     }

```

then you have in the object, where you added the script, a free field, where you can drag & drop your GameObject with the script "enemyCountt" and then it should work, but I'm not quite sure
> 0 votes

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


title: CCD in C++ Console application

text:
# Question
Title: CCD in C++ Console application
I am writing a game in a c++ console application. I would like to detect whether or not there is a collision between two objects, and displace them accordingly. All sprites are simply strings drawn on screen (Ex. a sprite with x 5, y 5, width 3, height 3 and the image "XXXXOXXXX" would create a 3-by-3 box of X's with a O in the middle). All objects have a x, y, length, and width which can aid in looking for potential collisions; however I would like to look at the actual string for finer collision detection. I am relatively new to the concept of continuous collision detection and I am having trouble finding the answer via Google. Does anybody know how I would go about doing this? Thanks in advance.

# Answer
Collision Detection is essentially looking for intersections of lines defined by points. A square bounding box consists of 4 points, the lines between being checked for intersection of lines between other pairs of collision points.

The only conceptual difference between a traditional bounding box and pixel-perfect bounding boxes, is that traditional BB's have fewer collision edges to check.

Pixel perfect boxes effectively have a new point for every non-transparent edge pixel. Some efficiency can be gained by eliminating bounding points that are co-linear and non-terminating(not on the ends of the line) with other points, which reduces the number of line segments that must be checked for intersection. If for some reason such an efficiency doesn't happen, there is no difference in "pixel-perfect" and simply iterating over the tiles that will occupy previously unoccupied space.

In your case, since you're "rendering" text in a console window, worrying about this is over complicating things. Maintain a list of characters that are considered "blocking", and when you move your 3x3 object, you only have to check the 3 cells immediately adjacent in the horizontal or vertical directions for "blocking characters". In the case of a diagonal movement, you have to check the 5 space that will be newly occupied by your 3x3 object. If part of your 3x3 is considered "non-blocking" or not part of your bounding box, simply ignore the cell that it will move into when doing your checks. If any of the tiles have a blocking character, you interrupt the move and don't change the position of the object.

TL;DR In a nutshell, you only have to check the spaces in the world that will be occupied against the corresponding characters in your object that will occupy them. So long as none "collide," move your object and rerender.
> 0 votes

# Answer
For a school assignment we made a class to wrap up the characters in, essentially creating bitmaps where instead of coloured pixels we used characters.

This greatly simplified things such as drawing stuff at the right place etc, and should also help you with your collision detection issues.

By viewing the characters as pixels your engine can use any techniques used in 2D games. This way you can effectively ignore that you are working with ascii-art instead of sprites.
> 0 votes

---
Tags: collision-detection, sprites, bounding-boxes, aabb, console
---


# Question
Title: Can I tell what graphic engine an Android game uses?
How can I know which graphic engine has an app android game like "Hidden City" for example?

Are there any tools or web pages to analyse some game applications for android to know how they did the graphics in their game?

For example if developers used some engine or pure XML?

PD: I don't want to steal the graphics, I just want to know how they managed to get that graphics in their game.

# Answer
> How can i know which graphic engine has an app android game like "Hidden City" for example?

In some cases, a developer will state the technology they use. Perhaps casually, in interviews or Twitter, or perhaps somewhere in the credits due to legal licensing requirements.

In other cases you may be able to make educated guesses based on how the technology looks or behaves, assuming the technology was used mostly-unmodified and *has* some distinctive characteristics you can look for.

You also may be able to tell through inspection of the game's binaries or data files, if possible.

But in general, you can't just go to some registry website and look the game up and get an answer. Your best bet, if you are curious, is to attempt to get in touch with the developer and ask if research does not reveal the answer elsewhere.
> 2 votes

---
Tags: android, graphics, graphic-effects
---


# Question
Title: Rotating plane to face object while rotating around z axis. C++
I want to create a plane 2d sprite plane that looks at a 3d object and then rotates by its z axis.

So I have created a LookAt Function in my game which will make the object look automatically at the sphere, but it is executed every frame, I believe this is because it makes the rotations every frame, now if I want to rotate it again by its local axis, the LookAt() overwrites this because its matrix is being set the same each time and so cannot rotate.

I believe I will have to rotate manually, now I know this problem is easy on one axis of rotation.

My maths is rusty. So I don't think I could just do this for a 3D rotation but I'm not sure. If so do I require quaternions?

Step by step desired action

1. Rotation on the z axis to make the plane face on the right x angle of sphere ignoring its y position.
2. Rotate on its x ais to make the plane face the y angle between sphere and 2d plane.
3. Rotate around the z axis each second, while remaining faced at the object.

@Jay

Here is the code related to the first answer which makes my model dissapear.

```
selec->SetPosition(a->unit_x, a->unit_y, a->unit_z);
selec->GetMatrix(&rotmatrix[0][0]);
CMatrix4x4 crotmatrix{ &rotmatrix[0][0] };
crotmatrix.RotateLocalZ(0.025);

selec->GetMatrix(&lookatm[0][0]);
CMatrix4x4 clookat{ &lookatm[0][0] };
clookat.FaceTarget(CVector3{ 0,0,0 });

clookat.MultiplyAffine(crotmatrix);
convertmatrix(clookat);

selec->SetMatrix(&lookatm[0][0]);

```

This does multiply the matrices, but it keeps multiplying and creating a crazy motion, then causes a crash, maybe from gimbal lock?

# Answer
> 1 votes
Im going to quickly describe this, as I have to do similar for billboarding of my particles.

Simply, you have your desired target vector (target - viewer), and you have your viewer direction vector. You want your target vector to have no "Z" component effectively (as you are rotating around the Z axis). I eliminate the Z component and normalise the vector. You then cross the 2 vectors to get your rotation axis, Dot the vectors to be able to determine angle of rotation (Acos if i recall). Create a matrix with the axis and the angle.

vecb here would be your previous direction vector.

```
        void CalculateBillboardMatrix(Vector3 a_targetDirection, ref Matrix a_billboardMatrix)
    {
        Vector3 veca = a_targetDirection;
        Vector3 vecb = new Vector3(1, 0, 0); // this is always the direction the particle is initially created in.
        veca.Normalize();
        Vector3 axis = Vector3.Cross(veca, vecb);
        axis.Normalize();
        float angle = VectorExt.AngleBetweenVectors(vecb, veca, axis);

        a_billboardMatrix = Matrix.RotationAxis(axis, angle);
    }

```

This piece works out which direction to rotate the angle.

```
        static public float AngleBetweenVectors(Vector3 a_direction1, Vector3 a_direction2, Vector3 a_planeNormal)
    {
        Debug.Assert(a_direction1.IsNormalized);
        Debug.Assert(a_direction2.IsNormalized);

        float angle = Vector3.Dot(a_direction1, a_direction2);

        angle = (float)Math.Acos(angle);
        Vector3 cross = Vector3.Cross(a_direction1, a_direction2);
        cross.Normalize();
        if (Vector3.Dot(a_planeNormal, cross) < 0)
        { // Or > 0
            angle = -angle;
        }

        return angle;
    }

```

The trick with the second item is to work out the winding, to this, you need to cross prod the axis with the vectors axis. The ordering changes the axis vector, you then Dot this to find out if its positive or negative which tells you the direction you need to rotate.

# Answer
> 0 votes
You don't need quaternions, you can do this with rotation matrices.

To get the final rotation you need to multiply successive rotations together. Order matters and in this case you'd use the rotations in the order you described.

Final rotation should be `lookAt4x4 * local4x4`.

---
Tags: c++, vector, quaternion
---


# Question
Title: How to make progress vertical bar increase instead of decrease
I have a script for a vertical progress bar using filled image but the image decreases (basically you can see the full image when the game starts and then it goes down, like a health bar) but since it's a progress bar I need it to increase (at the end I should see the complete image, not at first). This is the code:

```
public class ProgressBar : MonoBehaviour {

public Image Bar;
public float max_progress = 100f;
public static float cur_progress = 0f;

void Start () {
    cur_progress = max_progress;
}

void Update () {
    Bar.fillAmount = cur_progress / max_progress;
}

```

And I have `ProgressBar.cur_progress -= 0.4f;` in the bullet script because it should increase everytime you kill an enemy. I tried writing `+=` instead of `-=` but it doesn't work (the image is filled and it doesn't increase or decrease), and i think that is not incorrect so I don't know what the problem is. Thanks in advance.

# Answer
> 2 votes
Delete the line

```
cur_progress = max_progress;

```

from your `Start()` method. This is the part that currently says "Start 100% full."

Other than that, your idea to change the `ProgressBar.cur_progress` modification to `+=` is correct.

---
Tags: unity, image
---


title: Make enemy disappear after spawn

text:
# Question
Title: Make enemy disappear after spawn
I have enemies that spawn in different positions but what I want to do is that if you don't kill it after three seconds, the enemy disappears (but the spawning keeps happening of course, the enemy will show up again eventually). I tried using a coroutine but after reading the documentation and watching some tutorials I still don't understand very well how it works so I need some help. Thanks in advance. This is my code so far:

```
public class TimedSpawn : MonoBehaviour {

    public GameObject spawnee;
    public bool stopSpawning;
    public float spawnTime;
    public float spawnDelay;

    private GameManagerScript GMS;

    void Start ()
    {
        GMS = GameObject.Find ("GameManager").GetComponent<GameManagerScript> ();
        InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
    }

    public void SpawnObject ()
    {
        if  (GMS.counterDownDone == true){

        Instantiate (spawnee, transform.position, transform.rotation);
     }

        if (stopSpawning) {
            CancelInvoke ("SpawnObject");
        }
    }
 }

```

# Answer
> 1 votes
You can call `Destroy` with a 2nd parameter indicating the delay before the destroy occurs :

```
public void SpawnObject ()
{
    if  (GMS.counterDownDone == true)
    {
        Destroy( Instantiate (spawnee, transform.position, transform.rotation), 3 );
    }

    if (stopSpawning) {
        CancelInvoke ("SpawnObject");
    }
}

```

---
Tags: unity, spawning
---


# Question
Title: How to store the updated score in mysql databse from android?
I want to store the updated score in mysql database. So, what i do for that?

```
private void updateScore() {
    if (winner.equalsIgnoreCase("You")) {
        tally = 100 - computer.getId();
        MainActivity.userScore += tally;
        if (MainActivity.userScore >= MainActivity.maxEnd) {
            MainActivity.   stat++;
            MainActivity.totTurn++;
            MainActivity.userScore = 0;
            MainActivity.computerScore = 0;

        }

    }
    if (winner.equalsIgnoreCase("computer")) {
        tally = 100 - buddy.getId();
        MainActivity.computerScore += tally;
        if (MainActivity.computerScore >= MainActivity.maxEnd) {

            MainActivity.totTurn++;
            MainActivity.userScore = 0;
            MainActivity.computerScore = 0;
        }
    }
    MainActivity.saveConfig();
}

```

# Answer
You don't. Accessing an online MySQL database from a client application directly is a really bad idea for security reasons. The permission handling abilities of MySQL aren't refined enough to check what a game client can and can not write to and read from the database. You also can not restrict access to only *your* game client, because the MySQL server can not detect what software is behind an incoming connection (actually no server application can do that).

What you should do instead is create a server application using your preferred server application development technology. That server receives requests from the Android clients, verifies that they contain something the client is allowed to do, formulates and sends a query to the MySQL database and returns the results to the clients. Your MySQL database should be configured to only process queries which come from that server application.

Each of these steps allows a lot of creative freedom in implementation details, so giving a complete walkthrough would go too far here. If you have specific questions about them, please ask in form of a new question.
> 2 votes

---
Tags: java, android, mysql
---


title: Unity Network No sound on other clients

text:
# Question
Title: Unity Network No sound on other clients
I'm trying to play sound on other clients, so they could hear gunfire in the distance, but sound only works for the shooter. Here's my code:

```
    void Update()
    {
        ***

        if (Input.GetButton("Fire1"))
        {
            CmdFireWeapon(this.gameObject);
        }

        ***
    }

    [Command]
    void CmdFireWeapon(GameObject plr)
    {
       ***

        if (!plr.GetComponent<AudioSource>().isPlaying)
            RpcPlayWeapon(plr);

       ***
    }

    [ClientRpc]
    void RpcPlayWeapon(GameObject plr)
    {
        plr.GetComponent<AudioSource>().Play();
    }

```

I'm using 3D Spatial Blend, but there's no sound even with volume == 1 across all distance. Also tried with and without `if(isPlaying)` \- no progress. What am I doing wrong?

# Answer
> 0 votes
I think I figured it out. Player Prefab on other clients spawned without clip (it is loaded in its script). So I needed to load it first then play it. And I need to keep loading, because clip changes with different weapon.

```
[ClientRpc]
    void RpcPlayWeapon(GameObject plr)
    {
            plr.GetComponent<AudioSource>().clip =
                    plr.GetComponent<PlrController>().curWeapon.shotAudio;
            plr.GetComponent<AudioSource>().Play();
    }

```

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


# Question
Title: Unity UI: Dynamic button prefab font incorrect compared to other elements
I am having some issues when creating UI elements dynamically and the font size showing up incorrectly. The button is a prefab and font size set to 42 pixels. The elements next to it are not created dynamically and are set to the same font size and all settings are the same. It also is smaller or larger depending on the screen size but is NOT set to best fit

Using Unity 2017.x

# Answer
Looks like there was an issue in my prefab instantiation. Not sure exactly what it is but this fixed it:

```
GameObject TechList = Instantiate (Prefab) as GameObject;

TechList.GetComponent<ButtonTextController> ().ChangeText (SkillInfo.SkillName); // Only changes button text

TechList.transform.SetParent (this.transform, false);

TechList.transform.localScale = new Vector3(1, 1, 1);

```
> 0 votes

---
Tags: unity, gui
---


# Question
Title: How can I create a custom PropertyDrawer for my Point struct?
I created a `Point` struct:

```
[System.Serializable]
public struct Point
{
    public int x;
    public int y;
}

```

I am trying to create a property drawer for it, so that when it shows in the inspector, it is shown in a `Vector2` field. I have the following script in the "Editor" folder:

```
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(Point))]
public class PointEditor : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.Vector2Field(position, label, property.vector2Value);
    }
}

```

It shows up in the inspector the way I want, but the values are locked at 0. Basically, I am trying to access the `Point` instance from inside the `OnGUI` method, but this could be the completely wrong approach. How can I make this so that when the values are changed in the inspector, the respective `Point` is also changed?

# Answer
The reason that you can't change any of the values is because the `Point` struct isn't a `Vector2` data type. A `Vector2` contains 2 floats where `Point` has 2 ints, meaning that the types are incompatible. The other problem was that you couldn't get the data from the struct in the way that Unity's inspector code wants you too.

**Point.cs**

```
[System.Serializable]
public struct Point
{
    public int X;
    public int Y;
}

```

It took me a while to format it the same way that `Vector2`, it's a lot of code but is mostly there to get the correct formatting.

**PointDrawer.cs:**

```
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(Point))]
public class PointDrawer : PropertyDrawer
{
    SerializedProperty X, Y;
    string name;
    bool cache = false;

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (!cache)
        {
            //get the name before it's gone
            name = property.displayName;

            //get the X and Y values
            property.Next(true);
            X = property.Copy();
            property.Next(true);
            Y = property.Copy();

            cache = true;
        }

        Rect contentPosition = EditorGUI.PrefixLabel(position, new GUIContent(name));

        //Check if there is enough space to put the name on the same line (to save space)
        if (position.height > 16f)
        {
            position.height = 16f;
            EditorGUI.indentLevel += 1;
            contentPosition = EditorGUI.IndentedRect(position);
            contentPosition.y += 18f;
        }

        float half = contentPosition.width / 2;
        GUI.skin.label.padding = new RectOffset(3, 3, 6, 6);

        //show the X and Y from the point
        EditorGUIUtility.labelWidth = 14f;
        contentPosition.width *= 0.5f;
        EditorGUI.indentLevel = 0;

        // Begin/end property & change check make each field
        // behave correctly when multi-object editing.
        EditorGUI.BeginProperty(contentPosition, label, X);
        {
            EditorGUI.BeginChangeCheck();
            int newVal = EditorGUI.IntField(contentPosition, new GUIContent("X"), X.intValue);
            if (EditorGUI.EndChangeCheck())
                X.intValue = newVal;
        }
        EditorGUI.EndProperty();

        contentPosition.x += half;

        EditorGUI.BeginProperty(contentPosition, label, Y);
        {
            EditorGUI.BeginChangeCheck();
            int newVal = EditorGUI.IntField(contentPosition, new GUIContent("Y"), Y.intValue);
            if (EditorGUI.EndChangeCheck())
                Y.intValue = newVal;
        }
        EditorGUI.EndProperty();
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return Screen.width < 333 ? (16f + 18f) : 16f;
    }
}

```

It looks like this when compared to the `Vector2` type (as requested). Just swap the relevant parts of your code with this and it will let you change the values and keep them persistent throughout their use :)
> 15 votes

# Answer
I tried using the solution in the accepted answer but was having some issues with it, particularly when it was being used within a list. After messing around with things a bit and trying out different approaches, this is what I ended up settling on. I'm using the same property drawer for several different vector type structures (works well for any class with 2-4 fields each having a 1 character name).

```
/// <summary>
/// A custom property drawer for vectors type structures.
/// </summary>
/// <seealso cref="UnityEditor.PropertyDrawer" />
[CustomPropertyDrawer(typeof(Vector2i))]
[CustomPropertyDrawer(typeof(Vector2d))]
[CustomPropertyDrawer(typeof(Vector3i))]
[CustomPropertyDrawer(typeof(Vector3d))]
[CustomPropertyDrawer(typeof(Vector4d))]
[CustomPropertyDrawer(typeof(Quaterniond))]
public class VectorPropertyDrawer : PropertyDrawer
{
    /// <summary>
    /// A dictionary lookup of field counts keyed by class type name.
    /// </summary>
    private static Dictionary<string, int> _fieldCounts = new Dictionary<string, int>();

    /// <summary>
    /// Called when the GUI is drawn.
    /// </summary>
    /// <param name="position">Rectangle on the screen to use for the property GUI.</param>
    /// <param name="property">The SerializedProperty to make the custom GUI for.</param>
    /// <param name="label">The label of this property.</param>
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        var fieldCount = GetFieldCount(property);

        Rect contentPosition = EditorGUI.PrefixLabel(position, label);

        EditorGUIUtility.labelWidth = 14f;
        float fieldWidth = contentPosition.width / fieldCount;
        bool hideLabels = contentPosition.width < 185;
        contentPosition.width /= fieldCount;

        using (var indent = new EditorGUI.IndentLevelScope(-EditorGUI.indentLevel))
        {
            for (int i = 0; i < fieldCount; i++)
            {
                if (!property.NextVisible(true))
                {
                    break;
                }

                label = EditorGUI.BeginProperty(contentPosition, new GUIContent(property.displayName), property);
                EditorGUI.PropertyField(contentPosition, property, hideLabels ? GUIContent.none : label);
                EditorGUI.EndProperty();

                contentPosition.x += fieldWidth;
            }
        }
    }

    /// <summary>
    /// Gets the field count for the specified property.
    /// </summary>
    /// <param name="property">The property for which to get the field count.</param>
    /// <returns>The field count of the property.</returns>
    private static int GetFieldCount(SerializedProperty property)
    {
        int count;
        if (!_fieldCounts.TryGetValue(property.type, out count))
        {
            var children = property.Copy().GetEnumerator();
            while (children.MoveNext())
            {
                count++;
            }

            _fieldCounts[property.type] = count;
        }

        return count;
    }
}

```
> 2 votes

# Answer
Have you tried doing this?

```
property.vector2Value = EditorGUI.Vector2Field(position, label, property.vector2Value);

```

Basically, `EditorGUI.Vector2Field()` is a function that returns a value of the "position". By setting "position" variable to `EditorGUI.Vector2Field`, you'll be able to change the "position" variable.

Hope this helps!
> -2 votes

---
Tags: unity, serialization
---


# Question
Title: How can I prevent a latitude/longitude based chunk system from Mercator projection stretching?
I'm working on an little mapbox based game and I'm currently working on an latitude/longitude-based chunk system. The distance between each of them should be the same. As you can see in the example the width and height of each chunk are equal. The little grey square is just the chunk middle. Those chunks were created near latitude/longitude zero, where they aren't effected by the Mercator projection.

But due to the Mercator projection the distances between the chunks are increasing as more as they move away from the middle (they look kinda stretched).

As you can see the distances between each one aren't equal anymore. The height of each of those chunks did increase. Here's another picture of the Mercator projection to visualize what I mean:

The chunks of the first picture were created near the middle of the word map (where the big black upper arrow points towards). The chunks from the second pictures were created near the bottom of the world map, where the other arrow points towards.

The type of game I'm developing requires equal chunk sizes and also it doesn't look that good when at some point the chunks look different due to the stretching.

I want to achieve a chunk system like this on the mercator projection :

I calculate the chunks as follows:

```
First we need the player latitude/longitude coordinates : 3.0146683, 5.3046076

One latitude is about: 110.57 km -> 110570 meters.
One longitude is about: 111.32 km -> 111320 meters.

One chunk should be about 750 meters on the map.

Because latitude and longitude got different ranges we need to adjust the chunk size.

One latitude factor = 110570 / 750 = 147,43.
One longitude factor = 111320 / 750 = 148,42.

One latitude chunk size = 110570 / 147 = 750 meters.
One longitude chunk size = 111320 / 148,42 = 750 meters.

(Maybe this step is unnecessary)

Now we convert the Lat/Lng to meters.

Latitude in Meter = 3.0146683 * 110570 meters = 333 331.873931 Meters.
Longitude in Meter = 5.3046076* 111320 meters = 590 508.918032 Meters.

Now we need to calculate the meters till the last chunk by using modulo.

Latitude Modulo => 333 331.873931 modulo 750 = 331 meter.
Longitude Modulo => 590 508.918032 modulo 750 = 258 meter.

After that we are able to calculate the Latitude and Longitude chunks.

Latitude chunk position = 333 331.873931 - 331 = 333 000.873931.
Longitude chunk position = 590 508.918032 -258 = 590 250.918032.

When we didive that now through the chunk size we get the actual chunk position.

Chunk X = 333 000.873931 / 750 = 444,0011.
Chunk Y = 590 250.918032 / 750 = 787,001.

Rounded: Chunk X = 444; Chunk Y = 787.

Now we know that the player stands right in this chunk [444;787].

In the next step I just calculate the Chunk X and Y back to latitude and
longitude and convert them via transform.AsUnityPosition to 3D coordinates,
where I place those grey objects then.

```

So basically I need a way to have the same visual distance between each of those chunks. Or either a way to change the projection from Mercator to a square projection, where nothing is stretched. I never worked with mapbox/Google Maps before... so I'm a newbie. Or is there maybe a formula I can use to prevent my chunks from being stretched by the projection?

Thanks for your time and attention! :)

# Answer
If you want to use a Mercator projection, but have each chunk the same size, then you need to diminish the latitude span as you proceed away from the equator.

For the following examples I'll use a simplified Mercator-style projection that models the Earth as a sphere. If you're making use of a particular source of map/GIS data, you'll need to adjust this to use the appropriate ellipsoid/datum/etc. of your data source of choice.

This function gives us the transformation between latitude & longitude on the globe, and 2D coordinates on our map plane:

```
Vector2 mapCoordinates(float latitude, float longitude) {
    return new Vector2(longitude, Mathf.Rad2Deg * Mathf.Tan(latitude *  Mathf.Deg2Rad));
}

```

The map coordinates run from -180 to 180 horizontally and -infinity to +infinity vertically by default, but you can scale the result differently as needed.

Let's say we're dividing the surface into `n` chunks around the equator, so each chunk spans `longitudePerChunk = 360/n` degrees of longitude.

We'll put our first row-dividing line along the equator, and stack rows of chunks northward and southward from there.

To get our first row of chunks to be square in size, we want the y coordinate of their top line to come out to the same value as `longitudePerChunk`, and their centers at half that.

```
firstRowTopLatitude = Mathf.Atan(longitudePerChunk * Mathf.Deg2Rad) * Mathf.Rad2Deg;

firstRotCenterLatitude = Mathf.Atan(longiduePerChunk * 0.5f * Mathf.Deg2Rad) * Mathf.Rad2Deg;

```

And we can generalize this. The `i`th row of chunks (starting from 0)...

* Runs from `bottomLatitude[i] = Mathf.Atan(longitudePerChunk * i * Mathf.Deg2Rad) * Mathf.Rad2Deg`
* ...up to `topLatitude[i] = Mathf.Atan(longitudePerChunk * (i + 1) * Mathf.Deg2Rad) * Mathf.Rad2Deg`
* ...centered at `centerLatitude[i] = Mathf.Atan(longitudePerChunk * (i + 0.5f) * Mathf.Deg2Rad) * Mathf.Rad2Deg`

This gets you even spacing of lines/rows of chunks on your 2D plane. Note though that each chunk represents an ever-diminishing amount of surface area on the original globe. (Because the globe gets smaller and smaller in circumference as we move toward the poles, but our projection is forcing it to maintain the same width on the 2D plane, and scaling the vertical to match conformally)

You can compute the effective scale factor at a given chunk by the formula

```
scale = 1f/Mathf.Cos(centerLatitude * Mathf.Deg2Rad);

```

For for instance, for `n = 128`, our first row has an average scale around 1.0003x. By the tenth row above the equator, our map scale is up to 1.1x. By the time we reach Canada around the 24th row, it's 1.5x. We hit 2x scale by the time we get to Yellowknife around row 40, and it keeps accelerating from there. Alert is up around row 145, where the scale is over 7x.

---

You could also switch to something like an equirectangular projection, and use constant latitude & longitude strides between chunks. Here the challenge is that the scaling you encounter is non-uniform: each span counts for less and less distance horizontally as we approach the poles, while the vertical scale stays the same.

Or you could use still other map projections like Gall-Peters or any of the other hundreds of options. ;) Selecting one would require more details about your application and needs.
> 2 votes

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


# Question
Title: Lua Unknown error when typing something in Zerobrane studio IDE
What is this weird error that I am getting when I typing something in the Zerobrane studio IDE? It crashes my IDE. But The game project compiles and runs fine.

When I turn off "Autocomplete Identifiers" from Edit menu, then the error doesn't come up.

Also, I searched entire google and facebook for some help or solution but no luck at all.

# Answer
This is a bug in the autocomplete logic in the IDE, which has been fixed in the repository.
> 1 votes

---
Tags: lua
---


# Question
Title: How do games that generate the world by noise handle physics on the server?
I keep thinking about what it is like to do the physics on the server, so that it is authoritative, and thus avoid cheating, in a game that manages the world by noise, ie the collisors are being generated from the player walking. If the server also generates the world, how do you deal with several players? I can not imagine that it manages the server-side world to give the last word, because if a player is far from each other, they would be in different chunks, so the game would have to run the algorithm to generate for each of those chunks.

Or is it simply ignored, and the server is not authoritative in this type of game (minecraft, terraria, No Man's Sky, or any other that generates logic by noise)?

The problem of not doing this on the server is that players can cheat and send what features are where they are not or which mountains no longer collide among others.

# Answer
> and the server is not authoritative in this type of game

Server should always be authoritative and handle all physics and interactions. Clients can run same logic on their side and then just do small corrections if they receive different state from server but server has last say what's correct. Really good article on that topic is Source Multiplayer Networking article.

> If the server also generates the world, how do you deal with several players?

You generate world as they explore it. You need to generate world server-side and send that data to client-side. Not sure about other games but Minecraft does exactly that. If you overload your server (TPS lag) or there's network lag, new chunks simply won't appear and if your character moves into them, it will start glitching, falling into void and such. If you have multiple characters exploring world at the same time, you just need to generate terrain at 2 different locations.

Terrain generated using noise can be generated in chunks. When implementing the algorithm, you need to choose chunks that are small enough that they don't cause performance issues but still big enough so that player doesn't see edge of terrain.
> 1 votes

---
Tags: physics, networking, noise
---


# Question
Title: How to find the possible directions to move next?
I don't want to find the shortest way and not moving in diagonals. The start position and end position are both on the edges walls so in the start i can't move back and in the end i can't move forward (depending on what direction the player is facing when getting to the end position ).

I want to move only left,right,forward but randomly. Randomly i mean that in the start i have only 3 directions possible moves: Forward,Left,Right so i want to store the 3 directions and then to pick one random direction for example Left to rotate the player facing to the left and then moving to the waypoint on the left the nearest waypoint on the left.

Now if he moved left now he have two directions to move right or keep forward and again to pick random direction from this two.

I want that the player will never go back to the last waypoint he visited.

So in any case the player will have 2 or 3 directions to move and each time to pick random direction to move to.

The red is the start position the blue is the end position. So i want to create a random path from the red to the blue.

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

public class PathFinder : MonoBehaviour
{
    private Transform start;
    private Transform end;

    public void FindPath()
    {
        GenerateStartEnd();
        GenerateRandomPath();
    }

    private void GenerateRandomPath()
    {
        GridGenerator gridgenerator = GetComponent<GridGenerator>();

        List<float> distances = new List<float>();
        List<float> rotations = new List<float>();

        for (int i = 0; i < gridgenerator.allBlocks.Length; i++)
        {
            var distance = Vector3.Distance(start.localPosition, gridgenerator.allBlocks[i].transform.localPosition);
            if (distance == 1.5f)
            {
                var angle = Vector3.Angle(start.localPosition, gridgenerator.allBlocks[i].transform.localPosition);
                rotations.Add(angle);
            }
        }

        distances.Sort();
    }

    void SmoothLook(Vector3 newDirection)
    {
        start.rotation = Quaternion.Lerp(start.rotation, Quaternion.LookRotation(newDirection), Time.deltaTime);
    }

    private List<Vector3> GenerateStartEnd()
    {
        GameObject walls = GameObject.Find("Walls");
        List<Transform> wallsParents = new List<Transform>();
        List<Vector3> startEndPos = new List<Vector3>();

        foreach (Transform child in walls.transform)
        {
            wallsParents.Add(child);
        }

        for (int i = 0; i < 2; i++)
        {
            wallsParents.Remove(wallsParents[Random.Range(0, wallsParents.Count)]);
        }

        var childsWall0 = wallsParents[0].GetComponentsInChildren<Transform>().ToList();
        var childsWall1 = wallsParents[1].GetComponentsInChildren<Transform>().ToList();
        childsWall0.RemoveAt(0);
        childsWall1.RemoveAt(0);

        start = childsWall0[Random.Range(0, childsWall0.Count)];
        end = childsWall1[Random.Range(0, childsWall1.Count)];
        startEndPos.Add(start.position);
        startEndPos.Add(end.position);

        start.GetComponent<Renderer>().material.color = Color.red;
        end.GetComponent<Renderer>().material.color = Color.blue;

        return startEndPos;
    }
}

```

In GenerateStartEnd i pick two random walls. Then i'm getting the children of each wall the blocks(cubes). I remove the parents. Then i pick random block from each wall childs. I set the start and end.

Then in GenerateRandomPath this is where i'm trying to generate the random path between start and end. This is the whole part of the random path:

```
private void GenerateRandomPath()
    {
        GridGenerator gridgenerator = GetComponent<GridGenerator>();

        List<float> distances = new List<float>();
        List<float> rotations = new List<float>();

        for (int i = 0; i < gridgenerator.allBlocks.Length; i++)
        {
            var distance = Vector3.Distance(start.localPosition, gridgenerator.allBlocks[i].transform.localPosition);
            if (distance == 1.5f)
            {
                var angle = Vector3.Angle(start.localPosition, gridgenerator.allBlocks[i].transform.localPosition);
                rotations.Add(angle);
            }
        }

        distances.Sort();
    }

    void SmoothLook(Vector3 newDirection)
    {
        start.rotation = Quaternion.Lerp(start.rotation, Quaternion.LookRotation(newDirection), Time.deltaTime);
    }

```

The logic is simple find what directions you can move pick random direction move one waypoint in that direction don't stop continue to the next random waypoint. The next waypoint can be the nearest or even far away i don't mind but once he is reaching to the next waypoint find the directions pick random one and rotate and move to that direction to another rndom waypoint on this direction.

And son on until the player will get to the end. And i don't mind if the path will be long.

I'm just not sure how to translate it to the script.

allBlocks is GameObject\[\] array containing all the grid blocks(cubes).

# Answer
> 1 votes
If I understand correctly, you wish to implement random walk but prevent agent from visiting the same spot again. Agent also can't move backwards. If that's so, that's not possible. If agent can't visit same spot again, it is not guaranteed it can find the exit. At the end of answer I'll outline what you can do to improve that but first let's discuss random walk.

Since you are already using cubes, I assume these cubes also have colliders attached, right?

Each time you wish to decide on agent's next move, you can find available spots like this. I assume distance between cubes is 1.5.

```
// Array of forward, left and right directions
var availableDirections = new Vector3[]{Vector3.forward, Vector3.left, -Vector3.left}
// Map them to points around agent, 1.5 is distance between cubes
.Select(direction => transform.position + direction * 1.5f)
// Filter points that lie inside cubes, this assumes size of cube is 1
.Where(spot => Physics.OverlapBox(spot, Vector3.one * 0.5f).length > 0)
.ToArray();

```

Then just take random direction from all available directions.

```
var direction = availableDirections[Random.Range(0, availableDirections.Length-1)];

```

To check if you are currently at exit, you can use tags. First tag an exit in `GenerateStartEnd` method like this:

```
end.tag = "End";

```

and then when you move your agent, use OverlapBox to get all colliders at that point and check their tags.

```
if(Physics.OverlapBox(transform.position, Vector3.one * 0.5f)
  .FirstOrDefault(collider => collider.gameObject.tag == "End")
     != null)
    // We are at exit

```

To solve the problem of not getting to the exit because it is completely blocked with visited cubes, you have 2 options. You can either remove that rule or always choose exit if your agent is next to it. When you are selecting availableDirections, you also need to check if any of those colliders have `tag == "End"` and if it does have, you need to select that one instead of random.

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