# Question
Title: How do I sign up and download CryENGINE?
I cannot sign up for Cryteks CryENGINE, at this site. When I click on the "sign up and download" button, nothing happens. I would ask this on their forums, but for that, you need an account.

How do I sign up and download CryENGINE?

# Answer
In my previous experience, the CryENGINE sign up page has its flaws. In summary of this example, the best solution you have is to try accessing the site from a different web browser.

Further matters of housekeeping may improve your usability:

If all matters fail, I have since found means to contact Crytek without having an actual account. You can email Crytek in regard to CryENGINE issues at *cryengine@crytek.com*.
> 1 votes

---
Tags: cryengine
---


# Question
Title: How to stretch screen image to fit higher res monitors set to lower resolutions with Unity?
Using `Screen.SetResolution(width, height, windowMode);` , how might I stretch the image to match the monitor size? I've noticed this problem occurs both with this line of code and also the default unity configuration launcher.

No body seems to discuss this issue which is odd to me.

# Answer
If I was using this as a background image for instance. I would use a larger resolution so it would scale down on devices with lower res rather than up and pixelate.
> -1 votes

# Answer
You have to set Image anchoring and require to mess with **canvas Scalar**.

And you have to remember that

> UI elements are by default anchored to the center of the parent rectangle. This means that they keep a constant offset from the center.
>
> If the resolution is changed to a landscape aspect ratio with this setup, the buttons may not even be inside the rectangle of the screen anymore.

As it is a long topic, i will recommend you the unity official tutorial **Designing UI for Multiple Resolutions**
> -1 votes

---
Tags: unity, c#, resolution, screen
---


# Question
Title: Why is Unity ignoring my camera on Android?
I am making a TV remote app for a specific android device (the Pixel XL, 1440x2560 resolution). However, when I put the app on my phone, it truncates most of the app.

Here's what it should look like:

Here's what it ends up looking like:

My game is forced in portrait, and I want to keep it that way. I have tried rotating the canvas, but that does nothing. The Android app also seems to ignore the main camera; I think it is just using the canvas.

I tried many different things, including changing the scaling and setting the anchors. None of this had any effect. I have even set the editor Game window to the target resolution, but it appears to work via the editor.

Why is Unity ignoring my camera on Android?

# Answer
It is truncating; actually, your UI is not responding to the resolution of your device. You have to set its anchoring and scaling. I would recommend you read the Unity guide for "Designing UI for Multiple Resolutions"

For a reference, this what you have to change:

> In the Canvas Scaler component, you can set its UI Scale Mode to Scale With Screen Size. With this scale mode you can specify a resolution to use as reference.
>
> **...**
>
> When the screen size is changed to a larger or smaller resolution, the buttons will also remain anchored to their respective corners. However, since they keep their original size as specified in pixels, they may take up a larger or smaller proportion of the screen. This may or may not be desirable, depending on how you would like your layout to behave on screens of different resolutions.
> 1 votes

# Answer
There's so many possibilities for your problem. Basically, you can try these and if it will not work then you should to give more information about your scripts components etc.

Check your **Canvas**' **UI Scale Mode**, it should be **Scale With Screen Size**

If it is then check your sprite what's look like in the Inspector. Attention to **Pixel Per Unit** factors.

If everything is okay then check the Canvas-UI element's **anchor**. And see the spread of UI elements (like buttons) in the screen.

Did not works ? Give us to more info and let's write a camera script.
> 0 votes

---
Tags: unity, camera
---


# Question
Title: How do I check the performance of my apk?
I have developed an app with Unity 5.2 for the Android platform. The app is running perfectly, but it's loading time is about 7 to 10 seconds, at least, on my Samsung S5.

The first scene that takes time to load contains 6 canvases for different UI purposes. It is mandatory for me to retain these 6 canvases, as my code relies on them. I can't go back from here.

How do I check the performance of my apk, and find the source of my problem?

# Answer
`Canvas` affects performance, but not as much as particles, wrong shaders and too many graphics. If the loading time is \>7 - profiler is the best option, because you probably have some RAM/draw problems.

From Unity Forums:

* Make sure to disable Mobile Data on your Android device.
* Connect your Android device to your WiFi network.
* Check the "Autoconnect Profiler" checkbox in Unity's build settings dialog.
* Attach your device to your Mac/PC via cable and hit "Build & Run" in Unity Editor.
* When the app launches on the device, open the profiler window in Unity Editor (Window-\>Profiler)
* If the Unity Editor fails to autoconnect to the device, select the appropriate device from the Profiler Window Active Profiler drop down menu.
> 4 votes

# Answer
There's more than one way to go about testing performance of your game but you usually want to use the Unity's built-in profiler, which has a manual here.

This allows you to see how much of each resources your game is using. You need to dive into the details below and see what's using what, and then optimize by working around the problems or optimizing your code if necessary.

Now, the first way to use the profiler is to just run the game on your computer and look at the results there. This will probably not be very useful by itself since your CPU is probably (and hopefully) much more powerful than your phone's or tablet's. So, you need to limit the CPUs that Unity uses while testing (don't forget to let Unity use all of them when you're done testing). This method is usually much faster than the second one.

The second method would be to use your phone. Either connect your phone to your computer and just use the build and run option Unity provides or send the APK to your phone, install the game and then connect your phone to your computer, then use the profiler to connect to your device. Both will let you test the performance of your game but both are slower to test the performance (in terms of the time it takes from "ready to test the game" to "actually testing the game") than the first method, which allows you to stop the program and then start it again without waiting for a build and an APK installation.
> 1 votes

---
Tags: unity, performance
---


title: Sprite is not showing in game

text:
# Question
Title: Sprite is not showing in game
I'm new to unity and started learning for 1 week.

But when I add a Sprite and run the game (or check the camera view) I can't see it.

Check this GIF. https://i.gyazo.com/a54e69096bbd4ef629dcf82b7f90124d.gif

or MP4 https://i.gyazo.com/a54e69096bbd4ef629dcf82b7f90124d.mp4

# Answer
> 4 votes
It's because the Z position of the `Main Camera` is 0, the same as the sprite's one.

Set the Z position of the Camera to a negative value (like the default at -10), and you'll be able to see the sprite rendered by the camera.

---
Tags: unity
---


# Question
Title: Left-handed version of the reversed depth projection with infinite far plane
Let's say that I have standard left-handed `WorldToView` and `ViewToScreen` row-major matrices in the same vein as the DirectX D3DXMatrixPerspectiveLH functions, like so:

```
EXVector vView = NormalizeVector(LookAt() - m_Position);

float fDotProduct = DotProduct(m_WorldUp, vView);

EXVector vUp = NormalizeVector(m_WorldUp - fDotProduct * vView);

// Generate x basis vector (crossproduct of y&z basis vectors)
EXVector vRight = CrossProduct(vUp, vView);

// Generate the matrix
row0.Set(vRight.x, vUp.x, vView.x, 0);
row1.Set(vRight.y, vUp.y, vView.y, 0);
row2.Set(vRight.z, vUp.z, vView.z, 0);
row3.Set(-DotProduct(m_Position, vRight),
         -DotProduct(m_Position, vUp),
         -DotProduct(m_Position, vView), 1);

EXMatrix mWorldToView(row0, row1, row2, row3);

```

Here's the left-handed `mViewToScreen` / projection matrix:

```
float zNear  =    0.001f;
float zFar   = 1000.000f;
float Aspect = DisplayHeight() / DisplayWidth();

float sinfov, cosfov; qsincosf(VFOV() / 2, sinfov, cosfov);
float cotfov = cosfov / sinfov; // cos(n) / sin(n) = 1/tan(n)

float w = Aspect  * (cotfov);
float h =   1.0f  * (cotfov);
float Q = zFar / (zFar - zNear);
float R = -Q * zNear;

row0.Set(w, 0, 0, 0);
row1.Set(0, h, 0, 0);
row2.Set(0, 0, Q, 1);
row3.Set(0, 0, R, 0);

EXMatrix mViewToScreen(row0, row1, row2, row3);

```

Many things like map/object culling depend on this fact:

```
// View to cull matrix
Q = (       zFar + zNear) / (zFar - zNear);
R = (2.0f * zFar * zNear) / (zFar - zNear);

row0.Set(w, 0, 0, 0);
row1.Set(0, h, 0, 0);
row2.Set(0, 0, Q, 1);
row3.Set(0, 0, R, 0);

EXMatrix mViewToCull(row0, row1, row2, row3);

```

Does anyone know how to derive the infamous "*reverse depth with infinite far plane*" from the original blog post for `mViewToScreen` and `mViewToCull`? Every single reference I have found (nlguillemot and nVidia, for example) is in the right-handed space.

Normally I am able to figure things out visually, but 4D matrices are a headache.

# Answer
Well, I feel stupid now. Turns out I had to use a positive `1` in the last member of the third row instead of the `-1` displayed in the right-handed examples, that fixes it. The best thing being that I don't even have to touch the cull matrix.

This sign flip was one of the first things I tried, but didn't work because the solution was mixed with other problems. I have just found it again by accident while reverting my changes and after testing every other combination you can imagine:

```
row0.Set(w, 0,     0,  0);
row1.Set(0, h,     0,  0);
row2.Set(0, 0,     0,  1 /* -1 */);
row3.Set(0, 0, zNear,  0);

EXMatrix mViewToScreen(row0, row1, row2, row3);

```

And, of course, remember to depth-test your fragments with `GL_GREATER` (or `GL_GEQUAL`) instead of `GL_LESS` (or `GL_LEQUAL`) and clearing depth to `0.0f`, instead of `1.0f` (which is the default value for the horizon). That's all the same for everyone.

Pair that with a floating point buffer and you should have improved depth precision and no far clipping.
> 1 votes

---
Tags: opengl, directx, matrix, projection, depth-buffer
---


title: How can I dissuade alliances?

text:
# Question
Title: How can I dissuade alliances?
I'm designing a game where players are able to form alliances with each other.

The game has two winning conditions: When all other players are eliminated, the remaining player wins; or if all the teams work together to solve the problem that was set them against each other in the first place, then they all win.

I'd like to encourage the single player victory, as it's more fun, but I don't want to flat-out remove the cooperative victory.

How would I go about discouraging players from attempting to cooperate with each other?

One idea I had was to make alliances a vector for mistrust - alliances might be able to steal items from each other, for example.

For some small amount of context: the game involves capturing territory and destroying territory belonging to other players. When a player runs out of territory they are eliminated.

Cheers for any suggestions!

# Answer
So going purely based off the information you have provided to us so far I think you have a few options (and the ones I have are by no means all your options).

First I would like to point out this sounds a lot like the online game hexagor.io.
Capturing territory, and destroying opponents', with the option for alliances.

* Based off of that game, a pretty simple thing alliances give you is that you cannot attack/steal territory from others. As you already mentioned, stealing would be a good way to discourage this because if you let your guard down, trusting another player, they could begin to steal your territory from a possibly vulnerable front.
* A way to discourage alliances would be to implement some sort of basic economy in your game and have their be a cost to maintaining an alliance with other players.
* Depending on the scope and depth of this game, potentially something like espionage could be incorporated and allow you to siphon secrets or other information from an 'ally' that you could trade to your real allies in other places.
* Another way to encourage and discourage alliances would be to "remove" the cooperative victory. Make it so that although you can work together, and maybe become to final two or more players, there can be only one winner and force them to fight against each other. (Or if you want to simplify that, just have a score system and the best score in the alliance is given 1st place).
* You also stated that your single player win condition is more fun and the cooperative one is fighting against some other condition (AI or environmental perhaps?). That being said, you should try to emphasize the factors of playing solo that are more enjoyable. I wouldn't exactly say make cooperative modes harder, because that may just remove any interest in it entirely.
* Lastly a way that may only work depending on the mechanics of the core gameplay (as was stated, more would help us better provide examples), you could make some sort of negative multiplier per the number of allies you are maintaining relationships with. For example, the more allies you have, the less of a standing army you can maintain.

As I said in the beginning, this is not a complete list, but it's some ideas that I thought of or I drew from other games. Without some more information about what you are planning on building, it'll be harder for specific examples to be provided. As of right now, your game simply sounds like the web browser game hexagor.io as I listed in the start.
> 1 votes

# Answer
I think all you need are two incentives:

1) A solo victory grants more of whatever is good in your game to the victor

2) Backstabbing a team-mate gives a bonus of some kind, while removing the benefits of having allied with that team mate. The bonus should slightly outweigh the benefits. The timing of this should be a factor e.g. it would be benificial to ally while there are a large amount of opponents, but once there are only a few players it makes sense to be the betrayer (because of point 1) + whatever other benefits you want to code in
> 1 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: Java - simultaneous ground and wall collision
I've been working on a Line2D based collision system:

```
public void update() {
    for (int i = 0; i < lines.size(); i++) {
        line = lines.get(i);
        if (line.line.intersects(player.hitbox))
            playerCollision();
    }
}

public void playerCollision() {
    if (Math.abs(line.angle) <= 45) {
        player.jumped = false;

        if (player.speedY > 0)
            player.speedY = 0;

        // inefficient?
        while (line.line.intersects(player.hitbox)) {
            player.centerY--;
            player.hitbox.setRect(player.centerX - player.WIDTH / 2, player.centerY - player.HEIGHT / 2,
                    player.WIDTH, player.HEIGHT);
        }

        player.centerY++;
        player.hitbox.setRect(player.centerX - player.WIDTH / 2, player.centerY - player.HEIGHT / 2, player.WIDTH,
                player.HEIGHT);

    } else if (line.angle > 0) {
        while (line.line.intersects(player.hitbox)) {
            player.centerX--;
            player.hitbox.setRect(player.centerX - player.WIDTH / 2, player.centerY - player.HEIGHT / 2,
                    player.WIDTH, player.HEIGHT);
        }

    } else if (line.angle < 0) {
        while (line.line.intersects(player.hitbox)) {
            player.centerX++;
            player.hitbox.setRect(player.centerX - player.WIDTH / 2, player.centerY - player.HEIGHT / 2,
                    player.WIDTH, player.HEIGHT);
        }
    }
}

```

Overall, it works pretty well. There is, however, one problem I haven't been able to fix. When the player collides on a place where a wall and the ground meet, both the ground and wall collisions are executed, however, only one should be.

The result is that the player is abruptly pushed off a cliff when approaching one, or that the player is abruptly moved up when jumping alongside a cliff.

When approaching a cliff:

After one step to the right:

I've been able to come up with a method to determine which collision should be executed:

```
if (player.hitbox.getMaxY() - player.speedY > line.line.getY1())
    // execute wall collision only
if (player.hitbox.getMaxY() - player.speedY <= line.line.getY1())
    // execute ground collision only

```

However, I haven't been able to come up with how to implement this. I can't check all lines for collision first and execute the collision later, as the collision is executed per line. Does anyone know how I can fix my collision system?

P.S. I'm a beginning game developer, so my collision detection system might be bad or inefficient. If there's a better way to do this, that doesn't have the same problems, I'd love to hear about it. Please keep in mind, though, that I'm trying to keep the code simple and efficient.

# Answer
> 1 votes
I think the key to fixing this situation without writing all new collision code is to identify the "cliff" situation while inside `playerCollision()`.

The first step would be to determine which line endpoints are part of a cliff edge - either the wall or the ground at the top of it. This is a pretty simple pre-processing step. As you load or create your level data, search the list of lines for wall and ground segments that make cliff edges. Store with each Line2D whether or not each of its ends is part of a cliff.

The second step is inside `playerCollision()`, where you need to detect that the player is touching a cliff endpoint. This is also pretty simple, just test whether each line endpoint is part of a cliff, and if it is test whether the player collision shape contains that endpoint. If both are true, then the player is on a cliff edge.

Finally, use your method to decide whether the current segment should push the player or not.

Note 1: I would test my solution by manually adding the cliff information to a simple level. Once the rest of the code works, I'd switch to automating the marking-line-ends-as-cliffs process.

Note 2: Your collision code seems fine, especially for small levels like your example image. If levels get larger and the collision code becomes too slow, you can look for ways to optimize the outer loop and still keep `playerCollision()` as it is.

---
Tags: java, collision-detection
---


# Question
Title: Libgdx draw a sprite in top of an isometric tile
I have this isometric map and im using `IsometricTiledMapRenderer` to render the map I have a `OrthographicCamera`. I know where each tile is in the isometric map, but the isometric map is kinda rotated?

So I was wondering how to convert Map Coordinates to Isometric and viceversa?

Here I tried to draw a color cube in each tile coordinates....

---

Thanks in advance, I have been struggling with this for 2 days, and my lack english vocabulary isnt helping with the research, please some one point me to something

# Answer
> 1 votes
Looking at the source code for the Isometric renderer I found this piece of code (slightly edited):

```
private void init () {

    // create the isometric transform
    isoTransform = new Matrix4();

    isoTransform.idt();

    // isoTransform.translate(0, 32, 0);

    isoTransform.scale((float)(Math.sqrt(2.0) / 2.0), (float)(Math.sqrt(2.0) / 4.0), 1.0f);

    isoTransform.rotate(0.0f, 0.0f, 1.0f, -45);

    // ... and the inverse matrix
    isoTransform.inv();

}

private Vector3 translateScreenToIso (Vector2 vec) {

    Vector3 screenPos = new Vector3(vec.x, vec.y, 0);

    screenPos.mul(isoTransform);

    return screenPos;

}

```

Try using this to convert your screen coordinates to Isometric coordinates.

---
Tags: libgdx, isometric
---


# Question
Title: Should I use "conventional" colors to represent item rarity?
I'm making a new RPG that has loot. In fact, a majority of the game is based around loot. It's going to have colored borders to denote the rarity of the loot as it's drawn.

WoW uses Grey, White, Green, Blue, Purple, Orange and some others. GW2 uses Gray, Black, Blue, Green, Yellow, Orange, Pink, Purple. The colors don't match but you can see some distinct overlap.

I'm wondering if those colors are important or intuitive to users understanding of the rarity or if they can be messed with? If they can be changed how do you determine what colors to put in what order?

For instance, if I went with White, Blue, Green, Yellow, and Red, would that be fine as long as I made it clear in other ways or would those colors be confusing?

# Answer
> 53 votes
Generally when there's a common convention that your audience may already be familiar with, the question isn't whether it's mandatory, but whether there's any reason to deviate from it.

If you use a colour scheme compatible with the ones used in WoW, GW2, Destiny, etc. then players who have played one of those games will have one less thing to learn to understand your game. And players who play both your game and one of those others will be less likely to get mixed up and make mistakes than if you arbitrarily swapped some of the colours.

That said, if you have a compelling reason to change the colours (say your entire world is under "the violet curse" and all low-grade common items have to be purple for narrative reasons), there's nothing to prevent you from doing so.

In the absence of such a reason though, sticking with a similar colour sequence costs nothing, and potentially gets you some ease-of-use wins, so sticking with the familiar convention is often worthwhile.

# Answer
> 21 votes
The advantages to sticking with convention are: it works, and users are already familiar with it. The disadvantage is that you may be ignoring ways to improve and be unique.

But on this subject, there's not much convention. This topic is covered at Giant Bomb and TVTropes, and from their analysis, generally grey/white items are the lowest tiers, but after that there's not much consistency. Even the two games that did the most to establish the concept - WoW and Diablo II - are inconsistent in using the green colour: the former has green as a lower tier, whereas the latter has green at a very high tier.

Besides, the colours themselves don't inherently fall into a hierarchy of rarity or desirability. You might be able to use the spectrum, but note that most games don't do this. For example, a typical game might have, from common to rare, green \> blue \> purple, but then they jump back to yellow \> orange as the highest tiers. Colour theory won't help you much either, apart from telling you that very dull colours, like grey or brown, are less attractive.

So really it doesn't matter too much which exact colours you use. Pick one game to copy, or pick whatever scheme makes the most sense to you and your players.

# Answer
> 1 votes
Generally, I would suggest using muted colors for more common items and bright colors for rarer items. The benefits of that are that color-blind people still have saturation cues to work from, item rarity is instantly recognizable even if someone's monitor settings are off, and it's intuitive in the sense that common items are less interesting and eye-catching than rare items.

I would definitely stick to a system with limited rarity levels. You mention 5 and that seems fine, but any more than 4-5 just gets complicated. The saturation approach also helps here, though--users know where an item lies on the scale even if they haven't seen that color before.

One further benefit is that you can limit the hue region you pull from for rarity indicators, opening up other hue/saturation regions for other indications. For instance, in Lord of the Rings Online, items had rarity, but then they introduced Legendary items. They were a different type of item all together, so their name color indicated that they were Legendary rather than indicating their rarity. So, for instance (and this isn't a suggestion, just an example), if you wanted to restrict your hue region to yellows and oranges, and you were going to implement the WoW scale of rarity, you could have:

* Poor: grey-brown
* Common: russet
* Uncommon: a dark-ish orange
* Rare: yellow-orange
* Epic: sunny yellow

Then, if you later wanted to implement, say items that could be combined with other items, or items that had lore-relevant significance, or items that also had specific effects beyond the regular stat boots, you could set them off with different colors and they would be instantly recognizable.

OTOH, I suppose you could scrap the color theme all together and give the item pop-up a plain-to-fancy border to indicate rarity, also. Or you could just make it white with purple hair and three blue diamonds and be done with it. (Sorry, my kids have been watching a lot of MLP and I couldn't help myself.)

# Answer
> -4 votes
You shouldn't use any colours. Colouring items to represent their rarity just teaches and encourages players to look at nothing but the colour.

---
Tags: color, user-experience
---


title: Unity 2D animation issue

text:
# Question
Title: Unity 2D animation issue
I have this weird animation bug in Unity that I believe is how Unity handles the frame. I dont know how to show the image so I'll do my best to explain it. So I put a bunch of 2D sprites in a sequential order right and I made a timer in my code to play animation whenever. The weird thing is that it does complete the whole animation but then it goes back to the first frame and ends it. I tried changing the timer to every number possible but it just does the same thing or repeats the animation twice when I increase my timer.

Here's the code :

```
using UnityEngine;
using System.Collections;

public class PlayerAttack : MonoBehaviour {

private bool attacking = false;//Switches for all attac combo
private bool attacking2 = false;
private bool attacking3 = false;

//attack 1 stats
public float attackTimer = 0f;
public float attackCD = .3f;

public Collider2D attackTrigger;//Referring to our attack collider

Animator anim;

// Use this for initialization
void Start () {
    anim = GetComponent<Animator> ();
    attackTrigger.enabled = false;//Disable our collider at start
}

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown ("space") && !attacking)
    {
        attacking = true;//We are attacking
        attackTimer = attackCD;//assign variables

        attackTrigger.enabled = true;//Enabled our trigger collider
    }

    //If we are attacking
    if (attacking) {
        //Check if our timer is greater than zero
        if(attackTimer > 0){
            attackTimer -= Time.deltaTime;//Decrease our timer
        }else
        {
            attacking = false;//We arent attacking anymore
            attackTrigger.enabled = false;
        }
    }
    anim.SetBool ("Attack", attacking);
 }
}

```

# Answer
There's no need to attacking variable. it should work.

```
public class PlayerAttack : MonoBehaviour {

private bool attacking = false;

public float attackTimer = 0f;
public float attackCD = .3f;

public Collider2D attackTrigger;
Animator anim;

// Use this for initialization
void Start () {
    anim = GetComponent<Animator> ();
    attackTrigger.enabled = false;
    attackTimer = attackCD;//       assign variables
}

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown ("space"))
    {
         anim.SetBool ("Attack", true);

        attackTrigger.enabled = true;
         if(attackTimer > 0){
            attackTimer -= Time.deltaTime;//Decrease our timer
        }else
        {
            attackTrigger.enabled = false;
             anim.SetBool ("Attack", false);
        }
    }

}

```
> 1 votes

# Answer
I believe what you're looking for is the animation's WrapMode. Go to the inspector for the Animation file. Click the menu icon next to the "padlock" icon in the very very top-right corner. Change it to `Debug` and you should see "Wrap Mode" as highlighted here:
> 1 votes

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


# Question
Title: Dynamically change shader syntax with the help of C++
I'm starting with the programmable pipeline and the shaders in C++ for OpenGL 3.0+, i would love to be able to change some settings on the fly, for example replacing a function with another function, supposing that i have a shader with an operation like

```
var = A + B

```

my goal is replacing `+` with any other operation on the fly with my C++ program, maybe with a GUI, but in general terms with C++, the problem is that until now i'm able to run a shader only after compiling it, so i have something like a static approach.

The same goal applies to the values of the vars that i would also like to change through C++.

It's possible with a programmable pipeline? I'm not interested in performance, just if is possible for the C++ to dynamically communicate and exchange data with the OpenGL pipeline.

# Answer
I'm not sure exactly what you mean.

You can certainly create a new shader string, compile it into a new shader object, and link it into a new program object. But you can't *modify* an existing shader's source code.

If you just want to change what gets called when, you can use an `if` statement in your shader based on `uniform` variables. Though this can get out of hand if you do it a lot.

GLSL 4.00 adds the ability to define multiple subroutines in a shader and dynamically (meaning, post-linking) pick which one to execute. But that's about it.
> 3 votes

# Answer
**Assumption: You have shader code in the variable.**

You actually can do something that accomplishes this. Change the source code of the given shader, recompile it and run the new one.

My use of this :

```
char s1[] = "#version 430 core\n\
                #define SIZE ";
char *s2 = new char[sizeof(itoa(256, s2, 10))];
char computeShaderSource[] = {"rest of the shader code here"}
char *finalSource = new char[sizeof(s1) + sizeof(s2)+ sizeof(computeShaderSource)];
sprintf(finalSource,"%s%s\n%s",s1,s2,computeShaderSource);

```

I really dont guarantee that this is the best practices.

From the performance point of view, it will depend on how many times you will change this.
> 0 votes

---
Tags: c++, opengl, shaders, pipeline
---


# Question
Title: In Unity, does a reference delegate clear out when its parent GameObject is destroyed?
If I have a GameObject with a component like some:

```
class SomeComponent : MonoBehaviour
{
    System.Action DoStuff;
}

class SomeOtherComponentInAnotherGameObject
{
    public GameObject ObjectWithThatComponent;
    void Start()
    {
        ObjectWithThatComponent.GetComponent<SomeComponent>().DoStuff += SomeFunc;

        Destroy(ObjectWithThatComponent);

        // is there still a reference to SomeComponent somewhere?
    }
}

```

I'm getting some odd behaviour/random crashing when deleting this stuff but I'm not sure if it's being caused by these delegates.

# Answer
> 2 votes
**"In Unity, does a reference delegate clear out when its parent GameObject is destroyed?"**

Very little happens in managed land when a UnityEngine.Object is destroyed. The object will compare as equal to null from that point on, but it remains present until all references to it go out of scope, after which the garbage collector can pick it up. No MonoBehaviour methods like Update or OnCollisionEnter will get called on it, so its lingering presence usually isn't noticeable unless you're accessing its fields or calling functions on it manually.

Most of the work of removing the object happens under the hood in the unmanaged engine code where we can't see it. If we want something to happen to managed code we've written when something is destroyed, we need to specify that in an OnDestroy() method or similar.

**"Is there still a reference to SomeComponent somewhere?"**

We can put this to the test in the following way:

```
public class DestructionTest : MonoBehaviour {

    System.Action DoStuff;

    System.WeakReference watchedComponent;

    void Start () {
        var testObject = new GameObject();
        var component = testObject.AddComponent<DestructionTest>();
        component.DoStuff += SomeFunc;

        // Get a weak reference to the component so we can keep an eye on it,
        // without influencing the behaviour of the garbage collector.
        watchedComponent = new System.WeakReference(component, false);

        Destroy(testObject);
    }

    // Update is called once per frame
    void Update () {
        // Two seconds in, force a garbage collection.
        if(Time.time >= 2f && Time.time - Time.deltaTime < 2f)
        {
            System.GC.Collect();
            Debug.Log("-------Garbage Collected--------");
        }

        // Report whether the other component still exists.
        Debug.Log("Alive: " + watchedComponent.IsAlive);
    }

    void SomeFunc()
    {
    }
}

```

When you run this, you'll see it print "Alive: true" for the first 2 seconds.Then the garbage collector hits and the output changes to "Alive: false"

That means the garbage collector found no (strong) references to the other component and was able to clean it up, despite our mucking with its DoStuff action. So this itself does not create a dangling reference to it, at least so far as the garbage collector is concerned.

# Answer
> 1 votes
Spot on; delegates *can* cause odd behavior if the subscribing member is removed. While I am not sure if this is always the case, they are not necessarily automatically removed during garbage collection (that is, when you delete the subscribing game object). As such, we are often told to ensure the subscriber also *unsubscribes* from the delegate. I note that this instruction is *not present* in the Unity tutorial; but it is in every secondary tutorial I have ever completed in regards to delegates and delegates in Unity

---

In the below script, we pass a reference to the target `DelegateComponent` from which we wish to subscribed to `DoStuff`. In doing so, we add a reference to the `DelegateComponent`, so we can later unsubscribe from all subscribed `DoStuff` delegates when the `OnDestroy()` method is called; for instance, when you delete your game object.

```
using System.Collections.Generic;

class DelegateComponent : MonoBehaviour
{
    System.Action DoStuff;
}

class ObjectScript : MonoBehaviour
{
    // Store reference to all linked delegateComponents; if you only ever intend
    // to subscribe to one delegateComponent, this does not need to be a list.
    private List<DelegateComponent>() subscribedDelegates;

    void Start()
    {
        // Only needed if we are instantiating a list.
        subscribedDelegates = new List<DelegateComponent>();
    }

    void OnDestroy()
    {
        for(int i = 0; i < subscribeDelegates.Count; i++)
        {
            subscribedDelegates[i].DoStuff -= SomeMethod;
        }
    }

    public void SomeMethod()
    {
        // Your subscribed logic, here.
    }

    public void Subscribe(DelegateComponent delegateComponent)
    {
        subscribedDelegates.Add(delegateComponent);
        delegateComponent.DoStuff += SomeMethod;
    }
}

```

---

If you only intend to subscribe to a single `DoStuff`, you should replace the `List<DelegateComponent>` with a single `DelegateComponent` reference. You can then omit the instantiation in the `Start()` method, and directly unsubscribe from this delegate in the `OnDestroy()` method. For completion sake, we should also use some additional logic in the `Subscribe(DelegateComponent delegateComponent)` method to account for the possibility that we were previously subscribing to a different `DelegateComponent`.

```
private DelegateComponent subscribedDelegate;

public void Subscribe(DelegateComponent delegateComponent)
{
    if(subscribedDelegate != null)
    {
        subscribedDelegate.DoStuff -= SomeMethod;
    }

    subscribedDelegate = delegateComponent;
    subscribedDelegate.DoStuff += SomeMethod;
}

```

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


# Question
Title: How to calculate a projection of 360° equirectangular slides?
My goal is to have a light source inside of a transparent sphere that has an equirectangular texture to act as a 360°-slide. I want to get the projection on arbitrary objects as a texture image on these objects in high resolution. This will happen on a webserver.

So my input should be the equirectangular and the object and optionally position of the light source and my output should be texture files of each flat surface of the arbitrary object.

What algorithms can I use to make this as simple, quick and fast-in-action as possible?

# Answer
Here's a high-level overview of the method:

1. For each object, walk through the triangles making up its mesh.
2. Compute the position of each of the triangle's vertices in world space (ie. applying any rotation / translation as needed) and subtract the light position to get a vector representing the ray of light reaching this vertex.
3. Rasterize the current triangle into your output texture using the uv texture coordinates of its vertices. This generates a collection of pixels in your output texture that the triangle covers.
4. For each rasterized pixel, interpolate the light vector from the triangle's vertices to get a vector representing the ray of light falling on this point within the triangle.
5. Convert this direction to spherical coordinates.
6. Use the latitude and longitude as texture coordinates to look up the corresponding texel in your equirectangular input texture. Write that colour to your output pixel.

As you can see, this maps readily to normal 3D rendering pipelines, using eg. WebGL or the API of your choice. Step 1 is a draw call, steps 2-3 are a vertex shader, 4 is the built-in interpolator, and 5-6 are a fragment shader.

If you specify what graphics API you plan to use, we can make the steps above concrete with the actual syntax needed.
> 1 votes

---
Tags: textures, algorithm, webgl, projection
---


# Question
Title: Can we merge multiple FBX files, using Maya, and export as a single FBX file?
I have a humanoid model which is made up of four FBX files; one is for the human, one is for the T-shirt, one is for the pants and one is for the hair. I want to merge them into one FBX, because the manner in which I am using it requires using a single FBX file to represent the character.

Can we merge four FBX files into one, using Maya, and export as a single FBX file?

# Answer
> 2 votes
Merging multiple FBX files is actually fairly easy.

1. You first need to bring all of the FBX files into Maya. As I have found out, this is fairly simple. Just open an empty scene, and drag and drop the files from a file explorer.
2. Position all of the objects in Maya. If you are unfamiliar with Maya, itself, the basic transformation principles actually work very similar to Unity. After clicking on a model, for example, you can use `W`, `E` and `R` to bring up the gizmo tools for moving, rotating and scaling, respectively.
3. Once you have all of your pieces in the desired positions, select *"Mesh \> Combine"*.
4. Export the file with *"File \> Export All"*, and be sure to select the FBX file type before you save.

That's it. Note that the object will still appear as a hierarchy of objects, when loaded into Unity, but they are all compressed into a single FBX file.

---
Tags: unity, maya, fbx, export
---


# Question
Title: Unity Network how to move noplayer object from client side
When i drag a nonplayer object from host, client can see it, but when move the object from client, host player doesnt see any changes. How can i fix it?

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

public class DragObject : NetworkBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;

void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
    offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

void OnMouseDrag()
{
    Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
    transform.position = cursorPosition;
}}

```

# Answer
> 0 votes
(Note: I'm not well versed in Unity, but I do know my way around enough networking APIs to have a reasonable amount of confidence about what's going on here)

You need to replicate the state changes you want from the client to the host. It looks like what's happening is that you're changing the host's state, and because the host has authority to replicate state to other clients, it gets replicated to everyone else. Right now when the client makes a change, it's just changing its local state and no one else in the game knows about that. Networking APIs usually have this concept of "Authority", to have at least some level of security over the game state (I can't just set the opposing players health to 0, etc).

What you want to do, is send a command from the client to the server (what's called a "Command" in Unity terminology), telling it what you want to change, then make that change on the server. The state will then get replicated to everyone, just as it would if the host had made the request itself.

Looking at the Unity networking API docs, it looks like the only way you can make a request like that from a client to the server, is to route it through your local player object. So you'd need to add a Command to your Player to make that change to your object.

See the following pages from Unity's networking docs.

https://docs.unity3d.com/Manual/UNetActions.html https://docs.unity3d.com/Manual/UNetPlayers.html

---
Tags: unity, unityscript, unity-networking, unet
---


# Question
Title: Entity Component System - Handling Input
I'm developing a using the Entity-Component model, and so far have components for position, input, graphics and a camera, and systems for rendering graphics and handling input.

All seems to be working well, and I can use my model to create a multi-player, multi-camera setup relatively easily.

Anyway, my problem is that my input system checks keypresses against each player's controls, but I'm not sure how to react to these keypresses without introducing a lot of coupling.

For example, if 'W' is pressed, I want to tell player 1 to move upwards, but that first involves some collision detection -- something I'm not sure my input system should handle.

Advice greatly appreciated!

Thanks in advance, Rich.

# Answer
> 5 votes
Input is usually more abstracted from character behaviour than that. Usually by some kind of "character controller" that translates requested state into movement/actions.

Ideally you don't want to couple that too closely to actual player input. What if in the future you want an AI behaviour tree to drive that entity? Or what if you implement networked multiplayer and you're simulating entities that are being controlled remotely?

The data a character controller is usually operating on is more closely tied to the actions that particular type of entity can perform (desired movement direction and speed, booleans to indicate whether or not particular actions are being requested, etc).

Personally for things like input, AI controllers, cameras etc, my preference is not to hang those directly off the entity itself, as you potentially might to make it more flexible to leave your options open. E.g what happens if you want to be able to dynamically switch the camera/control to another entity without destroying the old one, and have the old entity be taken over by AI? (Like in some team sports games, for example). What if you want to have a cutscene where the camera gets temporarily switched to a cinematic camera?

Collision detection and the like really don't belong on the input level. The best way to think about it in my opinion is that input is what the player/AI is asking to do. Whether or not it can do those things is irrelevant to the input system.

---
Tags: c++, input, entity-system
---


# Question
Title: What takes up more processing power between whole character models or models that are pieced together in Unity?
In terms of performance when it comes to animation what takes up more processing power: Whole character models or models that are pieced together? (1 object vs multiple objects).

I also wonder if animating multiple objects allows us to get a better overall animation quality instead of working with one object (especially if we deal with action packed scenes).

# Answer
> 2 votes
Combining several objects or animations into one will require slightly less computations (avoiding duplicated initializations, updates, etc), and will therefore have a slightly better performance.
Regarding quality, whatever solution you use, you are able to produce the same level of quality (at the expense of slightly worse performance for example if you use several separate objects).
One final aspect I think you should consider is the maintainability of your solution. If splitting your big object in several small ones makes your iteration time much faster, you should choose this option in the first place (and worry about performance only if it really appears necessary later on).

Update:

I realized you might mean you are interested in specifically comparing these cases:
\- Using a skinned model with bone animation data created in an external tool
(versus)
\- Using separate rigid models and animating then relatively to each other at run-time procedurally

As noted in the comments, depending on the complexity of your model and on the number of instances you will create, the answer will vary. Try to profile both solutions in your specific scene to find which one performs better.

Regarding quality, it also depends on the kind of model you are talking about, and on the visual style of your game.
If you aim for realistic motion-capture based character animation, I think it will be a lot of work to reproduce it procedurally, and you might prefer the "skinned model" solution.
If you are talking about animated environment models (a "merry-go-round" would be a good example), it should be easy to simulate as separate models.

---
Tags: unity, animation, performance, character, 3d-modeling
---


# Question
Title: How do I blend 2 lightmaps for day/night cycle in Unity?
Before I say anything else: **I'm using dual lightmaps, meaning I need to blend both a near and a far.**

So I've been working on this for a while now, I have a whole day/night cycle set up for renderers and lighting, and everything is working fine and not process intensive.

The only problem I'm having is figuring out how I could blend two lightmaps together, I've figured out how to switch lightmaps, but the problem is that looks kind of abrupt and interrupts the experience.

I've done hours of research on this, tried all kinds of shaders, pixel by pixel blending, and everything else to no real avail. Pixel by pixel blending in C# turned out to be a bit process intensive for my liking, though I'm still working on cleaning it up and making it run more smoothly. Shaders looked promising, but I couldn't find a shader that could properly blend two lightmaps.

Does anyone have any leads on how I could accomplish this? I just need some sort of smooth transition between my daytime and nighttime lightmap. Perhaps I could overlay the two textures and use an alpha channel? Or something like that?

# Answer
> 2 votes
So I recently tried my hand at this and ran into a lot of the same issues you guys have. The render texture solution is a bit of a red herring. I was able to solve it using multithreading pixel manipulation on a separate thread.

https://www.youtube.com/watch?v=T\_zpFk1mdCI

So ordinarily one would use `graphics.blit()` and pass the render texture in to wherever it needs to go, but lightmap data doesn't support textures, they require texture2ds. The next logical step would be to copy the data to a texture2d and then feed that to the lightmap data. This technique ruins frame rates because it is stalling the GPU to send data to the CPU, rather than just a reference to the data.

The solution is then to not use the GPU.

Light map transitions happen over a long period of time so it is not necessarily important to update the light map every frame. As a matter of fact, players probably wouldn't notice if the light maps were only updated every 20-40 minutes in game time.

So what you do is you issue the task out to the CPU on separate threads for each light map.

Ordinarily Unity does not support multithreading. But that's okay, C# does. This guy does a phenomenal job explain multithreading in Unity, so if you've never heard of it, or never knew how to multithread in Unity this is the video:

https://www.youtube.com/watch?v=ja63QO1Imck

All you need to do is make a worker thread class that varies copies of the lightmap pixel data in Color arrays, and then create a blend function.

A simple lerp from one color to the next will do.

Then create the thread, start it, and when all the lightmaps are finished in the separate threads you can copy the pixel data back into the lightmap data texture2d.

I posted some example code below. It's certainly not the fully implemented version, but it shows you the main concepts of making the class, creating the thread, and then setting the lightdata.

The other things you would have to do is call a function every so often to trigger updating the lightmaps. Also you have to either copy all of the pixel data into the worker class at start or at compile time. Good luck to anyone who finds this. I figure the op has moved on with their life, but I know other people with similar problems might stumble upon this.

```
public class work
{
    Color[] fromPixels;
    Color[] toPixels;

    public float LerpValue = 0;
    public bool Finished = false;
    public Color[] mixedPixels;

    public work(Color[] FromPix, Color[] ToPix)
    {
        fromPixels= FromPix;
        toPixels= ToPix;
        Finished = false;
        mixedPixels = new Color[FromPix.Length];
    }
    public void DoWork()
    {
        for (int x = 0; x < fromPixels.Length; x++)
        {
            mixedPixels[x] = Color.Lerp(fromPixels[x], toPixels[x], LerpValue);
        }
        Finished = true;
    }
}

IEnumerator LightMapSet()
{
    Thread workerThread = new Thread(someworker.DoWork);
    someworker.LerpValue = lerpValue;
    workerThread.Start();
    yield return new WaitUntil(() => someworker.Finished);
    mixedMap.SetPixels(someworker.mixedPixels);
    mixedMap.Apply(true);
    LightmapData someLightmapData;
    someLightmapData.lightmapColor = mixedMap;
    lightDatas = { someLightmapData};
    LightmapSettings.lightmaps = lightDatas;
}

```

# Answer
> 1 votes
There is a skybox shader that blends between two sets of skybox textures. **Think day and night cycle!**

If you want to build or animate the skybox from script, use `skyboxmaterial.SetFloat("_Blend", yourBlend)` to change the blending; can also use `SetTexture` material functions to setup or change the textures.

Video tutorial about day/night cycle: http://www.youtube.com/watch?v=FTfv9JhkmIA

The example code goes as follows:

```
Shader "RenderFX/Skybox Blended" {
Properties {
    _Tint ("Tint Color", Color) = (.5, .5, .5, .5)
    _Blend ("Blend", Range(0.0,1.0)) = 0.5
    _FrontTex ("Front (+Z)", 2D) = "white" {}
    _BackTex ("Back (-Z)", 2D) = "white" {}
    _LeftTex ("Left (+X)", 2D) = "white" {}
    _RightTex ("Right (-X)", 2D) = "white" {}
    _UpTex ("Up (+Y)", 2D) = "white" {}
    _DownTex ("Down (-Y)", 2D) = "white" {}
    _FrontTex2("2 Front (+Z)", 2D) = "white" {}
    _BackTex2("2 Back (-Z)", 2D) = "white" {}
    _LeftTex2("2 Left (+X)", 2D) = "white" {}
    _RightTex2("2 Right (-X)", 2D) = "white" {}
    _UpTex2("2 Up (+Y)", 2D) = "white" {}
    _DownTex2("2 Down (-Y)", 2D) = "white" {}
}

SubShader {
    Tags { "Queue" = "Background" }
    Cull Off
    Fog { Mode Off }
    Lighting Off
    Color [_Tint]
    Pass {
        SetTexture [_FrontTex] { combine texture }
        SetTexture [_FrontTex2] { constantColor (0,0,0,[_Blend]) combine texture lerp(constant) previous }
        SetTexture [_FrontTex2] { combine previous +- primary, previous * primary }
    }
    Pass {
        SetTexture [_BackTex] { combine texture }
        SetTexture [_BackTex2] { constantColor (0,0,0,[_Blend]) combine texture lerp(constant) previous }
        SetTexture [_BackTex2] { combine previous +- primary, previous * primary }
    }
    Pass {
        SetTexture [_LeftTex] { combine texture }
        SetTexture [_LeftTex2] { constantColor (0,0,0,[_Blend]) combine texture lerp(constant) previous }
        SetTexture [_LeftTex2] { combine previous +- primary, previous * primary }
    }
    Pass {
        SetTexture [_RightTex] { combine texture }
        SetTexture [_RightTex2] { constantColor (0,0,0,[_Blend]) combine texture lerp(constant) previous }
        SetTexture [_RightTex2] { combine previous +- primary, previous * primary }
    }
    Pass {
        SetTexture [_UpTex] { combine texture }
        SetTexture [_UpTex2] { constantColor (0,0,0,[_Blend]) combine texture lerp(constant) previous }
        SetTexture [_UpTex2] { combine previous +- primary, previous * primary }
    }
    Pass {
        SetTexture [_DownTex] { combine texture }
        SetTexture [_DownTex2] { constantColor (0,0,0,[_Blend]) combine texture lerp(constant) previous }
        SetTexture [_DownTex2] { combine previous +- primary, previous * primary }
    }
}

Fallback "RenderFX/Skybox", 1
}

```

# Answer
> 0 votes
If you know how to switch, why not to go on with creating a number of transition lightmaps on the background thread, and then enable the transitions when the lightmaps are ready?

You can also have a look at an interesting asset on AssetStore: https://www.assetstore.unity3d.com/en/#!/content/5674

I guess it includes the lightmaps blending, although I don't know the way how.

---
Tags: unity, lighting, lightmap
---


# Question
Title: What algorithm should I use for 2D pathfinding?
In my game I want to spawn a monster which would immediately calculate a path to its target. If the monster faces any new obstacles, he destroys it and goes further on the calculated way. If there is no path to the target (the way is fully blocked) he destroys everything and goes straight to the target. The target is this Yellow cube. Maze is made from black cubes. And available path is in white. The monster can't go crosswise.

The total area width and height can be different. Here now is 12x14.

Could you help me please with formula? Given maze\_width + maze\_height + starting\_point + target\_point + all area black cubes x/y coordinates.

This is too complex for my non-mathematical head and I really want to implement this pathfinding formula in my game :)

So I need only one formula for the first once-made pathfinding, nothing more. I will use it with JavaScript.

Thanks in advance for any help!

```
const MAZE_WIDTH = 12;
const MAZE_HEIGHT = 14;
const STARTING_POINT = [0, 1];
const TARGET_POINT = [6, 6];

function get_path(maze_blocks) {
  ..
}

var maze_blocks = [[2, 1], [8, 1], [1, 7] ... ]; // not sorted
get_path(maze_blocks) // returns [[0, 1], [1, 1], [1, 2], [1, 3] ...]

```

# Answer
> 0 votes
Usually A\* is the choosen algorithm for pathfinding in videogames since it's easy to implement and yields a decent behaivour but in your case i think it's not necesary.

If you dissects your needs, you can realize that what you really want is to check the relative position of the target from the enemy, once you have this vector, since your enemy can break walls, you only have to break and advance in that direction.

Moving just toward the player's direction would be weird, so you can use a flood aproach to check what's the closest accessible tile to the player by checking the distance between both entities and move the enemy there. once you get the closest cell you can go, then you break and repeat.

EDIT: You asked for a formula but it's not that easy, we are here to help and support you, not to spoon-feed you. Is your task now to get the answers, learn some maths and implement your code understanding what you'r doing.

Keep trying mate :)

---
Tags: 2d, javascript
---


# Question
Title: MagicaVoxel - Making it look exactly the same in Unity
Am playing around with MagicaVoxel, then exporting as an obj, and importing into Unity.

What I am trying to do is make it appear exactly the same in Unity as it does in MagicaVoxel, but am not sure how. I've played with the lighting, a few different shaders, but nothing comes close to how it looks in MagicaVoxel.

Below is a screen shot of Unity and MagicaVoxel so you can see the difference. The colors in Unity just seem so dull. Looking at the sand in MagicaVoxel compared to Unity is so much brighter. I know that there is AO in MagicaVoxel, but for now I'm just trying to get the colors to be correct.

The object is using the standard shader (Unity 5.3), with the albedo set to an image...

In the Unity screen shot, it's using a basic directional light (default settings in screen shot).

Any advice?

# Answer
> 1 votes
I'd start with increasing intensity of ambient light to a much higher value, to make unlit sides of voxels brighter. Compare vertical faces on the left sides of the screenshots: they are much darker in Unity. You also might need to increase intensity of the directional light as well, to match overall brightness of the scene. And, yes, the next important step would be adding ambient occlusion (either realtime or baked), it will significantly improve the picture.

# Answer
> 0 votes
If you want to get the *exact* same result, you have to implement in Unity the *same* rendering as the one used in MagicaVoxel, and to create a scene with the *same* lighting and material data.
As noted in the comments, MagicaVoxel uses a ray-tracing solution that might be hard to implement using Unity features. I heard however that the new experimental "Scriptable Render Loop" feature might give you enough flexibility to try to do it...
Alternately, since the main contribution of path-tracing to a scene rendering is the quality of Global Illumination, you *might* be able to get a closer result by playing with Unity's Global Illumination settings (Light Maps, Light Probes, Image-Based Lighting I guess - sorry I don't know these features well enough to give more advice).

---
Tags: unity
---


# Question
Title: Android split build - manual obb file download necessary?
I have an apk built with Unity 5.0.1 that has over 50MB. Google Play does not accept files over 50MB so I have to make a Split Build as covered in the Unity manual: http://docs.unity3d.com/Manual/android-OBBsupport.html

Now it says that I need to download the obb file manually. On the other hand, elsewhere I read that all apps that are downloaded from the play store are already downloaded with the obb file. So which one is it? Do I have to use the Google Play Obb Downloader or not? Where is the downloaded obb file stored in the filesystem?

# Answer
In most cases, Google Play will download it for you, but it can fail some times.

> On most devices, Google Play downloads the expansion file(s) at the same time it downloads the APK, so your application has everything it needs when the user opens it for the first time. In some cases, however, your application must download the files from Google Play when your application starts.

The OBB should usually be stored in `Android/obb/com.example.package`. See Google's documentation on the expansion file storage location. It should also be named in a specific format.

> For example, suppose your APK version is 314159 and your package name is com.example.app. If you upload a main expansion file, the file is renamed to:
>
> main.314159.com.example.app.obb

Unity has a plugin in the asset store that should help you get started with handling this case.
> 1 votes

# Answer
Ones if obb are downloaded successfully and later on deleted. Google play is tell you about the negative case ;)
> -1 votes

---
Tags: unity, google-play
---


# Question
Title: How should you save sprites for talking and blinking characters?
Lets say you have a game like Phoenix Wright: Ace Attorney, where characters appear on screen and do things like:

* change their stance/pose depending on the situation and mood (looking happy, looking sad, looking at the camera, looking to the side, etc.)
* move their mouths while their text is printing out
* randomly blink
* do other stuff (getting pecked by a bird for example)

I'm not sure how I should go about saving all those different "sub animations" in my spritesheets. Should everything related to one character be saved in one huge spritesheet? Or should all those sub animations have their own separate spritesheet? Should I save ALL blinking related sprites in one spritesheet or should I keep them separate from each other (one spritesheet for the blinking sprites of the happy pose, one file for the sad pose, etc)?

I would like to know what the preferred approach would be from a technical and "artistic" standpoint:

* What's the best way to save up on space and make sure the game handles the sprites well?
* What "format" would be preferred for the guy actually creating those sprites? I don't mean format as in file format or even a tool specific for the creation of spritesheets, but more HOW the sprites are arranged on the spritesheet(s).

# Answer
> 0 votes
Format and layout doesn't really matter for the artist because you can process and pack the sprites to take up less room.

You can tell the artist to save each sprite in a separate file and make everything that is not part of the sprite fully transparent.

Then you use a tool to go over every sprite and find some tight enough enclosing geometry and then go and pack several of them into a single sheet. while making sure there are no overlaps. Prefer packing sprites that you need together into a single file. For example all the frames of a sobbing animation would go into the same file.

You save the layout of each sheet so you can index them by the original file name (or whatever you use as sprite identifier) so you can create the geometry to display it at runtime. Make sure to discard the pixels that are fully transparent.

This allows you to add hot-loading of new sprites easily. Your engine can then monitor a directory of raw files with 1 sprite each and each time a file is updated in it you and then loading the updated file and letting it override any previously loaded sprite with the same ID.

---
Tags: spritesheet
---


title: LibGDX with SoundPool

text:
# Question
Title: LibGDX with SoundPool
I'm developing a game for Android using LibGDX in Android Studio. I recently found out that some sounds in my game fail to play. I noticed that every time a sound fails to play, these are the logs:

```
04-12 10:49:51.784 24234-24283/com.gadarts.parashoot.android E/AudioTrack: AudioFlinger could not create track, status: -12
04-12 10:49:51.785 24234-24283/com.gadarts.parashoot.android E/SoundPool: Error creating AudioTrack
04-12 10:49:52.503 24234-24283/com.gadarts.parashoot.android W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 4, track 44100 Hz, output 48000 Hz

```

This is the code I use to play the sounds:

```
public long playSound(SFX fileName, boolean loop, float volume, boolean randomPitch) {
        if (GameSettings.SOUND_TOGGLE) {
            try {
                Sound sound = prepareSound(fileName);
                if (randomPitch && GameSettings.SOUND_RANDOM_PITCH) {
                    return setRandomPitch(loop, sound, volume);
                }
                if (loop) {
                    return sound.loop(volume);
                } else {
                    return sound.play(volume);
                }
            } catch (GdxRuntimeException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }
private Sound prepareSound(SFX soundFile) throws GdxRuntimeException {
        try {
            String soundPath = SFX.fileAttribute.SFX_FOLDER_NAME.getValue() + "/" + SFX.fileAttribute.SOUNDS_FOLDER_NAME.getValue() + "/" + soundFile.getParentDir().getValue() + "/" + soundFile.getValue() + "." + soundFile.getFormat().getValue();
            Sound sound;
            if (!sounds.containsKey(soundFile.getValue())) {
                sound = Main.getAssetsManager().get(soundPath, Sound.class);
                sounds.put(soundFile.getValue(), sound);
            } else {
                sound = sounds.get(soundFile.getValue());
            }
            if (sound == null) {
                throw new GdxRuntimeException("preparing sound failed - sound not found.");
            }
            return sound;
        } catch (GdxRuntimeException e) {
            throw e;
        }
    }

```

The sound files are in WAV format. Any ideas how to fix it? Thanks in advance!

Update: I've found out that this problem appears only on my Nexus 5X. I tried it on Xiaomi Redmi Note 4X and it didn't happen.

# Answer
> 0 votes
I had the same issue at an early stage of one of my projects. While not getting to know the actual cause of the issue, converting all my sound files into .OGG format worked for me.

# Answer
> 0 votes
Check the sound files are 44.1k hz 16 bit .wav file as only certain bitrates will work in libgdx.

---
Tags: android, libgdx, sound, sound-effects, android-studio
---


title: GraphicRaycaster performance OnClick

text:
# Question
Title: GraphicRaycaster performance OnClick
Let's say I have two Canvases: `BackgroundCanvas` and `UICanvas`.

Now, on `BackgroundCanvas` I have multiple moving, not clickable objects so I removed the `GraphicRaycaster` (+ 69 to performance).

On the `UICanvas`, all the objects are on the `UI` layer. I also have some additional layers somewhere else.

Now, if I change the `GraphicRaycaster`'s (on `UICanvas`) blocking mask to `UI` only, would it improve performance if there are other objects on the `Default` and other layers? Or would it still ray all these objects on other layers?

How does this really work? I'm asking cause I don't see any performance impact while switching these Blocking Masks, but after disabling the entire component - I do (but the input is not working ;S).

# Answer
No, changing the blocking mask won't improve performance. For example, even if you set the blocking mask to `Nothing` in your `UICanvas`, the calls will be triggerd the same. Same goes if the children objects are inactive.

One quick way to improve performance by reducing calls is to disable the `Raycast Target` bool in all the children objects that shouldn't be checked by the raycaster.
> 2 votes

---
Tags: unity, performance, gui, input, raycasting
---


# Question
Title: Calculate speed vehicle physics 2d racegame
I am currently working on a 2d racegame where I am using physics to move a vehicle. On my form I would like to add a label containing the speed on the vehicle.

My physics knowledge is a little rusty, haven't done anything with it for a while, so I am asking the following question. Which of the calculations in my code represent the total velocity of my vehicle?

My relevant code:

```
    //our simulation object
    class RigidBody
    {
        //linear properties
        private Vector m_position = new Vector();
        private Vector m_velocity = new Vector();
        private Vector m_forces = new Vector();
        private float m_mass;

        //angular properties
        private float m_angle;
        private float m_angularVelocity;
        private float m_torque;
        private float m_inertia;

        public void Update(float timeStep)
        {
            //integrate physics
            //linear
            Vector acceleration = m_forces / m_mass;
            m_velocity += acceleration * timeStep;
            m_position += m_velocity * timeStep;
            m_forces = new Vector(0,0); //clear forces

            //angular
            float angAcc = m_torque / m_inertia;
            m_angularVelocity += angAcc * timeStep;
            m_angle += m_angularVelocity * timeStep;
            m_torque = 0; //clear torque
        }
   }

```

Hopefully someone will be able to help.

# Answer
You can get a measurement of speed, simply by calculating the magnitude of your velocity vector.

```
float speed = m_velocity.Length();

```

In most cases, this measurement would be in meters/second. In order to convert this into kilometers/h we can do the following:

```
float kmh = speed * 18f / 5f;

```

m/sec = 1m/1sec = (1/1000) km/(1/60 × 60) hr = 60 × 60 /1000 km/hr = 18/5 km/hr
> 1 votes

---
Tags: c#, 2d, physics, mathematics, software-engineering
---


# Question
Title: Calculating World Unit or Pixels Per Unit values
Is there a formula to calculate world unit or pixels per unit values in LibGdx? Most of my objects fit into a 32x32 or 16x16 frame. When the objects are close to 32x32, and I use `1f` as the size or 16x16 and use `.5f` things seem to work out fine. What I try to do is use this:

```
// Create viewport that is used to as the game size
static final float VIEWPORT_WIDTH = 15f;
static final float VIEWPORT_HEIGHT = 7f;

viewport = new FitViewport(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);

// Scale sizes
final float UNIT_PIXEL = 0.03125f;  // 1 / 32
float newSize = 32f * UNIT_PIXEL;

```

Which seems to work for 32x32 or 16x16. But size problems seem to happen when you try to use that to calculate other widths or heights. Like if I try to use:

```
float newSize = 24f * UNIT_PIXEL;

```

Using this the bounding rectangle becomes much larger than the object.

# Answer
> 1 votes
The problems you're having is due to the ratio between viewport width and your images. Currently you're using 15 as a width value and 7 as a height value. This doesn't fit well into 32 or 16.

```
E.g.
32/15 = 2.13333 recurring
16/15 = 1.06666 recurring
32/7  = 4.57142 etc
16/7  = 2.28571 etc

```

These recurring numbers are causing your conversion values to loose precision.

One way to fix this is to make your viewport width and height a Power of Two the same as your images. so 15 x 7 should become 16 x 8; This way when you want to convert back and forth you can use values without lots of decimal places.

```
E.g.
32/16 = 2
16/16 = 1
32/8  = 4
16/8  = 2

```

---
Tags: java, libgdx
---


# Question
Title: Why do I get this 'Object reference not set [...]' error on this array?
I get:

> object reference not set to an instance of an object

on line 22 of the following code. I tried digging online but I can't seem to find any solution. Please help.

```
public class Button{
    public bool free;
    public Vector3 worldPos;
    public Vector2 screenPos;
    public int Type;

    public Button(bool _free){
        free = _free;
    }
}

public class PlayerMobility : MonoBehaviour {
    const int MaxBtn = 20;
    Button[] Buttons = new Button[MaxBtn];

    // Use this for initialization
    void Start () {

        //Buttons = new Button[MaxBtn];
        for (int i = 0; i < MaxBtn; i++) {
            print ("init");
            Buttons[i].free = true; //< object reference not set to an instance of an object
                                    //  error
        }
    }
}

```

# Answer
> 2 votes
I'm not a C# programmer, but I gave this a shot. Apparently new Button\[MaxBtn\] only constructs an array, but doesn't initialise it's contents (which makes sense - how would it when you're not providing a constructor argument?). So what you're getting is an array with MaxBtn null references.

If you replace your crashing line with

```
Buttons[i] = new Button(true);

```

everything will work and the array elements will be correctly constructed.

# Answer
> 1 votes
your problem is you haven't instantiated actual buttons into your array.

When you call `new` with the code

```
Button[] buttons = new Button[MaxBtn];

```

you have set aside all the spots for the array, but at those memory locations there are no buttons yet.

what you need to do after creating the array is iterate through and instantiate buttons at each index.

```
  for(int i=0; i<MaxBtn; i++){
    buttons[i] = new Button();
   }

```

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


# Question
Title: How to detect when the current animation is finished in code in Unity's Animator?
I have a model with an animation controller. I set the states and parameters for transitions between them. Now I need to make the model play its animations in the order I want.

I can use:

```
GetComponent.<Animator>().SetBool("someparameter",true);

```

to uncheck currently checked parameter and check another parameter after current animation finished.

Please help me to find a way to make a condition "when the current animation finished".

The examples I'm finding are related to animation component (not animator), or they are too complicated for me, while I need a simple way I can understand and use quickly.

Thank you so much in advance!

# Answer
> 1 votes
What you are looking for is **State Machine Behaviours**

> State machine behaviours are scripts that can be attached to animator states or sub-state machines in an Animator Controller. \[...\] To add a state machine behaviour to a state or sub-state machine, click the Add Behaviour button in the inspector.

Then, on the newly created state machine behaviour file, implement the `OnStateExit` callback and set the value of your parameter

```
override public void OnStateExit (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
    animator.SetBool("someparameter",false);
}

```

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


# Question
Title: OpenGl: Error, The loaded object takes the same colors and style of the Texture?
I'm new to OpenGl Faced this problem:

Draw function:

```
void Renderer::Draw()
{

    glUseProgram(programID);
    shader.UseProgram();

    mat4 view = mat4(mat3(myCamera->GetViewMatrix()));
    glm::mat4 VP = myCamera->GetProjectionMatrix()*myCamera->GetViewMatrix();
    shader.BindVPMatrix(&VP[0][0]);

    glm::mat4 VP2 = myCamera->GetProjectionMatrix() * myCamera->GetViewMatrix() * floorM;
    model13D->Render(&shader, scale(100.0f, 100.0f, 100.0f)); // scaling the skybox

    t2->Bind();
    model3D->Render(&shader, scale(2.0f, 2.0f, 2.0f)); //scaling aircraft

    glUniformMatrix4fv(VPID, 1, GL_FALSE, &VP2[0][0]);

    mySquare->Draw();

}

```

The code of loaded:

```
    shader.LoadProgram();
    model3D = new Model3D();
    model3D->LoadFromFile("data/models/obj/Galaxy/galaxy.obj", true);
    model3D->Initialize();
    myCamera->SetPerspectiveProjection(90.0f, 4.0f / 3.0f, 0.1f, 10000000.0f);

    model13D = new Model3D();
    model13D->LoadFromFile("data/models/obj/skybox/Skybox.obj", true);
    model13D->Initialize();
    // Projection matrix :
    //shader.LoadProgram();

    // View matrix :
    myCamera->Reset(
        +0.0f, +0.0f, 5.0f,// Camera Position
        +0.0f, +0.0f, +0.0f,// Look at Point
        +0.0f, +1.0f, +0.0f // Up Vector
        );
    //////////////////////////////////////////////////////////////////////////
    std::string Images_names[6];

    Images_names[0] = "right.png";
    Images_names[1] = "left.png";
    Images_names[2] = "top.png";
    Images_names[3] = "bottom.png";
    Images_names[4] = "back.png";
    Images_names[5] = "front.png";
    t = new Texture(Images_names, 0);
    t2 = new Texture("arrakisday_dn.tga", 1);

```

# Answer
It appears that you either have the wrong texture bound when you attempt to draw the airplane, or you're referencing the wrong texture unit when drawing it.

Some things to check:

* Are you calling `glBindTexture()` before drawing the plane? If not, then whatever texture was last bound will still be bound, and it will assume that's the texture you want to use.
* If you are binding a texture, is it the right one?
* If it is the right one, is your shader using the same texture unit in its sampling calls?
* If all the above is correct, then perhaps you're storing all your textures in one big image and you've used the incorrect texture coordinates on the aircraft?
> 3 votes

# Answer
Normally you want to unbind things as soon as they are finished being used to make it clearer which object is currently bound. After you draw your Sandbox/terrain try to do `glBindTexture(gl_texture_target, 0)`. This will also prevent the wrong texture to be sent to the shader.
> 1 votes

---
Tags: opengl, c++, textures
---


# Question
Title: Is running cron jobs every minute a good practice for browser-based games?
I'm trying to create a browser-based game (made in PHP, MySQL, Js, HTML, and CSS) that is heavily dependent on user's actions being carried out after a certain amount of time passed whether online or offline. Will running cron jobs every second/minute a good practice or a solution to my problem?

Please check out this question first before answering, I ask this new question to focus more on the pros and cons of using cron jobs. To be more specific, here's a list of the things that I want to know:

1. Scalability? Up to what extent?
2. Performance? How fast? How slow?
3. Server Overhead? Will a normal server be able to accommodate the load?

Assuming the game will be an MMO.

I appreciate all the help people! Thanks in advance!

# Answer
If you're smart with it, it won't be too resource intensive - but I definitely wouldn't try to run it every second (plus the shortest time interval for a cron is 1 minute). Because you mention actions occurring for a user when offline, a cron is probably your only option for that.

For online actions, I recommend not having that in a cron, that way you can do actions on a per user basis, immediately, rather than batched in a cron.

If you're not already set on PHP as the backend, you should take a look into node.js combined with Websockets or socket.io \- it will allow you to keep a persistent connection, so if you want something to happen after a minute you can just use `setTimeout`. Based on what the other question states, that sounds like it'd be the best option for what you're trying to do.

Alternatively (again based on your other question, you could use `setTimeout` on the client side, and pass the info to the server to call the action. Of course, you should verify on the server that the correct amount of time has passed. This won't work if the user goes offline before the timeout callback is called (if you really wanted to, the cron could be a fallback for this scenario).
> 3 votes

# Answer
I know your question is specifically asking about cron jobs, but I think a lot of web-based mmos are written using "completeTime" logic as opposed to lots of crons.

When you start a long-running action, like building a granary that takes 5 hours to complete. The server will just mark the granary's completion time as `start time + 5 hours` and store that in the database, that's it. The client will see constant progress if they stay online, but that's only simulated on the client side. If the client logs out and back in before the 5 hours is up, when they connect, the server will tell the client when the granary is expected to be complete, and the client continues the simulation with no further server interaction. If the client logs back in and the granary should have been completed days ago, on connect, the server looks at the date and figures this out and not only completes the granary on the spot, but provides the user with the ability of the granary (let's say +2 food/hour) for all the time the user has been away for with the simple calculation:

```
foodToAdd = (currentTime - granaryCompletionTime) * 2 food / hour

```

For other actions that may affect other users (eg: building an army), updates can be executed when the affected parties do something that may require the army to be there. Everything should be able to break down in to rates, and rates can be multiplied by the amount of time that has passed.

I can't think of a case where cron jobs are necessary, other than automated backups. This also effectively removes inactive players from being processed unless they are interacted with.

```
Battle example:
Start a 3-day training session and you log out
An enemy attacks you, but the army takes 2 hours to arrive (use the same completeTime logic), then the enemy logs out

--- Time passes with no login, Nothing happens on the server

You log in a few days later and a re-calc occurs for your empire (as it does every log in)
The server figures out that you were attacked and brings both your army and the enemy army from their last update time to the battle time, making any necessary adjustments (like for training or whatever)
Resolve conflict
Continue with normal operations and pass on simulation data to client

```

Notice how the server doesn't do anything about the battle until someone (you) logs in. I'm pretty sure Travian uses a system similar to this, although there's no way to be sure.
> 6 votes

# Answer
There are pros and cons of a long-running daemon vs cron.

"Cron" will run your job every 1 minute (maximum). This carries some overhead of starting a new process, loading data files etc.

However, starting a new process will avoid memory leaks (because when the old process exits, it releases any leaked resources).

So there is a performance / robustness trade-off.

PHP is a poor language for writing a long-running daemon in due to its lack of "proper" garbage collection - certain objects, when created, cannot ever be freed (NB: It is possible that this has been partially solved since I last checked this).

In any case, if you use "cron", you should be careful that multiple instances of your processor can't run at once (hint: create an exclusive lock on a file you have open for writing; if it fails, there is another instance running). Some versions of "cron" do check if the previous instance is running but this is not completely reliable because instances may be run outside of cron.
> 1 votes

# Answer
Very interesting thinking :)

I did try to make a game using cron jobs because I didn't have the money to own my own server. And I was new to programming. But soon enough, I had a working game logic which was doing its thing every so often; the server data was processed and using php I was saving things to database and I had a table of jobs which the Server had to check for every minute. I also had htop open to check for resources being used, I was surprised that the cron jobs were using almost nothing to run, a mere 2-3% of cpu ...

So I decided to automate a browser script and run few hundred instances of the game, each instance doing something simple like move player to map x and kill x monsters, update the database with the new xp and new gold collected if any. (Funny I had to automate my own game , basically hacking it.)

I was surprised. The server didn't really go much higher than 10% with so many jobs to do it was still doing them all no problem at its set interval. Soon though I realized there was no point in completing the jobs per cron run, rather every time user makes a job do it as soon as the user made the job for the server. I was able to make the game look more live like feel like this was proper MMO with other players existing on the map with tiny delays. But Soon I realized I should go back to cron jobs. I mean the performance Went really high because players made requests more often to the server than cron jobs per day ... Literally everything a player did was immediately recorded to the database. So imagine how many requests were done .... It was like DDoS attacking from the inside. CPU was up the roof top and the free hosting company actually banned me from using my hosting account for a while because of too many requests.

So I went back to cron jobs and it felt less Online like but it worked like a charm. Of course If you have money and enough to get a vps or anything with socket support, highly recommending it because you only make initial handshake request and the rest of the game runs smoothly, and I mean it, seeing other players live moving next to you makes the game more interesting and players more happy.

However if you think you've an idea for a game that just needs to be updated every minute then go for cron jobs. They are not that resource hungry and they worked for me no problem! (Make a jobs list table and let it complete jobs in the joblist table.)

Good luck!
> 0 votes

---
Tags: mmo, browser-based-games, php, timer
---


# Question
Title: Why does this 'else' throw an error after the 'elif' in Python?
I am having trouble using the else statement and wont function correctly and will not pick it up as a correct syntax how would I correctly get this to work if invalid input was entered..

```
condition = "Start"
while condition == "Start":
Dice = int(input("Please select number of dice you would like to use (atleast 1)"))
Sides = int(input("Please select number of sides on dice you would like to use (atleast 2)"))
if Dice <= 0 or Sides <= 1:
    condition = "Start"
elif Dice >= 1 and Sides >= 2:
    else:
        condition = "Start"

```

# Answer
> 1 votes
You need to use the `pass` keyword in Python to denote an empty block (like you appear to want for your `elif`). Using that, I'd format the code you provided like this:

```
condition = "Start"
while condition == "Start":
  Dice = int(input("..."))
  Sides = int(input("..."))
  if Dice <= 0 or Sides <= 1:
    condition = "Start"
  elif Dice >= 1 and Sides >= 2:
    pass
  else:
    condition = "Start"

```

Presumably you want to do something else where that `pass` was inserted (since it seems like your positive/correct input block), but it should get you started.

---
Tags: python
---


# Question
Title: How do you exit a game when you hit an enemy?
I have a game where you are going to dodge the enemies. I want to implement a feature where the game exits when the player hits an enemy. How can I do that?

# Answer
> 1 votes
If by exit you mean terminate the program then the Java way is to simply call

```
System.exit(0);

```

when the player hits an enemy or call a shutdown method within your program.

If by exit you mean go to a main menu screen then I would recommend that you have a game state system so that when the player hits an enemy, the current state is switched to the main menu state which is updated and rendered. This would also mean that the you would have another state for the actual gameplay which then allows you to easily switch between the two.

For example:

```
//Player class
public void onHit() {
    State.setState(State.mainMenuState);
}

```

# Answer
> 0 votes
As soon as you hit your enemy, which should be captured by any event, or whatever, call `System.exit(0);` in Java.

Wherever you have your enemy hit detection method/function, you could call `System.exit(0);`, thereby exiting the application on hitting the enemy.

However, it's a common approach to return to a menu after the game is over, so I suggest you try that too, if you wish to.

Hope this helps you!!

Abhigyan Chattopadhyay.

# Answer
> -1 votes
I should ask in advance, do you want the actual game itself to close? Or do you want the game to simply go back to the main menu.

If its the former, System.Exit(0) works just fine. Your game will close and the JVM will handle the rest. If however you want it to go to the main menu, I'd just create a small function which resets the games state and displays the main menu screen.

Hope this helped!

---
Tags: java, eclipse
---


# Question
Title: Efficiently updating building effect radius coverage
I've already searched for answers but I was not able to figure out the best approach for handling expensive functions/calculations.

In my current game (a 2d tile-based city building) the user is able to place buildings, build roads etc. All of the buildings need a connection to a junction the user has to place at the border of the map. If a building is not connected to this junction, a "Not connected to road" sign will popup above the affected building (otherwise it has to be removed). Most of the buildings have a radius and might be related to each others as well (e.g. a fire department can help all houses within a radius of 30 tiles). That is what I also need to update/check when the road connection changes.

Yesterday I ran into a big performance issue. Lets have a look at the following scenario:

A user can of course also erase buildings and roads. So if a user now breaks the connection right after the junction **I need to update many buildings at the same time**. I think one of the first advice would be to avoid nested loops (which definitely is a big reason in this scenario) but I have to check...

1. if a building is still connected to the junction in case that a road tile has been removed (I do that only for affected buildings by that road). *(Might be a smaller issue in this scenario)*

(Asked separately as Efficiently determining which buildings are connected by roads)
2. the list of radius tiles and get buildings within radius *(nested loops - big issue!)*.

```
// Go through all buildings affected by erasing this road tile.
foreach(var affectedBuilding in affectedBuildings) {
    // Get buildings within radius.
    foreach(var radiusTile in affectedBuilding.RadiusTiles) {
        // Get all buildings on Map within this radius (which is technially another foreach).
        var buildingsInRadius = TileMap.Buildings.Where(b => b.TileIndex == radiusTile.TileIndex);

        // Do stuff.
    }
}

```

This all breaks down my FPS **from 60 to almost 10** for one second.

So would could I do. My ideas would be:

* Not using the main thread (Update function) for this one but another thread. I might run into problems of locking when I start using multithreading.
* Using a queue to handle a lot of calculations (what would be the best approach in this case?)
* Keep more information in my objects (buildings) to avoid more calculations (e.g. buildings in radius).

Using the last approach I could remove one nesting in form this foreach instead:

```
// Go through all buildings affected by erasing this road tile.
foreach(var affectedBuilding in affectedBuildings) {
    // Go through buildings within radius.
    foreach(var buildingInRadius in affectedBuilding.BuildingsInRadius) {
        // Do stuff.
    }
}

```

But I don't know if this is enough. Games like Cities Skylines have to handle way much more buildings if the player has a big map. How do they handle those things?! There might be a updating queue since not all the buildings do update at the same time.

I'm looking forward to your ideas and comments!

Thanks a lot!

# Answer
> 5 votes
## Caching building coverage

The idea of caching the information which buildings are in range of an effector-building (which you can cache either from the effector or in the affected) is definitely a good idea. Buildings (usually) don't move, so there is little reason to redo these expensive calculations. "What does this building affect" and "what affects this building" is something you only need to check when a building is created or removed.

This is a classic exchange of CPU cycles for memory.

## Handling coverage information by region

If it turns out you are using too much memory to keep track of this information, see if you can handle such information by map regions. Divide your map into square regions of `n`*`n` tiles. If a region is fully covered by a fire department, all buildings in that region are covered too. So you only need to store coverage information by region, not by individual building. If a region is only partially covered, you need to fall back to handling by-building connections in that region. So the update-function for your buildings would first check "Is the region this building is in covered by a fire department?" and if not "Is this building individually covered by a fire department?". This also speeds up updates, because when a fire department is removed, you no longer need to update the coverage states of 2000 buildings, you only need to update 100 buildings and 25 regions.

## Delayed updating

Another optimization you can do is not updating everything immediately and not updating everything at the same time.

Whether or not a building is still connected to the road network isn't something you need to check every single frame (By the way, you might also find some ways to optimize this specifically by looking a bit into graph theory). It would be completely sufficient if buildings only check for that periodically every few seconds after the building was built (AND if there was a change to the road network). The same applies to building range effects. It is perfectly acceptable if a building only checks every few hundred frames "Is at least one of the fire departments which affect me still active?"

So you could have your update-loop only do these expensive calculations for a few hundred buildings at a time for every update. You might want to give preferences to buildings which are currently on the screen, so the players get immediate feedback for their actions.

## Regarding Multithreading

City builders tend to be on the more computationally expensive side, especially if you want to allow players to build really large and if you want to have a high simulation complexity. So in the long run it might not be wrong to think about what computations in your game can be handled asynchronous.

# Answer
> 3 votes
**1. Duplicate work**.

Your `affectedBuildings` are presumably close to each other, so the different radii will overlap. Flag the buildings that need to be updated, then update them.

```
var toBeUpdated = new HashSet<Tiles>();
foreach(var affectedBuilding in affectedBuildings) {
    foreach(var radiusTile in affectedBuilding.RadiusTiles) {
         toBeUpdated.Add(radiusTile);

}
foreach (var tile in toBeUpdated)
{
    var buildingsInTile = TileMap.Buildings.Where(b => b.TileIndex == radiusTile.TileIndex);
    // Do stuff.
}

```

**2. Unsuitable Datastructures.**

```
var buildingsInTile = TileMap.Buildings.Where(b => b.TileIndex == radiusTile.TileIndex);

```

should clearly be

```
var buildingsInRadius = tile.Buildings;

```

where Buildings is an `IEnumerable` with constant iteration time (e.g. a `List<Building>`)

---
Tags: algorithm, monogame, performance, tilemap, city-builder
---


# Question
Title: Import and run LibGDX project in IntelliJ
I followed this guide to import a demos project, but when I set the class path of the module to the desktop, then click on the button of the main class field and select the `DesktopLauncher` class, there is no desktop module in the list. I can't run the imported project, because I have to create a custom run configuration named "Desktop" with the module "desktop" and the main class "DesktopLauncher".

How do I import and run a LibGDX project in IntelliJ?

# Answer
Have you made sure you have let gradle import everything?

Usually intellij will say it found gradle files and ask you for settings, there you can enable auto import.

You might be able to rightclick and press build on build.gradle in the project root.

If you can already see a gradle tab in intellij (usually right side at the top) you can open that tab and press the refresh icon.
> 0 votes

---
Tags: libgdx, gradle
---


# Question
Title: How to draw smooth moving curve in libgdx?
i need to draw curve like this picture, I have tried from this link https://github.com/libgdx/libgdx/wiki/Path-interface-&-Splines , but the curve is not so smooth like some game(Amazing Wire) which is already in the market.

# Answer
> 4 votes
You can use a bezier or catmullromsplie to draw curves based on supplied points.

```
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Bezier;
import com.badlogic.gdx.math.CatmullRomSpline;
import com.badlogic.gdx.math.Vector2;

public class Test extends ApplicationAdapter{

    //create paths
    private Bezier<Vector2> path1;
    private CatmullRomSpline<Vector2> path2;
    private ShapeRenderer sr;

    @Override
    public void create () {

        // set up random control points
        int width = Gdx.graphics.getWidth();
        int height = Gdx.graphics.getHeight();
        int points = 4;
        Vector2[] controlPoints = new Vector2[points];
        for (int i = 0; i < points; i++) {
           int x = (int) (Math.random() * width) ;
           int y = (int) (Math.random() * height);
           Vector2 point = new Vector2(x, y);
           controlPoints[i] = point;
        }

        // set up the curves
        path1 = new Bezier<Vector2>(controlPoints);
        path2 = new CatmullRomSpline<Vector2>(controlPoints, true);

        // setup ShapeRenderer
        sr = new ShapeRenderer();
        sr.setAutoShapeType(true);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        sr.begin();
        sr.setColor(Color.WHITE);

        //draw path1
        for(int i = 0; i < 100; ++i){
            float t = i /100f;
            // create vectors to store start and end points of this section of the curve
            Vector2 st = new Vector2();
            Vector2 end = new Vector2();
            // get the start point of this curve section
            path1.valueAt(st,t);
            // get the next start point(this point's end)
            path1.valueAt(end, t-0.01f);
            // draw the curve
            sr.line(st.x, st.y, end.x, end.y);

        }

        //same as above but for catmullrom
        sr.setColor(Color.RED);
        for(int i = 0; i < 100; ++i){
            float t = i /100f;
            Vector2 st = new Vector2();
            Vector2 end = new Vector2();
            path2.valueAt(st,t);
            path2.valueAt(end, t-0.01f);
            sr.line(st.x, st.y, end.x, end.y);

        }

        sr.end();
    }

    @Override
    public void dispose () {
    }
}

```

EDIT: If the lines are still not smooth enough then you could try using anti-aliasing. You can enable it in libgdx by adding the following lines to your appropriate launcher

Android:

```
config.numSamples =2; // number of sample to take more = smoother

```

Desktop:

```
config.samples =2; // number of sample to take

```

This gives me this line

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