# Question
Title: How to add highlights or descriptions to the Unity Editor interface
Is there a way to develop a Unity learning program that runs within the Unity Editor?

For example, I want to create something like a highlight or a description on the Unity UI.

# Answer
> 0 votes
Your are asking about Unity Editor Scripting, yes there are a lot of ways to extend your inspector and even build tools inside the editor. as for highlights, you can use the tooltip attribute of EditorGUILayout like:

```
value = EditorGUILayout.FloatField(new GUIContent("Test Float", "Here is a tooltip"), value);

```

---
Tags: unity
---


# Question
Title: How can I render an OpenGL scene into an ImGui window?
The picture rapresents what i want to achieve.

I read, somewhere on the Internet, that you can render the fbo and pass that fbo as a texture to render into the ImGui window. The problem is that I don't even know what an FBO is, and how to create it. I just want to have the scene rendered into my ImGui window (just like the scene window in Unity)

How do i do it?

# Answer
> 9 votes
First you need to render you scene to a Frame Buffer Object (here is a good course on FBO: https://learnopengl.com/#!Advanced-OpenGL/Framebuffers)

After that you will end up with a Texture (of type GLuint) containing your rendered scene. To print it into Dear imGUI, just call a Draw Image Command.

**EDIT New (simpler) Example:**

```
ImGui::Begin("GameWindow");
{
  // Using a Child allow to fill all the space of the window.
  // It also alows customization
  ImGui::BeginChild("GameRender");
  // Get the size of the child (i.e. the whole draw size of the windows).
  ImVec2 wsize = ImGui::GetWindowSize();
  // Because I use the texture from OpenGL, I need to invert the V from the UV.
  ImGui::Image((ImTextureID)tex, wsize, ImVec2(0, 1), ImVec2(1, 0));
  ImGui::EndChild();
}
ImGui::End();

```

**Previous Version**

Here is an example:

```
// My Game has a different viewport than the editor's one:
const int W = 1080 / 2;
const int H = 1920 / 2;
// We set the same viewport size (plus margin) to the next window (if first use)
ImGui::SetNextWindowSize(ImVec2(W + 10, H + 10),
                           ImGuiSetCond_FirstUseEver);
  ImGui::Begin("Game rendering");
  {
    // Get the current cursor position (where your window is)
    ImVec2 pos = ImGui::GetCursorScreenPos();

    // A boolean to allow me to stop the game rendering
    if (runApp) {
      glViewport(0, 0, W, H);
      // Render the scene into an FBO
      game->render(time);
      // Restore previous viewport
      glViewport(0, 0, w, h);
    }
    // Get the texture associated to the FBO
    auto tex = game->getRendered();

    // Ask ImGui to draw it as an image:
    // Under OpenGL the ImGUI image type is GLuint
    // So make sure to use "(void *)tex" but not "&tex"
    ImGui::GetWindowDrawList()->AddImage(
        (void *)tex, ImVec2(ImGui::GetItemRectMin().x + pos.x,
                            ImGui::GetItemRectMin().y + pos.y),
        ImVec2(pos.x + h / 2, pos.y + w / 2), ImVec2(0, 1), ImVec2(1, 0));
  }
  ImGui::End();

```

# Answer
> 2 votes
Rendering to a FBO and using as a texture is just fancy speak for rendering to texture and then using that texture in a subsequent render. All geometry generated by imgui are just texture triangles.

FBO stands for FrameBuffer Object, it is a collection of images that you can use as a rendertarget. Opengl is initialized with the window as the default target FBO.

---
Tags: opengl, c++, gui, ui-design, imgui
---


title: How to make curved GUI in Unity?

text:
# Question
Title: How to make curved GUI in Unity?
I'm really new in Unity. I want to make a curved GUI by myself. How would I make one?

I'm using Unity 5.6.

# Answer
> 13 votes
Here's a strategy for making arbitrarily bent UI: we'll render our UI into a texture (in realtime, not as a baking step), and then map that texture onto whatever mesh we want.

Here's how I made this spherical example:

1. Create a RenderTexture to store the UI. This needs to be quite high-res to get text looking crisp. I used 4096x2048 because I intend to map the texture along lines of latitude & longitude, and there's twice as much longitude to cover. ;)

If you're only rendering part of the UI at a time, as in the case of a wraparound sphere, we could use an adaptive window that renders only the visible parts to maximize use of the available texture space, but I'll elide that complexity for now.
2. Create a second camera to capture your UI

* set to Orthographic
    * culling mask set to UI only
    * target texture set to your RenderTexture
    * set its Depth to -1 so it renders before your MainCamera
3. Create your UI canvas

* set to Screenspace - Camera, using your UI camera
    * remove the Canvas Scaler - it's not needed if we're rendering to a fixed resolution
4. Set your Main Camera's culling mask to exclude the UI layer (so we don't see it twice)
5. Set up your mesh. For my example I used a sphere centered on my Main Camera, with a shader that renders the inside faces instead of the outside, and maps the assigned RenderTexture around its surface using latitude & longitude (equirectangular mapping).
6. To get the UI to respond to input events, you need to customize your input module so it knows how to translate clicks/taps on the screen into corresponding coordinates in your UI rendering space. Here's one I wrote to handle the sphere, based off of the example OpticalOverride provides here.

---

```
 using UnityEngine;
 using UnityEngine.EventSystems;

 public class SphericalInputModule : StandaloneInputModule {

    new public Camera camera;
    public RenderTexture uiTexture;

    Vector2 m_cursorPos;
    private readonly MouseState m_MouseState = new MouseState();
    protected override MouseState GetMousePointerEventData(int id = 0)
    {
        MouseState m = new MouseState();

        // Populate the left button...
        PointerEventData leftData;
        var created = GetPointerData(kMouseLeftId, out leftData, true);

        leftData.Reset();

        if (created)
            leftData.position = m_cursorPos;

        // Ordinarily we'd just pass the screen coordinates of the cursor through.
        //Vector2 pos = Input.mousePosition;

        // Instead, I'm going to translate that position into the latitude longitude
        // texture space used by my UI canvas:
        Vector2 trueMousePosition = Input.mousePosition;
        Vector3 ray = camera.ScreenPointToRay(trueMousePosition).direction;

        Vector2 pos;
        pos.x = uiTexture.width * (0.5f - Mathf.Atan2(ray.z, ray.x) / (2f * Mathf.PI));
        pos.y = uiTexture.height * (Mathf.Asin(ray.y) / Mathf.PI + 0.5f);
        m_cursorPos = pos;

        // For UV-mapped meshes, you could fire a ray against its MeshCollider
        // and determine the UV coordinates of the struck point.

        leftData.delta = pos - leftData.position;
        leftData.position = pos;
        leftData.scrollDelta = Input.mouseScrollDelta;
        leftData.button = PointerEventData.InputButton.Left;
        eventSystem.RaycastAll(leftData, m_RaycastResultCache);
        var raycast = FindFirstRaycast(m_RaycastResultCache);
        leftData.pointerCurrentRaycast = raycast;
        m_RaycastResultCache.Clear();

        // copy the apropriate data into right and middle slots
        PointerEventData rightData;
        GetPointerData(kMouseRightId, out rightData, true);
        CopyFromTo(leftData, rightData);
        rightData.button = PointerEventData.InputButton.Right;

        PointerEventData middleData;
        GetPointerData(kMouseMiddleId, out middleData, true);
        CopyFromTo(leftData, middleData);
        middleData.button = PointerEventData.InputButton.Middle;

        m_MouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), leftData);
        m_MouseState.SetButtonState(PointerEventData.InputButton.Right, StateForMouseButton(1), rightData);
        m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, StateForMouseButton(2), middleData);

        return m_MouseState;
    }
}

```

# Answer
> 2 votes
*As @DMGregory suggested, here is the answer with some details*:

There is no built in option of Curved GUI, you either can make a curved mesh in Max, Blender or May or using any third party modeling tool. Later you can use this mesh in with Canvas.

1. make a curved mesh in any 3d modeling tools
2. import it into unity
3. create canvas
4. make curved mesh child of the canvas
5. add buttons or other desired unity ui objects into canvas and place it according to curved mesh.

Here are some images for demonstrations:

A view of curved mesh ui with buttons

A view of curved mesh, you can model it according to your requirments

---
Tags: unity, gui, ui-design
---


# Question
Title: How to make proper animations for a html5 game?
I am working on a web based MMORPG in html5.

Therefore, I think about using Phaser.io to be the main engine of the game on the client side.

I want the game to be isometric and I am wondering how to make proper sprites/animations/gfx for the game.

I don't want my graphic team to have too much pain. Would it be possible, for example, to use any kind of "vectorial spritesheet" so that I can zoom in and have a better look at the character.

On the other hand, I don't want the "stuff" (hat, armor, etc) to be too hard to "plug" on the character in all the different orientations.

I thought about using some kind of flash like system (my game is based on the french MMO Dofus which only uses flash for its client side but no web based techno)

But I don't know anything about flash, can I integrate it inside a canvas and does it mux well with raster images like png or jpg?

What alternative could I use?

# Answer
If you really want the best for your graphic team, then use 3d models. With an orthographic projection and good camera placement (it needs to be rotated 45 degrees around the y axis and 60 on the x axis) you can achieve the same look. In fact, the majority of the isometric games nowadays are actually 3d games with billboards for characters, but you can use models too.

The problem with Flash is that it's losing support. The browsers are on auto update and in the latest versions you already have to allow it. It also doesn't have any support on phones if that's something you're looking into.

You can't integrate Flash with the canvas, they're two different technologies.

As for your speed issue, I don't think you'll get any advantage with Flash anyways, Phaser uses WebGL internally and falls back to the canvas if needed.
> 1 votes

---
Tags: graphics, flash, image
---


# Question
Title: Minecraft: What is the reasonable face/vertex limit for custom models?
When adding custom models to function as tile entity representations, what is a reasonable ceiling - based on performance - to maintain for individual models? Assume that the player will have the potential possibility to place as many of these as desired, but functionally it would also be reasonable to assume no more than 20 would have to be rendered at once.

*If the answer has changed between significant versions of the game, it would be nice if that could be reflected*

# Answer
Sooo...basically the answer is "a bunch, really" as long as you're talking a *block model* (that is, a model that's precomputed and cached per the 1.10 JSON model system or ISBRH in 1.7, although ISBRH is going to be slightly CPU heavier than a JSON or IBakedModel as ISBRH aren't cached the same way IBakedModels are, they are periodically recomputed).

Based on one user's experimentation with Menger Sponge models the limitation is more *RAM* based than CPU or GPU (that is: having to open and read a 1.3 MB file, cache it, as well as busing over the massive mesh to the GPU).

TileEntity models (TESR) are insanely heavy on the CPU and should just be avoided at all costs. If it doesn't animate, you don't need a TESR.
> 1 votes

---
Tags: graphics, performance, minecraft-modding
---


title: Loading screen OpenGL with glut API

text:
# Question
Title: Loading screen OpenGL with glut API
I'm trying to make a loading screen. My idea is to have two threads working - one in the background loading the 'game' scene, one displaying 'load' scene. When building 'game' scene is finished, it's displayed instead of 'load' scene. Before threading I want to make it work the usual way: first display 'load' scene, then 'game' scene. Both GameScene and LoadScene inherit from a virtual function Scene. Here's how my main looks like:

```
LoadScene *load_scene;
GameScene *game_scene;
Scene *scene;

int main(int argc, char **argv)
{
// Init GLUT and create window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_STENCIL);
glutInitWindowPosition(initWindowX, initWindowY);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("OpenGL");

// Register callback functions for change in size and rendering.
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutIdleFunc(renderScene);

// Register Input callback functions.
// 'Normal' keys processing
glutKeyboardFunc(processNormalKeys);
glutKeyboardUpFunc(processNormalKeysUp);
// Special keys processing
glutSpecialFunc(processSpecialKeys);
glutSpecialUpFunc(processSpecialKeysUp);

// Mouse callbacks
glutMotionFunc(processActiveMouseMove);
glutPassiveMotionFunc(processPassiveMouseMove);
// void glutMouseFunc(void(*func)(int button, int state, int x, int y))
glutMouseFunc(processMouseButtons);
glutMouseWheelFunc(processMouseWheel);
// Position mouse in centre of windows before main loop (window not resized
yet)
glutWarpPointer(windowWidth / 2, windowHeight / 2);
// Hide mouse cursor
glutSetCursor(GLUT_CURSOR_NONE);
// warp

// Initialise input and scene objects.
input = new Input();
//scene = new LoadingScene(input);
load_scene = new LoadScene();
game_scene = new GameScene(input);

// load scene
// Create GameScene();
// Create LoadingScene(GameScene *)
// delete LoadingScene();
// LoadingScene thread tells game to start loafing assetss

// Enter GLUT event processing cycle
glutMainLoop();

return 1;
}

```

The game scene reassignment must be called in `changeSize` function. I thought it should be in the `renderScene` function but it's the only way it works. Here's how it looks like:

```
void changeSize(int w, int h)
{
scene = load_scene;

scene->resize(w, h);
}

```

Any ideas how I could go on about it? So far if I assign to 'scene' pointer 'load\_scene' object it's displaying 'load' scene. Same goes for 'game' scene. Is it even possible to achieve a transition between scenes without threading?

# Answer
This is an answer based on my previous comments.

In a game you usually have one loading function for each system/component (graphic, input, window, game logic, entities...) and you call it once when your program starts. You always have to load files from disk to RAM and to perform heavy task to setup the data needed by your game to run. This takes a lot of time (in AAA games sometimes even a minute or more). If you want to have a loading animation you need to update it x times per second and you can't if you're program is doing something completly different.

One simple approach is to have a fixed loading screen with a simple progress bar: you load your systems with different function and, between each one you call some kind of "update method" which updates the loading percentage and displays it. This method has its limits: maybe one system takes a lot to intialize itself and your program stucks and becomes unresponive, but, first of all you have to manually write the code to separate the different loading functions (and keep it updated).

And here comes multithreading: let the OS performs this division, switching automatically between loading and rendering thread. You usualy have you're main thread where you perform things like input handling, rendering and so on and one where, while you're game is running, you load the data needed for the next level for example.

So, in pseudo-code you have:

```
//Main thread
//Create game window, load graphic engine ann other basic stuff
function load()
{
f_loadWindow(width, height);
f_loadInput(m_Window);
f_loadGraphic(m_Window);

var isLoading = true;

//create the loading thread where GameLogic::loadingFunction will run
var loadingThread = new Thread(GameLogic::loadingFunction, isLoading);

//Display loading animation from the main thread while the other is loading
while(isLoading){
    f_updateLoadingAnimation();
    f_renderLoadingAnimation();
}

//Now that the data is loaded close the secondary thread
loadingThread.join();

//Now you can easily enter the game loop (frame() function)
return;
}

function frame()
{
f_updateGameLogic();
f_renderGameLogic();
}

function loadingFunction(bool& _isLoading)
{
//Load different objs
f_LoadTerrrain();
f_LoadEntities();
...
f_LoadMisc();

//now that you have load everything set isLoading to false
//to stop the main thread's animation while loop
isLoading = false;

return;
}

```

Everything rotates around "isLoading" which allow the two threads to communicate. I actually can't remember how threading is implemented in c++, but you can easiy find it on google.

(I used functions insetead of classes to be clearer, of course you can go your own way).

Ask for anything you need.
> 1 votes

---
Tags: opengl, c++, multithreading, glut
---


# Question
Title: Collision detection for an arc of a circle
So how do I implement the collision detection for an arc of a circle? Will I have to use the Box 2D collision or can I do it some other way using Rectangle or stuff like that?

BTW I hate box2d because I don't understand most of the things in it, so if there is a solution that excludes the box2d, it will be very much appreciated.

The yellow arc keeps on rotating over the black circle. How do I implement collision detection in here?

# Answer
> 0 votes
I answered this question already Collision detection for an arc of a circle however I will sum it up here:

You can create a polygon that represents the area you want to detect collisions for using code similar to:

```
    polya = new Polygon();

    // create vertices
    float section = 15f;
    float[] newVerts = new float[200];
    for(int i = 0; i < 50; i++){
        newVerts[i*2] = (float)Math.sin(i/section); //x 0 to 98 even
        newVerts[i*2+1] = (float)Math.cos(i/section); //y 1 to 99  odd

        newVerts[199-i*2] = (float)Math.cos(i/section); //x 100 to 108
        newVerts[198-i*2] = (float)Math.sin(i/section) + 0.2f; //y 101 to 199

    }

    polya.setVertices(newVerts);
    polya.scale(50);

```

Then you use the polygon.contains(x,y) method to check if the point x,y is inside. This will return a boolean value true if the point is inside the polygon which equates to a collision.

```
if(polya.contains(mp.x,mp.y)){
      //point has collided with polygon do something
}

```

---
Tags: libgdx, collision-detection
---


# Question
Title: Java 2D - Cannot get code to work for generating points for a line with a start point and Angle
I am developing a Java 2D video game. I am trying to write code to generate points for a line (actually a projectile path), at a specified angle, from a given start point. There seems to be something wrong with my Math. The points are to be used for moving a projectile from the top of the screen, towards the target (a submarine) which sits at the bottom.

I am suspicuous issue has to do with fact the origin of Java 2D coordinate system is 0,0 at top of the screen, not at bottom left for cartesian coordinate system. Note: I am not a Math person. So please excuse me if I am getting the terms wrong.

Here is what I am doing:

xloc, yloc - the initial location of the projectile I want to move towards the sub location

```
// Get slope of the line
float m= ((float)((int) yloc - subYcoord))/((int) xloc - subXcoord);

double radians= Math.atan(m);

double ycoord= yloc;
double xcoord= xloc;

int speed= 1;

// This is how I am attempting to generate the points for the path for the projectile to take

while (true) {

    xcoord += speed * Math.cos (radians);
    ycoord -= speed * Math.sin (radians);

    if (((int) ycoord)>= gunBaseYcoord) {

        break;
    }

    // WayPoints is my list of points to move the Projectile towards the sub at    bottom of the screen

    Point aPoint= new Point((int) xcoord, (int) ycoord);
    wayPoints.add(aPoint);
}

```

This does not seem to work for angles of 245 degrees.

As an example, if x,y are: 660, 35 (this would be my start point for the projectile), and subXcoord, subYcoord are: 169, 500

I get a slope of: -.947 (should be like: 245 degrees)

The radian is: -.758

I get degrees of: -43 (now this doesn't look right)

Appreciate any help with this! Thanks!

# Answer
> 0 votes
Here's the vector based method Bruno Vieira Costa mentioned in the edit, in a bit more detail:

Given `projectileX` & `projectileY`, `targetX` & `targetY`, we can think of each of these as a vector (arrow) pointing from the origin of our space `(0, 0)` to the respective objects.

By subtracting the projectile position from the target position, we get a vector (arrow) pointing from the projectile to the target:

```
differenceX = targetX - projectileX
differenceY = targetY - projectileY

```

We can "normalize" this vector to a length of one (a so-called "unit vector") to express just the direction of travel (using Pythagorean Theorem):

```
distance = sqrt(differenceX * differenceX + differenceY * differenceY)
directionX = differenceX/distance
directionY = differenceY/distance

```

Then we can move at a given `speed` along this direction like so:

```
currentX += speed * directionX
currentY += speed * directionY

```

We can use the dot product to figure out whether two vectors are pointing in similar directions (\>0), opposing directions (\<0), or perpendicular (0), and use this to detect when we've passed our target

```
differenceX = targetX - currentX
differenceY = targetY - currentY

dot = differenceX * directionX + differenceY * directionY

if(dot <= 0)
   // The target is now behind us, we passed it! Stop drawing our line.

```

You can see there's a lot of redundancy in the lines above, repeating the same code for both X and Y. Generally a vector math library will let you perform addition/subtraction and various multiplication operations on vectors as a whole, so don't have a lot of separate x & y (and in 3D, z or even w) variables to manage yourself.

# Answer
> 0 votes
The problem is that tan function is not injective in \[-pi .. pi\] interval.

You should use atan2 instead. This function need 2 parameters: deltay and deltax

**edit:**

Instead of using atan, you can only get the difference vector: (deltaX,deltaY) and normalize it and multiply by the speed you need.

---
Tags: mathematics, graphics-programming
---


title: Unity - Best Random Movement Strategy?

text:
# Question
Title: Unity - Best Random Movement Strategy?
As of now, to get random movement of my enemies, I am adding a Rigidbody and a BoxCollider then "throwing" them (i.e. adding velocity) in a random direction for a random amount of time and making them choose a new direction if ever they get outside of their designated area. This does not seem to work that well all the time. Sometimes they manage to get themselves stuck inside obstacles which should be impossible. The more I add guys, the more it seems the physics can't keep up or something with the collisions. Is there a better method to random movement or is "throwing" them perfectly valid? Is my method expensive and terrible? I might have around 50 guys active at a time and perhaps a few hundred to a thousand static obstacles each with their own colliders.

# Answer
Throwing them is perfectly valid and it is not a bad way of doing things unless you find that it becomes an issue. The amount of collisions you are describing should not be too expensive unless your Colliders are complex and you are running on a platform that has limited resources.

The "getting stuck" part is the bigger concern. There are a number of reasons that could be happening. You might can avoid this by changing the **collision detection** on the objects' `rigidBody` to *Continuous* instead of *discrete*. You normally wouldn't want to do that unless the objects are moving extremely fast because *continuous* does have a higher CPU cost.
> 1 votes

# Answer
You can build a Navigation Mesh of your movable area and send your agents to arbitrary positions inside its bounds.
> 0 votes

---
Tags: unity, physics, movement
---


# Question
Title: How to make the image move forward properly when rotated in my HTML5 game?
I am just trying to make a simple 2D racing game using canvas. It uses the `W`,`S`,`A`, `D` keys to move the car. The `W` key should take me forward and the `A` and `D` keys will turn each way. I want the car to continue heading forward after being turned. I am currently just multiplying the distance to move by the sin or cosine of the angle in order to find the x and y positions, but it is not reacting how I would expect. Thanks.

```
<!DOCTYPE html>
<head>
  <meta charset="UTF-8" />
  <title></title>
</head>
<body>
<canvas id="canvas_layer_01" width="3072" height="2048" style="border:1px solid #000000;">></canvas>

<script>
  var canvas = document.getElementById("canvas_layer_01");
  ctx = canvas.getContext("2d");

  car_image = new Image();
  car_image.src = 'http://i.imgur.com/Bl2p5KI.png';

  var key_pressed_a = false,
    key_pressed_d = false,
    key_pressed_w = false,
    key_pressed_s = false;

  var player_x = 50,
    player_y = 50,
    player_speed = 10,
    player_angle = 0,
    max_turn_angle = 10; // probably needs to change based on speed

  document.addEventListener("keydown", function(e){
    switch(e.keyCode){
      case 87:
        key_pressed_w = true;
        break;

      case 83:
        key_pressed_s = true;
        break;

      case 65:
        key_pressed_a = true;
        break;

      case 68:
        key_pressed_d = true;
        break;
    }
  }, false);

  document.addEventListener("keyup", function(e) {
    switch(e.keyCode) {
      case 87:
        key_pressed_w = false;
        break;

      case 83:
        key_pressed_s =false;
        break;

      case 65:
        key_pressed_a = false;
        break;

      case 68:
        key_pressed_d =false;
        break;
    }
  }, false);

  window.requestAnimFrame = (function(callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
      function(callback) {
        window.setTimeout(callback, 1000/60);
      };
  })();

  // http://stackoverflow.com/a/16546061/6716639
  function render_image(img, x, y, width, height, degrees) {

    //Convert degrees to radian
    var rad = degrees * Math.PI / 180;

    //Set the origin to the center of the image
    ctx.translate(x + width / 2, y + height / 2);

    //Rotate the canvas around the origin
    ctx.rotate(rad);

    //draw the image
    ctx.drawImage(img,width / 2 * (-1),height / 2 * (-1),width,height);

    //reset the canvas
    ctx.rotate(rad * ( -1 ) );
    ctx.translate((x + width / 2) * (-1), (y + height / 2) * (-1));
  }

  function updateGame() {

    if(key_pressed_w) {
      player_x += player_speed * Math.sin(player_angle);
      player_y += player_speed * Math.cos(player_angle);
    }
    else if(key_pressed_s) {
      player_y += player_speed;
    }
    else if(key_pressed_a) {
      player_angle -= max_turn_angle;
    }
    else if(key_pressed_d) {
      player_angle += max_turn_angle;
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    render_image(car_image, player_x, player_y, car_image.width, car_image.height, player_angle);

    requestAnimFrame(function() {
      updateGame();
    });
  }

  updateGame();

</script>

</body>
</html>
```

# Answer
You mixed the functions up, x should use cosine and y should use sine.

It's also worthy to mention, that these use radians instead of degrees, and by the look of things, your code uses degrees.

And also, the trigonometric functions with an angle of 0 create a vector pointing to the right, so if your car's image isn't correct, then it will go sideways.
> 0 votes

---
Tags: game-mechanics, html5, html-canvas
---


# Question
Title: GraphicsAdapter.Adapters on openGL won`t return secondary monitor
I have been searching for this everywhere and never found the answer.

I am developing a feature to allow the user to select which monitor to run the game.

I have two monitors, primary and secondary. I tried to use "GraphicsAdapter.Adapters" but it always retrieves only 1 monitor (the one I am running the Visual Studio which is the default one).

Is this a bug? How can I retrieve all the monitors available?

Thanks

MONOGAME 3.6 OPENGL (cross platform) Visual Studio 2015 Windows 10 Pro 64bits

# Answer
> 1 votes
If we look at the code for the 3.6 release:

There are three files containing `GraphicsAdapter` source code. It looks like `GraphicsAdapter.Legacy.cs` is used if you are using the Windows/OpenGL build of MonoGame.

In this version of the code, the `Adapters` property performs lazy-initialization of the underlying `_adapters` array. It has preprocessor blocks to build the array differently based on which platform is being built for. Since you're using Windows, that translates to a call to this line:

```
_adapters = new ReadOnlyCollection<GraphicsAdapter>(new[] { new GraphicsAdapter() });

```

The property then simply returns `_adapters`.

So yes, for OpenGL builds on Windows, `GraphicsAdapter.Adapters` will only ever return a single item. MonoGame does not appear to implement the functionality necessary to expose multiple-monitor support for OpenGL on Windows, at least not in the fashion you're looking for.

---
Tags: opengl, xna, monogame, cross-platform
---


title: How to get our music into games?

text:
# Question
Title: How to get our music into games?
As a fairly unknown independent band, what is the best way to get our music into computer games? I'm not so much thinking about licensing issues, but more about what channels are available and how to get noticed by game devs that could be interested in our type of music.

# Answer
> 11 votes
You have two options:

1) The indirect route: Find sites that distribute music and put it there. See Where is quality paid game music? and Where can I find free music for my game?

2) The direct route: Find a project in development and talk to them directly. See "Finding a project" from here: How can I get involved with open source game projects?

# Answer
> 2 votes
Direct Promotion.

Search for game developers which you'll think your music match in their current or previous products and send a simple email introducing yourself. I'll even send an email to devs even if your music doesn't fit with previous projects, as you never know what could be building: today is a educational game, tomorrow maybe a Satanic Hack'n' slash Gore game that would make God Of War rate C ;)

# Answer
> 2 votes
This isn't your games as the soundtrack, but Rock Band Network (currently under maintenance while they change stuff for Rock Band 3 compatibility, but should be back up soon) is simply awesome. You can author everything yourself, and the only cost is an XNA Creators Club account and an Xbox 36 ($300 for the Xbox, $100 for a year of creators club, which you can actually put off on getting until you're ready to test).

Another alternative is to just go make your own game. Shinobi Ninja just went and made an iPhone game about themselves: itunes.apple.com/us/app/brooklyn-to-babylon-shinobi/id347930797?mt=8

They contracted a developer, so there was that cost involved. Make friends with computer science majors. ;)

# Answer
> 1 votes
As an independent game developer I would tell you that, for us, it is very difficult to find the right music for our games... It should not be difficult for you to find games that match your music style. Just set up a webpage with some examples of your music and promote it in game development forums. If it is good, you will get a lot of responses, I'm sure!

# Answer
> 1 votes
network network network...

Go to things like the Game Developer's Conference. Hang out and talk to anyone and everyone you meet. Learn more about videogame music at someplace like GameSoundCon to try to make yourself more knowledgable (and more valuable) to a potential game developer.

Know and love games and gaming. Lots of people want to get into game music. Not a lot of them love games. Would George Lucas want a composer who never really watched movies or couldn't name a current game scoring his next film? Game Developers often feel the same way about their composers.

Get a student game or two under your belt-- go to the local college and see if they have a gaming club or computer science department. There are often a ton of student-created games at these places and they have no idea where to go for music. Nothing makes for a better resume than "oh, download XXXX from the App Store to hear some of our game music.

# Answer
> 1 votes
Building on Brian Schmidt's 2012 answer about networking, I'd suggest looking out for Game Jams

A jam is like a hackathon or charrette, where a group of game creators get together to make a playable game from scratch in a very short period of time - often a day or a weekend.

Some jams have an official concept of "floater" artists, musicians, and sound designers, who can sign up without a development team, and the organizers will attempt to matchmake them with one or more development teams who are in need of visual & audio content. Even without official matchmaking, firing off a tweet on the jam's hashtag to offer music support is likely to draw the interest of at least one developer.

Jam games themselves are often ephemeral, one-off prototypes that never go further, but sometimes you hit on some gold that's worth developing to a full release (examples from jams in my area include Toto Temple, Mount Your Friends, Super Time Force, Lovers in a Dangerous Spacetime, The Yawhg \- I have no affiliation with any of these games, I just think they and their creators are pretty awesome) :)

This one-off nature can be an asset for getting your foot in the door. The chance that you already have the perfect song for a major project in-development is slim, but a jam game is naturally malleable and shaped by the constraints of the timeframe / theme / available people. Get in early and the devs might be able to build a game around your music rather than the other way around, and be more willing to take risks on a sound or style they might not have thought of before.

Beyond the scope of any one game, the jam lets you develop relationships with developers, where you each know what it's like working with each other. The next time they're working on a commercial project and looking for music to commission or license, you'll be on their mind.

As an example, I had a great experience with an audio floater on my last jam game, and I've since commissioned them for additional sound and music. I'm planning to jam with them again this weekend.

---
Tags: music
---


# Question
Title: How can I handle delayed function calls?
I have objects, and each object has a function pointer that will be assigned a function. When the object is clicked, the assigned function will be called. I want to have a function do things with delay, meaning it would look something like this:

```
void function() {
    doSomething();
    wait(1000);     // either 1000 frames, or 1000 miliseconds
    doSomethingElse();
}

```

I heard threading shouldn't be abused, and main script should all be put in the same thread. There are lots of game engines out there that can handle such functions with a delay in time. My idea was to call the function in a new thread every time.

Is this a bad idea? If it is, how else would I manage to achieve this functionality?

Edit: the website asked to confirm it's not a duplicate question and I think it's not because it's a bit more complicated of an issue, even though it may use a similar solution.

# Answer
You could try a central Job manager that performs jobs in an asynchronous way.

The skeleton of the feature could look like this bastard c++/pseudocode:

```
struct Job
  double mTimer;
  std::function<void>() mFunction;

class JobManager
  addJob(Job job) { mJobs.insert( job ); }

  std::list<Job> mJobs;

  perFrameExecuteJob(deltaTime){
    // Iterate through all the jobs that are to be done, reduce the time left by the dt.
    // If the delay has expired, perform the job, and remove it from the set of jobs to
    // do.
    std::list<Job>::iterator it = mJobs.begin();

    while( it != mJobs.end() ) {
      it->mTimer -= deltaTime;
      if ( it->mTimer <= 0 ) {
        it->mFunction();
        it = mJobs.remove(it);
      }
      else {
        it++;
      }
    }
  }

```

Basically, a `Job` represents a unit of work and it can be delayed.

You'd do something like this to add a `Job` to the `JobManager`:

```
void function(JobManager& aJobManager){
    doSomething();
    Job job;
    job.mTimer = 1000;
    job.mFunction = doSomethingElse;
    aJobManager.addJob( job );
}

```

And you'd call

```
mJobManager.perFrameExecuteJob( dt );

```

every frame from your main loop.
> 4 votes

---
Tags: c++
---


# Question
Title: How do I change the game object on a button click?
I have a five game objects (`ornament1`, `ornament2`, `ornament3`, `ornament4` and `ornament5`) and two buttons (*"Next"* and *"Previous"*). When I click *"Next"*, the object should change from `ornament1` to `ornament2`. When I click *"Next"*, again, it should change from `ornament2`to `ornament3`; when I then click *"Previous"* it should change from `ornament3`to `ornament2`.

I have the *"Next"* button working, but the *"Previous"* button is not working. How do I change the game object on a button click?

---

Here is my code:

```
if(GUI.Button(new Rect(10, 20, 80, 50), "Ornament1"))
{
    Debug.Log("hhhhhhhhhhhhhhhhhhhhhhh" + countbool);

    if(count==0)
    {
        Debug.Log("hhhhhhhhhhhhhhhhhhhhhhh");
        ornament1.transform.position = new Vector3(-0.1428955f, -0.1894745f, 4.108555f);
        ornament1.SetActive(true);
        ornament2.SetActive(false);
        ornament3.SetActive(false);
        ornament4.SetActive(false);
        ornament5.SetActive(false);
        count++;
    }
    else if(count == 1)
    {
        ornament2.transform.position = new Vector3(-0.1428955f, -0.1894745f, 4.108555f);
        ornament2.SetActive(true);
        ornament1.SetActive(false);
        ornament3.SetActive(false);
        ornament4.SetActive(false);
        ornament5.SetActive(false);
        count++;
    }
    else if(count == 2)
    {
        ornament3.transform.position = new Vector3(-0.1428955f, -0.1894745f, 4.108555f);
        ornament3.SetActive(true);
        ornament1.SetActive(false);
        ornament2.SetActive(false);
        ornament4.SetActive(false);
        ornament5.SetActive(false);
        count++;
    }
    else if(count == 3)
    {
        ornament4.transform.position = new Vector3(-0.1428955f, -0.1894745f, 4.108555f);
        ornament4.SetActive(true);
        ornament3.SetActive(false);
        ornament1.SetActive(false);
        ornament2.SetActive(false);
        ornament5.SetActive(false);
        count++;
    }
    else if(count == 4)
    {
        //ornament1.SetActive(true);
        ornament5.transform.position = new Vector3(-0.1428955f, -0.1894745f, 4.108555f);
        ornament5.SetActive(true);
        ornament3.SetActive(false);
        ornament1.SetActive(false);
        ornament2.SetActive(false);
        ornament4.SetActive(false);
        count++;
    }
}

```

# Answer
> 2 votes
We know that your *"Next"* button works; at least, *mostly*. As such, we simply need to expand on your base code. That said, there are a few changes I make:

* I move all game objects into an array. Given the nature in which you are using them, this makes more logical sense. We can also directly access them using an integer index, where we could not, if we simply included the number in the actual name.
* I change the name of `count` to `currentOrnamentID`, as this value appears to point to the current game object, which does not really make sense as a "count".
* I store `originPosition` as a class member. That way, if you ever need to change this position, you change it once. Furthermore, I believe it might be a little lighter on the garbage collecting, by passing values into an already-existing `Vector3` instead of creating a new one.
* In your last `if` statement, that is, where `count == 4`, you still increment `count`. In such cases, you can end up with logic errors, as you are effectively moving on to a game object that does not exist (remember, you say that you only have 5 game objects). I have adjusted the logic to overlap; selecting *"Next"* on the last game object will return you to the first game object.
* You were previously resetting the `SetActive` for every game object, with each selection. This is unnecessary, as we should know what the last game object was. We only need to set the previous game object to `SetActive(false)`.

---

As such, you can see the logic, below. All you need to do is call `Next()` from the *"Next"* button, and `Previous()` from the *"Previous"* button. We then take the `currentOrnamentID`, and use it to determine what game object is currently displayed. We adjust this value, accordingly, before we send the new `currentOrnmanetID` and the previous `currentOrnamentID` by *value* to a `EnableOrnament` method. You will notice we pass a lot of direct values in; this is just a semantic difference in efficiency. We already know the exact values that should be passed, both to the new `currentOrnamentID` and `EnableOrnament`, given the specific context. No need to "work it out" again, by calling to the actual variables or performing `++`.

```
int currentOrnamentID = 0;
public GameObject[] ornaments;
public Vector3 originPosition = new Vector3(-0.1428955f, -0.1894745f, 4.108555f);

private void Next
{
    switch(currentOrnamentID)
    {
        case 0:
            currentOrnamentID = 1;
            EnableOrnament(1, 0);
            break;
        case 1:
            currentOrnamentID = 2;
            EnableOrnament(2, 1);
            break;
        case 2:
            currentOrnamentID = 3;
            EnableOrnament(3, 2);
            break;
        case 3:
            currentOrnamentID = 4;
            EnableOrnament(4, 3);
            break;
        case 4:
            currentOrnamentID = 0;
            EnableOrnament(0, 4);
            break;
    }
}

private void Previous
{
    switch(currentOrnamentID)
    {
        case 0:
            currentOrnamentID = 4;
            EnableOrnament(4, 0);
            break;
        case 1:
            currentOrnamentID = 0;
            EnableOrnament(0, 1);
            break;
        case 2:
            currentOrnamentID = 1;
            EnableOrnament(1, 2);
            break;
        case 3:
            currentOrnamentID = 2;
            EnableOrnament(2, 3);
            break;
        case 4:
            currentOrnamentID = 3;
            EnableOrnament(3, 4);
            break;
    }
}

private void EnableOrnament(int newID, int previousID)
{
    ornaments[previousID].SetActive(false);
    ornaments[newID].SetActive(true);

    ornaments[newID].transform.position = originPosition;
}

```

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


# Question
Title: How do I set up a bullet to fire towards the mouse pointer?
I am making an FPS, in Unity. I have a player with a gun, and I have a bullet prefab. I changed the mouse pointer to look like a crosshair, but I don't know how to place the bullet where the crosshair is aiming.

The player movement is on the x and z axis. I have done lots of research on the Internet, and couldn't find anything suitable; most of what I found, I could not understand enough to change it according to my needs.

How do I set up a bullet to fire towards the mouse pointer?

# Answer
If you would like to use actual bullet prefab instead of raycast, then what I would do is: (Keeping in mind it's an FPS)

1. Get the mouse position in world space `.ScreenToWorldPoint()`
2. Get direction between camera and that point
3. Fire a bullet from the camera in that direction (by using instantiate and then adding force) OR you could make the bullet look at that point and add force forwards this could work better as your bullets rotation would be correct

P.S. you may need to adjust an individual axis value for the first step if it's too close to the camera.
> 1 votes

---
Tags: unity
---


# Question
Title: How do I change the sprite of a player in Unity?
I am making a simple game in Unity, using C#. The game is about a blade that flies and collects coins. I want to make a shop where the player can change the image of the main character in the game.

I have variable that change the value according to the character the player chose; for example, if the player chose the yellow blade, the value of the variable would be 1. I don't know how to display different images for the blade object, according to this variable.

How do I change the sprite of a player in Unity?

# Answer
If your player has a SpriteRenderer component then all you need to do is,

```
public Sprite newSprite;

GetComponent<SpriteRenderer>().sprite = newSprite;

```

Then assign a Sprite (image) that you want to change to, you can also change the variable from script.
> 1 votes

---
Tags: unity, sprites
---


# Question
Title: How to calculate the stopping distance of a wheel collider?
I have an 'AI' bus in my game that needs to pull over occasionally at a bus stop. What I want to do is change the acceleration and brake force based on the stopping distance of the bus. I don't want to simply use the distance between the bus stop and the bus because each time the bus pulls over, it could be traveling at a different speed.

Right now it uses the distance between the bus stop and the bus. It doesn't really work well though because if a bus is traveling faster, it will take a longer distance to stop and will likely go past the bus stop. Same thing if it were going slower.

How do I calculate the stopping distance my bus will take to come to a complete stop?

# Answer
> 0 votes
I ended up using a simple speed-distance-time calculation, and a velocity calculation. This is the code I used:

```
float time = ((distance / currentSpeed) / timeFactor);

float acceleration = (-currentSpeed / time) / vFactor;

v = acceleration;

```

`timeFactor` and `vFactor` are just arbitrary values, which happened to be 1 and 15 respectively.

This may not work for most other people however as this was quite specific to my code.

# Answer
> 3 votes
Let's say that at some point in time you have the current speed `v0` of your bus, which is at some position `x0`, and it needs to stop at position `xs` (s stands for stop).

TL;DR: You have to exert the following force `f` on the bus:

```
f = 0.5 * m * v0^2 / (x0 - xs)

```

where `m` is the mass of the bus.

Details: The easiest way is to exert a constant force that will drive the bus to a parabolic (in time) curve ending exactly at the bus stop. The equation for the position `x` at time `t`, and for the velocity `v` are

```
x = x0 + v0 * t + 0.5 * a * t^2
v = v0 + a* t

```

where `a` is the acceleration, which is what we want to calculate. From the second equation, get `t` as a function of `v`, and plug into the first equation. In this way, you eliminate `t` and find the equation for `x` as function of `v`:

```
x = x0 + 0.5 * (v^2 - v0^2) / a

```

Now *impose* that at `v = 0` you want `x = xs`, and solve for `a`. You get

```
a = 0.5 * v0^2 / (x0 - xs)

```

from which you get the force by multiplying with the mass `m`.

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


# Question
Title: How to create a 3D network-like interactive model?
link: Link to video. it's a small video only 1 min 40 sec I have included a link to the video which shows what I am trying to achieve, I am a beginner and I don't have any idea to do it, also I am using this for something like showing the network I have to people and not for game development, If my question is not clear please comment I will try to clear the problem with my question

# Answer
> -1 votes
You have to generate random location position of items and connect those items with LineRenderer with the help of position. Look for how line are drawing from one point to another in the world space.

---
Tags: unity, 3d
---


# Question
Title: Updating Json files in a Unity game - What am I doing wrong?
I am working in Unity, on my first project. I am working on a turn-based RPG, and I am having a hard time figuring out my back end.

I'm currently using JSON files to store my data, which are then converted into objects and processed in C#. So far so good, but I have reached a road block when trying to save data back into a JSON file.

For example, lets say I have a character file such as: `[{"name":"John", "CurrentHP": 100, "MaxHP": 100},{"name":"Paul", "CurrentHP": 200, "MaxHP": 200}]`. After a combat, John loses 30 hp. How do I save this data back to that JSON file, so it reads as `[{"name":"John", "CurrentHP": 70, "MaxHP": 100},{"name":"Paul", "CurrentHP": 200, "MaxHP": 200}]`?

The tutorials I've watched all talk about serializing the object back into a JSON file, but this would involve deleting the whole file and creating a new one with the new information. This sounds like a very ineffective approach, especially for some large 'tables' in my game. There needs to be a way to update just one attribute from one of the IDs in a given JSON file.

How do I efficiently update individual JSON rows?

# Answer
> 3 votes
JSON is a string-based format. When you change the length of something in a JSON file (for example by changing `"CurrentHP": 99` to `"CurrentHP": 101` everything which comes after that in the JSON file needs to be rewritten because it's now at the wrong offset. That's how string-based file formats work. For that reason JSON libraries rarely support in-place replacement of individual fields, and Unity is no exception.

To mitigate the problem you might want to avoid too large JSON files. Split information into multiple files instead. For example, when you have a large table of objects, make each row an individual file. There is no law which says each savegame must be a single file and can not be a directory of multiple files.

Alternatively, you could use a proper database. Like SQLite, for example.

You should also avoid unnecessary saving. You generally don't need to save the complete gamestate whenever anything in the game changes. It is completely adequate to save when the player tells you to and/or autosave at regular checkpoints.

# Answer
> 0 votes
Make two files, GameData.json for storing actual data and GameState.json for holding the the current state. When your character initialized first time, assign their stats from GameData. When saving state of your character, write on GameState. SO next time when your character load, get state from GameState.

---
Tags: unity, savegame, json
---


# Question
Title: How can I make trailing ghost effect (3d game)?
I'm trying to draw previous frame of animation on screen

you can see this effect here: https://youtu.be/WNL\_KJNl6pU

**Mortal Combat X (left)** , ***Street Fighter Alpha 2 (right)***:

This effect also found in animation software and called onion skinning:

I've implemented this by spawning object every second but I think It is possible with shader.

---

# Update

I could make this effect by using RenderTexture for capturing previous frame , but I can't remove background color :(

I tried with Blending and grab pass but don't work(it was rendered normally)!!

sources :

https://github.com/smkplus/TrailingFX

https://unitylist.com/r/4tp/unity-fluid-2d-blur-image-effect

# Answer
> 2 votes
I would solve this using post processing. You find some way to mask out your ghosting objects (stencil buffer, render layers, w/e) then create a compositing PP effect that combines the current render with the previous renders at a lower opacity. Since you're just pasting new information on top of the old render, you can stack all the previous renders in one texture. This is essentially onion skinning.

You would control how many "ghosts" get displayed based on how quickly you decrease your opacity.

The quick proof of concept I made looks like this (they already faded before I got the screenshot)

---
Tags: unity, 3d, shaders
---


# Question
Title: Binding Nested JSON To Dictionary Not Working
I am creating nested JSON and binding it with the class. But It doesn't bind with the class.

JSON:

```
 {
  "PuzzleData": {
    "Category1": {
      "Cultus": {
        "Type": "Car",
        "Name": "Cultus",
        "Item1": "gate",
        "Item2": "window",
        "Item3": "tyre",
        "Item4": "tyre"
      },
      "Lion": {
        "Type": "Lion",
        "Name": "Animal",
        "Item1": "legs",
        "Item2": "hands",
        "Item3": "head",
        "Item4": "eyes"
      }
    }
  }
}

```

Class:

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

[System.Serializable]
public class PuzzleGameData{

    public Dictionary<string, Category1> PuzzleData;

    [System.Serializable]
    public class Category1
    {
        public string Type;
        public string Name;
        public string Item1;
        public string Item2;
        public string Item3;
        public string Item4;
    }
}

```

Any help would be appreciated. Thanks.

# Answer
Currently Unity 5's JSON utility is not fully capable of doing all the neat tricks you might expect. For instance, it can't do an array of objects that contain other arrays. You can hack the json string with wrapper classes to make it work for that case. For your Dictionary class it may be the same issue. I don't know how to hack that to make it work, but here is an example of using wrapper classes to make arrays within arrays work.

```
  public string CreateJSONStringFromArray(SaveableObject[] save_obj_array)
    {

        string building_json_string = string.Empty;

        for (int i = 0; i < save_obj_array.Length; i++)
        {

            if (building_json_string != string.Empty) building_json_string = building_json_string + ",";

            string js_converted = JsonUtility.ToJson(save_obj_array[i] );

            building_json_string = building_json_string + js_converted;
        }

        //this is the important part right here
        building_json_string = "{\"Items\":[" + building_json_string + "]}";
        return building_json_string;
    }

    //for reading the values back from json
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return UnityEngine.JsonUtility.ToJson(wrapper);
    }

    //for reading the values back from json
    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }

}

[System.Serializable]
public class SaveableObject
{
    public string object_name_to_save;
    public string something_else_to_save;
    public string[] items;//with an internal list.

}

```
> 1 votes

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


title: Strange Light Angles in Unity

text:
# Question
Title: Strange Light Angles in Unity
I'm quite sure that I'm missing something very simple here, but I'm a complete Unity noob and I absolutely can't figure out what I'm seeing.

I'm trying to light a sphere from both sides, perpendicular to the camera angle, to create an effect where each side of the sphere is illuminated but there's a strip of darkness down the center. Instead, I'm getting really weird angles from the two lights.

My setup (I've quintuple checked all numbers)...

* A single sphere (textured like Mars) at position (0, 0, 0).
* An orthographic camera pointed at it from position (0, 0, -20) and rotation (0, 0, 0).
* Two Point lights at (-5, 0, 0) and (5, 0, 0), with the same intensity and all other light settings.

By my understanding, that should position each light equidistant from the sphere, exactly on either side from the camera's POV. Sort of like a capital " T " configuration. In theory their shine on the sphere should be mirrored on each side, complimentary angles toward the sphere from exactly horizontal. Instead, I'm getting this:

Left Light...

Right Light...

So, instead of being horizontal and mirrored, it appears as though the Right Light is significantly closer to the camera than the Left Light along the Z axis, and they both seem to be somewhat below the vertical center of the sphere (despite all elements having a Y value of zero).

Even weirder, viewing it in the Scene panel from above, there's a spiral pattern of darkness when both lights are on, rather than a single dark band between them...

Can someone help me out here? Does Unity handle perspective in a way I'm not getting, or have I messed up my arrangement of elements? And aside from eyeballing it, what positions should I use to create the effect I'm going for?

# Answer
So, thanks to DMGregory in the comments, I learned about the need to "unpack" the normal data from the texture file in my custom shader. It was a super-easy fix, though. In my custom surface shader, I got the normal data for the vertex and passed it straight through...

```
half4 n = tex2D (_BumpMap , IN.uv_BumpMap);
o.Normal = n;

```

When really what I needed to be doing was unpacking that data before passing it to the output. Simply changing the above code to...

```
half4 n = tex2D (_BumpMap , IN.uv_BumpMap);
o.Normal = UnpackNormal(n);

```

...seemed to do the trick!
> 1 votes

---
Tags: unity, lighting, transformation, perspective
---


title: Is it reasonable to use FreeType

text:
# Question
Title: Is it reasonable to use FreeType
Won't it slow my game if I use FreeType lib and convert 2 fonts from .ttf instead of using preloaded BitmapFont .png? Or may be FreeType so fast, that I can use fonts both ways? All I need is to change color and size of my text. P.S. I use 3 fonts in my project

# Answer
> 13 votes
If you use a font rendering engine like FreeType, then the most common mistake is to re-render strings every frame. This is pointless, because when you render a string, it will usually be on the screen unchanged for at least a few seconds.

When you want to display a text, render that text to a texture once and then draw that texture instead of re-rendering the text. When you do this, the cost of text-rendering will only apply the first time you need to render a given string with given settings. On any subsequent frame, the cost of displaying that string is the same as for drawing any other sprite of that size.

A solution which I found quite handy in various projects was to have a `TextRenderingCache` class to manage cached font renderings. It usually has a hash table with string plus render settings (font, color, size, etc.) as key and a texture with the rendering as value. When a given rendering is requested from the TextRenderingCache class, it checks if it already has that rendering, and if not it creates one. Dropping renderings from the hash-map which were not used for several seconds to avoid memory leakage is optional (some games need this, some do not).

By the way: FreeType already comes with a rendering cache system. But it is only used when you use it explicitly.

# Answer
> 4 votes
Yes, Freetype is reasonable. If you use .png files, you have to make one for EVERY size and EVERY color, and that may occupy *10* times the space a .ttf file takes up. **Goodbye, free space** on android and iOS devices. Moreover, you just have to get 1 .ttf file, and that's it. Hope I helped you!

---
Tags: libgdx, fonts
---


# Question
Title: Unity Animation Controller: Is the "atomic" attribute in 4.6.3 the same as the "has exit time" attribute in 5.0?
I'm viewing a tutorial based on Unity 5.0. In this version, I see an option whose name is: `Has Exit Time`:

But on my Unity, version 4.6.3, I don't have this option. Instead I have an option called `Atomic`.

My guess is that these options mean the same thing. That is, if this box is checked, then the controller should finish playing this state before moving to a new state. But I'm not sure here. If my guess is wrong, which option is equivalent to `Has Exit Time` in Unity 4.6.3 ?

Thanks :)

# Answer
> 1 votes
No, they're two different things.

`HasExitTime`: if a transition has this option activated, it means that it will jump to the new state after a certain `ExitTime` (1 ExitTime = 1 Full Animation clip) has passed. If it's disabled, then that transition will be executed only if certain conditions will be met (added in the `Conditions` list) - until then, the current state will loop indefinitely.

`Atomic`: this has been changed in Unity 5 as the `Interruption Source` setting option - the old `Atomic` is equivalent to the `None` option, and it means that the transition cannot be interrupted by other conditions triggering other transitions, so it will be completed no matter what else happens.

# Answer
> 0 votes
Now that I'm testing it looks like this may be a different setting they've added, and what used to be called "atomic" is in that new Settings menu (note the word Settings with an arrow, just below Has Exit Time). It looks like now you might want to look in that menu and set Interruption Source to Current State; clear as mud \>:(

Also, every transition I've tested needs "Has Exit Time" off, so I'm not sure why it defaults on.

---
Tags: unity, animation
---


title: How to recalculate AABB after rotation?

text:
# Question
Title: How to recalculate AABB after rotation?
I'm facing a problem trying to calculate the AABB on my models after rotation is applied. The rotation is not applied on the vertex positions directly, but in a seperate rotation matrix - just multiplied with the projection matrix and set as uniform. Currently I'm calculating the min/max of the vertexes on all three axes (x, y, z) to calculate the AABB. This works well, as long as the model is unrotated.

```
AABB calculateAabb() {
    glm::vec3 center, extend;
    glm::vec3 min, max;
    for (size_t i = 0; i < getVertexCount(); ++i) {
      if (positions[i * 3] < min.x){
        min.x = positions[i * 3];
      }
      if (positions[i * 3 + 1] < min.y) {
        min.y = positions[i * 3 + 1];
      }
      if (positions[i * 3 + 2] < min.z) {
        min.z = positions[i * 3 + 2];
      }
      if (positions[i * 3] > max.x) {
        max.x = positions[i * 3];
      }
      if (positions[i * 3 + 1] > max.y) {
        max.y = positions[i * 3 + 1];
      }
      if (positions[i * 3 + 2] > max.z) {
        max.z = positions[i * 3 + 2];
      }
    }
    extend = (max - min) * 0.5f;
    center = min + extend;
    return AABB(center, extend);
  }

```

The std::vector `positions[]` contains all vertexes in the order x, y, z - `getVertexCount()` returns `positions.size()/3`. My rotation matrix is described by a single angle on the y axis `glm::eulerAngleY(glm::radians(angle));`.

My question is: is there any way to calculate the AABB for the rotated model without applying the rotation matrix to all the vertexes individually? How can I get min/max values on the axes from a rotated coordinate system?

# Answer
> 1 votes
It depends on the shape of your meshes. For correct calculation of bounding boxes, only the vertices spanning the convex bounding body of a mesh have to be considered (In other words, vertices that are going "inwards" do not have to be considered).

However, depending on how often your mesh changes its shape, how often you are rotating your meshes and the shape of your meshes, it may or may not be faster to just apply the matrix to every vertex and do it the naive way than calculating which vertices need to be considered. In particular, this does not yield any performance improvement for convex shapes.

Apart from that, there are only approximations that can be made, for example:

* assume the body is a sphere for small rotations (thereby ignoring the rotation and leave the bounding box as is)
* precalculate a simpler bounding shape and use this for the AABB calculation

---
Tags: rotation, glm, aabb
---


# Question
Title: Unity Custom Sprite Shader: Don't write transparent pixels into Depth Buffer
For performance reasons, i have to create my own billboards to replace some geometry. I modified the standard sprite shader to `Cull Back` and `ZWrite On`. Now my billboard layers are rendered in the correct order, but the ones in the front cull the ones in the back, even on transparent areas. This is due to the shape of the Plane/Quad i used as basis.

You can see this on the following screenshots:

The transparent pixels are occluding the second layer.

Front piece drawn with white texture to show dimensions.

How can i modify my shader below to avoid drawing the transparent pixels into the depth buffer?

```
    // Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)

    Shader "Sprites/DefaultSingle"
    {
        Properties
        {
            [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
            _Color ("Tint", Color) = (1,1,1,1)
            [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
            [HideInInspector] _RendererColor ("RendererColor", Color) = (1,1,1,1)
            [HideInInspector] _Flip ("Flip", Vector) = (1,1,1,1)
            [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {}
            [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0
        }

        SubShader
        {
            Tags
            {
                "Queue"="Transparent"
                "IgnoreProjector"="True"
                "RenderType"="Transparent"
                "PreviewType"="Plane"
                "CanUseSpriteAtlas"="True"
            }
            Cull Back
            Lighting Off
            ZWrite On
            Blend One OneMinusSrcAlpha

            Pass
            {
            CGPROGRAM
                #pragma vertex SpriteVert
                #pragma fragment SpriteFrag
                #pragma target 2.0
                #pragma multi_compile_instancing
                #pragma multi_compile _ PIXELSNAP_ON
                #pragma multi_compile _ ETC1_EXTERNAL_ALPHA
                #include "UnitySprites.cginc"
            ENDCG
            }
        }
    }

```

# Answer
> 1 votes
Two answers here; the first one is the one that usually works best, the second is closer to the exact answer you requested.

**First method**

In your example image, it looks like you are drawing two perpendicular panels. If you split the panels at the point where they intersect, creating four panels, they will sort and draw properly without having to write to Z at all (though you still may, if you find some reason to). Since these sprites are in the transparent queue anyway, they will always be sorted back-to-front by Unity before rendering.

**Second method**

You'll need to copy the fragment shader out of UnitySprites.cginc for this one. In that shader, after reading the sprite texture color and multiplying it by the incoming color, use the `clip` instruction to skip drawing anything that has a low alpha value. In my current Unity version, the new fragment shader is:

```
        fixed4 frag(v2f IN) : SV_Target
        {
            fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;
            clip(c.a - 1.0 / 255.0);
            c.rgb *= c.a;
            return c;
        }

```

Change the `1` in the clip call to whatever alpha threshold (out of 255) you want.

This method is only good if you're using point filtering and you don't have any alpha values that aren't 0 or 1. An alpha value of, say, 0.5 will blend with whatever was already in the color buffer behind it, but still block later billboard pixels from rendering. You would be exchanging your large quad edge artifacts for fringe artifacts.

---
Tags: unity, shaders, depth-buffer, transparency
---


title: Event Trigger for sprite not working

text:
# Question
Title: Event Trigger for sprite not working
I have set up a script to set game objects as active/inactive depending on a particular number representing the index of a gameObject array. As you can see the image below. I have two buttons as shown on the page, a backward button and a forward button. I have attached event trigger components to each of the buttons so as to turn pages forward / backward depending on which button I click

The forward button works **but this is not the case with the backward button**. The function is not even being called. In fact only this sprite which on being clicked does not call the function assigned to it.

More details on the backbutton :

Here is the script for the MonsterRosterManager.cs

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

public class MonsterRosterManager : MonoBehaviour
{
    int MonsterPageNo;
    public GameObject[] MonsterPages;

    void Start()
    {
        MonsterPageNo = 0;
    }

    void Update()
    {
        switch (MonsterPageNo)
        {
            case 0:
                MonsterPages[0].SetActive(true);
                MonsterPages[1].SetActive(false);
                MonsterPages[2].SetActive(false);
                break;
            case 1:
                MonsterPages[0].SetActive(false);
                MonsterPages[1].SetActive(true);
                MonsterPages[2].SetActive(false);
                break;
            case 2:
                MonsterPages[0].SetActive(false);
                MonsterPages[1].SetActive(false);
                MonsterPages[2].SetActive(true);
                break;
        }
    }

    public void PrevMonsterPage()
    {
        Debug.Log ("Monster Page No to decrement: "+MonsterPageNo);
        MonsterPageNo -= 1;
        if (MonsterPageNo == -1)
            MonsterPageNo = 0;
    }

    public void NextMonsterPage()
    {
        Debug.Log ("Monster Page No to increment: "+MonsterPageNo);
        MonsterPageNo += 1;
        if (MonsterPageNo == MonsterPages.Length)
            MonsterPageNo = MonsterPages.Length - 1;
    }
}

```

Furthermore, the logs below show that the `NextMonsterPage()` function is called on clicking the forward button, **but no calls to the `PrevMonsterPage()` are being registered.**

What am I overlooking here?

# Answer
I see that the backward image is turned around 180 degrees to make it face opposite the direction of the forward image. This means that its front side is facing away from the camera. By default, this will cause the event system to ignore it. There are three easy fixes for this.

**1.** Make a copy of the arrow texture and use your image editor to reverse it. Use the copy instead of rotating the button.

**2.** Use an x scale of -1 instead of a y rotation of 180. This doesn't change the facing, so the image still gets events.

**3.** Find the `Graphic Raycaster` component (usually on same `GameObject` as the `Canvas` for your UI objects). Clear the checkbox labeled `Ignore Reversed Graphics`.

I'd probably go with **2**, since it uses the same graphic you already have and it doesn't run the risk of messing anything up by doing something unusual with the user interaction components.
> 4 votes

---
Tags: unity, c#, sprites, scripting, events
---


# Question
Title: How to reduce lag when rendering 40,000 sprites in Unity?
I am attempting to render 40,000 sprites: a grid of 200x200 with each grid node having a sprite renderer. All the way zoomed out I get about ~20 frames per second.

What would be the best way to optimize this? Eventually I want to have an even larger grid. The grid has to be changeable — I need to be able to change the ground/floor for that specific grid node.

# Answer
You will have to generate and manage your own tile grid mesh(es) by putting all your tile graphics into one large texture (atlas) and updating the UV coordinates in the generated meshes when those tiles have to change.

You'll want to split your map into smaller tilemap meshes to allow Unity to do **Frustum Culling** on groups of tiles while not having to process frustum culling over 40,000 objects.

For example, creating meshes of 50x50 tile subsections will reduce the number of objects Unity has to check for frustum culling down to 16 (4x4, * 50x50 = 200x200) instead of 40,000 individual objects.

Addendum: Unity team has been working on a **TileMap** feature for about 2 years now. If and when this becomes available in non-beta it may be a better solution than rolling your own. But as of today it is not available for production use.
> 1 votes

# Answer
Modern graphics APIs allow you to use a technique called instanced rendering. This is the go-to technique when you want to render a lot of the same thing. You basically tell the GPU to render something x amount of times and use a shader to decide where and what to do with them.

You can access this in Unity too: https://docs.unity3d.com/Manual/GPUInstancing.html
> 0 votes

# Answer
Try setting it to a really low resolution and applying a lot of anti-aliasing on a recursive way, so having several layers of anti-aliasing concatenated. I usually do that when I do audio reactive visuals on limited CPU and graphics card power on my MacBook.
> -1 votes

---
Tags: unity, 2d, textures, rendering, frame-rate
---


# Question
Title: Why are my chunks not showing in my Unity voxels engine?
I created a voxel engine in Unity. It worked fine until yesterday when I tried to remove the faces between chunks to create a seamless world.

Now there's just an empty world when entering the game. I hope that you can help me.

On a side note, I have an idea why it doesn't work. Lines 143 and 144 in Chunk.cs don't seem to be executed, that's why there are no blocks added, but I don't have an idea what's causing this.

Here's my code:

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

public class Chunk : MonoBehaviour
{
    public Transform player;
    public int UnloadingDistance;
    public string pos;

    public static int CHUNK_DIMENSION = 16;

    void Update()
    {
        if ((transform.position - player.position).magnitude > UnloadingDistance)
        {
            Unload();
        }
    }

    public void Unload()
    {
        //TODO save
        Player.chunks.Remove(pos);
        Destroy(gameObject);
    }

    public static void Load(Transform player,int LoadingDistance,int UnloadingDistance)
    {
        Vector3 start = player.position - new Vector3(LoadingDistance, LoadingDistance, LoadingDistance);
        Vector3 end = player.position + new Vector3(LoadingDistance, LoadingDistance, LoadingDistance);
        start.x = Mathf.Clamp(start.x, -50000000, 50000000);
        end.x = Mathf.Clamp(end.x, -50000000, 50000000);
        start.y = Mathf.Clamp(start.y, 0, 512);
        end.y = Mathf.Clamp(end.y, 0, 512);
        start.z = Mathf.Clamp(start.z, -50000000, 50000000);
        end.z = Mathf.Clamp(end.z, -50000000, 50000000);
        for (int x = Mathf.FloorToInt(start.x / CHUNK_DIMENSION) * CHUNK_DIMENSION; x < Mathf.FloorToInt(end.x / CHUNK_DIMENSION) * CHUNK_DIMENSION; x += CHUNK_DIMENSION)
        {
            for (int y = Mathf.FloorToInt(start.y / CHUNK_DIMENSION) * CHUNK_DIMENSION; y < Mathf.FloorToInt(end.y / CHUNK_DIMENSION) * CHUNK_DIMENSION; y += CHUNK_DIMENSION)
            {
                for (int z = Mathf.FloorToInt(start.z / CHUNK_DIMENSION) * CHUNK_DIMENSION; z < Mathf.FloorToInt(end.z / CHUNK_DIMENSION) * CHUNK_DIMENSION; z += CHUNK_DIMENSION)
                {
                    if ((new Vector3(x,y,z)-player.position).magnitude > LoadingDistance) { continue; }
                    if (!Player.chunks.ContainsKey(x.ToString() + ";" + y.ToString() + ";" + z.ToString()))
                    {
                        loadChunk(x, y, z, UnloadingDistance, LoadingDistance, player);
                    }
                }
            }
        }
    }

    private static void loadChunk(int x, int y, int z, int UnloadingDistance, int LoadingDistance, Transform player)
    {
        GameObject chunk = Instantiate(Player.ChunkPrefab);
        chunk.transform.position = new Vector3(x, y, z);
        Chunk c = chunk.GetComponent<Chunk>();
        c.pos = x.ToString() + ";" + y.ToString() + ";" + z.ToString();
        c.UnloadingDistance = UnloadingDistance;
        c.player = player;
        Player.chunks.Add(c.pos, c);

        new Thread(delegate () {
            List<Vector3> verts = new List<Vector3>();
            List<int> tris = new List<int>();
            List<Vector2> uvs = new List<Vector2>();
            List<Vector3> norms = new List<Vector3>();
            List<int> types = new List<int>();
            List<Vector3> positions = new List<Vector3>();

            int[,,] existants = new int[CHUNK_DIMENSION + 2, CHUNK_DIMENSION + 2, CHUNK_DIMENSION + 2];

            System.Random r = new System.Random();
            for (int bx = -1; bx < CHUNK_DIMENSION + 1; bx++)
            {
                for (int bz = -1; bz < CHUNK_DIMENSION + 1; bz++)
                {
                    int perlinHeight = Mathf.RoundToInt(Mathf.PerlinNoise(0.01f * (bx + x) + 0.001f, 0.01f * (bz + z) + 0.001f) * 100f) + 156;
                    for (int by = -1; by < CHUNK_DIMENSION + 1; by++)
                    {
                        Vector3 cPos = new Vector3(
                            x + (bx < 0 ? -1 : bx < CHUNK_DIMENSION ? 0 : 1),
                            y + (by < 0 ? -1 : by < CHUNK_DIMENSION ? 0 : 1),
                            z + (bz < 0 ? -1 : bz < CHUNK_DIMENSION ? 0 : 1)
                        );
                        Vector3 bPos = new Vector3(
                            bx < 0 ? CHUNK_DIMENSION - 1 : bx >= CHUNK_DIMENSION ? 0 : bx,
                            by < 0 ? CHUNK_DIMENSION - 1 : by >= CHUNK_DIMENSION ? 0 : by,
                            bz < 0 ? CHUNK_DIMENSION - 1 : bz >= CHUNK_DIMENSION ? 0 : bz
                        );
                        int type = -1;
                        if (Player.WorldData != "")
                        {
                            string btype = Player.tryGetB64Arr(Player.WorldData, new int[] { (int)cPos.x, (int)cPos.y, (int)cPos.z, (int)bPos.x, (int)bPos.y, (int)bPos.z });
                            if (btype != "")
                            {
                                type = Convert.ToInt16(btype);
                            }
                        }
                        if (type == -1)
                        {
                            if (by + y > perlinHeight)
                            {
                                if (by + y < Player.SeaLevel)
                                {
                                    type = Player.WaterBlock;
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else if (by + y == perlinHeight)
                            {
                                type = Player.ToppingBlock;
                            }
                            else if (by + y == 0)
                            {
                                type = Player.GroundBorderBlock;
                            }
                            else if (by + y < Player.GroundMedianBorder * perlinHeight)
                            {
                                type = Player.GroundBlocks[r.Next(0, Player.GroundBlocks.Length - 1)];
                            }
                            else if (by + y < Player.MedianUpperBorder * perlinHeight)
                            {
                                type = Player.MedianBlocks[r.Next(0, Player.MedianBlocks.Length - 1)];
                            }
                            else
                            {
                                type = Player.UpperBlocks[r.Next(0, Player.UpperBlocks.Length - 1)];
                            }
                        }
                        if (type == -1)
                        {
                            continue;
                        }
                        existants[bx+1, by+1, bz+1] = Player.TransparentBlocks.Contains((int)type) ? 1 : 2;
                        if (bx > -1 && bx < CHUNK_DIMENSION && by > -1 && by < CHUNK_DIMENSION && bz > -1 && bz < CHUNK_DIMENSION)
                        {
                            types.Add(type);
                            positions.Add(new Vector3(bx, by, bz));
                        }
                    }
                }
            }

            for (int i = 0; i < types.Count;i++)
            {
                addBlock(verts, tris, uvs, norms, types[i], positions[i],existants);
            }

            Player.LoaderQueue.Add(delegate ()
            {
                if (chunk == null)
                {
                    return;
                }

                Mesh mesh = chunk.GetComponent<MeshFilter>().mesh;
                mesh.SetVertices(verts);
                mesh.SetTriangles(tris, 0);
                mesh.SetUVs(0, uvs);
                mesh.SetNormals(norms);
                mesh.RecalculateTangents();
                chunk.GetComponent<MeshFilter>().mesh = mesh;
                chunk.GetComponent<MeshCollider>().sharedMesh = mesh;
            });
        }).Start();
    }

    private static void addBlock(List<Vector3> verts,List<int> tris, List<Vector2> uvs, List<Vector3> norms,float type,Vector3 localPos, int[,,] existants)
    {
        Debug.Log(type + ";" + localPos);
        float us = (type % 8f) / 8f + 0.0002f;
        float vs = Mathf.Floor(type / 8f) / 8f + 0.0002f;
        float ue = us + 0.1246f;
        float ve = vs + 0.1246f;
        int si = 0;
        int selfLevel = Player.TransparentBlocks.Contains((int)type) ? 1 : 2;

        selfLevel = 10;

        //back
        if (existants[(int)localPos.x,(int)localPos.y,(int)localPos.z-1] < selfLevel)
        {
            si = verts.Count;
            verts.Add(new Vector3(0, 0, 0) + localPos);
            uvs.Add(new Vector2(us, vs));
            verts.Add(new Vector3(0, 1, 0) + localPos);
            uvs.Add(new Vector2(us, ve));
            verts.Add(new Vector3(1, 0, 0) + localPos);
            uvs.Add(new Vector2(ue, vs));
            verts.Add(new Vector3(1, 1, 0) + localPos);
            uvs.Add(new Vector2(ue, ve));
            norms.Add(Vector3.back);
            norms.Add(Vector3.back);
            norms.Add(Vector3.back);
            norms.Add(Vector3.back);
            tris.Add(si); tris.Add(si + 1); tris.Add(si + 2);
            tris.Add(si + 2); tris.Add(si + 1); tris.Add(si + 3);
        }

        //front
        if (existants[(int)localPos.x,(int)localPos.y,(int)localPos.z + 1] < selfLevel)
        {
            si = verts.Count;
            verts.Add(new Vector3(0, 0, 1) + localPos);
            uvs.Add(new Vector2(us, vs));
            verts.Add(new Vector3(1, 0, 1) + localPos);
            uvs.Add(new Vector2(ue, vs));
            verts.Add(new Vector3(1, 1, 1) + localPos);
            uvs.Add(new Vector2(ue, ve));
            verts.Add(new Vector3(0, 1, 1) + localPos);
            uvs.Add(new Vector2(us, ve));
            norms.Add(Vector3.forward);
            norms.Add(Vector3.forward);
            norms.Add(Vector3.forward);
            norms.Add(Vector3.forward);
            tris.Add(si); tris.Add(si + 1); tris.Add(si + 2);
            tris.Add(si); tris.Add(si + 2); tris.Add(si + 3);
        }

        //right
        if (existants[(int)localPos.x+1,(int)localPos.y,(int)localPos.z] < selfLevel)
        {
            si = verts.Count;
            verts.Add(new Vector3(1, 0, 1) + localPos);
            uvs.Add(new Vector2(us, ve));
            verts.Add(new Vector3(1, 0, 0) + localPos);
            uvs.Add(new Vector2(us, vs));
            verts.Add(new Vector3(1, 1, 0) + localPos);
            uvs.Add(new Vector2(ue, vs));
            verts.Add(new Vector3(1, 1, 1) + localPos);
            uvs.Add(new Vector2(ue, ve));
            norms.Add(Vector3.right);
            norms.Add(Vector3.right);
            norms.Add(Vector3.right);
            norms.Add(Vector3.right);
            tris.Add(si); tris.Add(si + 1); tris.Add(si + 2);
            tris.Add(si); tris.Add(si + 2); tris.Add(si + 3);
        }

        //left
        if (existants[(int)localPos.x-1,(int)localPos.y,(int)localPos.z] < selfLevel)
        {
            si = verts.Count;
            verts.Add(new Vector3(0, 0, 1) + localPos);
            uvs.Add(new Vector2(us, ve));
            verts.Add(new Vector3(0, 1, 0) + localPos);
            uvs.Add(new Vector2(ue, vs));
            verts.Add(new Vector3(0, 0, 0) + localPos);
            uvs.Add(new Vector2(us, vs));
            verts.Add(new Vector3(0, 1, 1) + localPos);
            uvs.Add(new Vector2(ue, ve));
            norms.Add(Vector3.left);
            norms.Add(Vector3.left);
            norms.Add(Vector3.left);
            norms.Add(Vector3.left);
            tris.Add(si); tris.Add(si + 1); tris.Add(si + 2);
            tris.Add(si); tris.Add(si + 3); tris.Add(si + 1);
        }

        //top
        if (existants[(int)localPos.x,(int)localPos.y+1,(int)localPos.z] < selfLevel)
        {
            si = verts.Count;
            verts.Add(new Vector3(1, 1, 0) + localPos);
            uvs.Add(new Vector2(ue, vs));
            verts.Add(new Vector3(0, 1, 1) + localPos);
            uvs.Add(new Vector2(us, ve));
            verts.Add(new Vector3(1, 1, 1) + localPos);
            uvs.Add(new Vector2(ue, ve));
            verts.Add(new Vector3(0, 1, 0) + localPos);
            uvs.Add(new Vector2(us, vs));
            norms.Add(Vector3.up);
            norms.Add(Vector3.up);

```

# Answer
I fixed it. It was an IndexOutOfRangeException when getting/setting values in the existants array, that didn't show up in unity and just ended the thread. Although the faces between chunks are still visible.
> 1 votes

---
Tags: unity, c#, procedural-generation, voxels
---


# Question
Title: How to make the main menu screen fade out when the game starts in libGDX?
I am creating the main menu of my game, and I want the main menu screen to disappears with a fade out. I thought that if I used a `Stage` to make the menu and added buttons as actors, the menu would work...

But I get the following problem: If I add the `fadeOut(1)` in the click event of the button used to start the game, instead of having the whole screen fade out, only the buttons of the menu disappear. Probably using `Stage` is the wrong way to make menus, and I do not know the right way ...

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.phillips.mrbulb.MrBulb;

public class MenuState extends Estado {
    private Stage menu;
    private Texture fondo;
    private Drawable empz, instr, acrc, slir;
    private ImageButton empezar, instrucciones, acerca, salir;
    public MenuState(GameStateManager gsm) {
        super(gsm);
        fondo = new Texture("fondo_temp.png");
        empz = new TextureRegionDrawable(new TextureRegion(new Texture("Empezar.png")));
        instr = new TextureRegionDrawable(new TextureRegion(new Texture("Instrucciones.png")));
        acrc = new TextureRegionDrawable(new TextureRegion(new Texture("Acerca.png")));
        slir = new TextureRegionDrawable(new TextureRegion(new Texture("Salir.png")));
        empezar = new ImageButton(empz);
        empezar.addCaptureListener(new ClickListener(){
            public void clicked(InputEvent event, float x, float y){
                menu.addAction(Actions.fadeOut(1));
            }
        });
        empezar.setPosition(MrBulb.ANCHO/2 - 90,MrBulb.ALTO/2);
        instrucciones = new ImageButton(instr);
        instrucciones.setPosition(MrBulb.ANCHO/2 - 80,MrBulb.ALTO/2 - 90);
        acerca = new ImageButton(acrc);
        acerca.setPosition(MrBulb.ANCHO/2 - 62,MrBulb.ALTO/2 - 180);
        salir = new ImageButton(slir);
        salir.setPosition(MrBulb.ANCHO/2 - 33,MrBulb.ALTO/2 - 267);
        menu = new Stage();
        menu.addActor(empezar);
        menu.addActor(instrucciones);
        menu.addActor(acerca);
        menu.addActor(salir);
    }

    @Override
    public void update(float dt) {
        Gdx.input.setInputProcessor(menu);
        handleInput();
    }

    @Override
    public void handleInput() {

    }

    @Override
    public void render(SpriteBatch batch) {
        batch.begin();
        batch.draw(fondo,0,0,MrBulb.ANCHO, MrBulb.ALTO);
        batch.end();
        menu.act(Gdx.graphics.getDeltaTime());
        menu.draw();
    }

    @Override
    public void dispose() {
        fondo.dispose();
    }
}

```

What would be the correct way to make a menu for the game? Or, if using `Stage`, what would be the right way of coding it?

# Answer
Using `fadeOut` is the way to go. You just need to make sure that everything that you want to fade out is part of your `Stage`. You should start by adding an `Image` instead of directly rendering your background.

```
menu = new Stage();

/* Create your background as an actor instead of just a texture */
Image background = new Image(fondo);
background.setBounds(0, 0, MrBulb.ANCHO, MrBulb.ALTO);

menu.addActor(empezar);
menu.addActor(instrucciones);
menu.addActor(acerca);
menu.addActor(salir);
menu.addActor(background);

```

This will now appropriately fade out your background as well as the buttons. Also make sure to remove these lines from your render method so you don't double-render the background:

```
batch.begin();
batch.draw(fondo,0,0,MrBulb.ANCHO, MrBulb.ALTO);
batch.end();

```
> 1 votes

---
Tags: libgdx, screen
---


title: Implementing a resource bar with LibGdx

text:
# Question
Title: Implementing a resource bar with LibGdx
I am developing my first LibGdx game, and I would like some help understanding Scene2D/Ui.

So far I understand a "Stage" contains the various UI elements, and a "Table" contains the layout; an input processor can be assigned to buttons and stuff to define what they will do.

What I don't really understand clearly so far is how to utilise tables and skins, and if I'm doing this correctly.

So far I have a MainGameScreen class which extends Screen, and renders a Tiled map.

I want to render the UI on top of it, I have defined a Stage, a Table and a Skin, as well as a button; here are my relevant code snippets.

```
//declaration of stage, table, skin
public class MainGameScreen implements Screen, InputProcessor{
    ...
    private Stage stage;
    private Table table;
    private Skin skin;
}

//class constructor
public MainGameScreen(final MyGame game){
   ...
   stage = new Stage(new ScreenViewport());
   table = new Table();
   skin = new Skin(Gdx.files.internal("uiskin.json"));
   table.setFillParent(true);
   stage.addActor(table);
   button = new TextButton("TEST BUTTON", skin, "default");
   button.setWidth(200);
   button.setHeight(50);
   stage.addActor(button);

//Screen render function
public void render(float delta) {
    ...
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

```

It works, the Tiled map gets rendered, a button appears on the bottom left.

Now, please take a look at this Warcraft 2 screenshot: http://en.war2.ru/wp-content/uploads/2015/03/screenshot-14.png

I'd like to implement a top bar similiar to that, meaning "Menu" "Pause" buttons as well as rendering an icon + value for each resource (variable) at the top of the screen.

I understand that I'd have to use the Image widget for the icons, Label for text and Button for Menu and Pause, but I don't get how to lay them out properly using a Table and ensuring scaling.

I'd be grateful if someone could provide a simple implementation, or point me on the right direction.

# Answer
> 1 votes
To just create the top bar I would do something like this:

```
Image resourceImage1 = ...;
Label resourceLabel1 = ...;
...

Table table = new Table();

//Display at the top and occupy a 10th of the screen height
table.setBounds(0, screenHeight * .9, screenWidth, screenHeight *.1);
table.defaults().padRight(10); // All cells have a padding of 10px to the right

table.add(resourceImage1);
table.add(resourceLabel1).spaceRight(50); //Move next element 50px right
table.add(resourceImage2);
table.add(resourceLabel2).spaceRight(50);
...

stage.addActor(table);

```

This will align all of the above elements in a single row with some space in between them. If you need to create another row use `table.row();`. For a quick rundown of using the table take a look at the LibGdx wiki entry on them.

As for your concern on scaling take a closer look at Viewports. I see you're already using a `ScreenViewport` which does not support a constant size. Perhaps a `FitViewport` would be more suitable for you as it keeps the aspect ratio.

---
Tags: java, libgdx
---


# Question
Title: How to stop sprite when overlap on in libgdx?
How can I stop my player if he overlap or touch the ball? In my top down game my player is cat and I want to stop his moving or stack in that place of the ball is located if he hit the ball I'm using acceleromter to move the cat left and right.

Here is my code. How can I add collide method just like the image bellow? Thank's and advance!

```
// Load the sprite sheet as a texture
cat = new Texture(Gdx.files.internal("cat.png"));
catsprite = new Sprite(cat);
player = new Rectangle();
player.width = 20;
player.height = 80;
player.x = 300;
player.y = 0;

basketball = new Texture(Gdx.files.internal("ball.png"));
ball = new Circle();
ball.x = Gdx.graphics.getWidth() / 2;
ball.y = Gdx.graphics.getHeight() / 2;
ball.radius = basketball.getWidth() / 2;

```

In render method

```
camera.update();
TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
spriteBatch.draw(basketball, ball.x-ball.radius, ball.y-ball.radius);
spriteBatch.draw(currentFrame,player.x, player.y);// Draw current frame at (50, 50)

if(player.y < 0)
    player.y = 0;
if(player.y > 900 - 80)
    player.y = 700 - 80;

// check collision
if(Intersector.overlaps(ball, player)){
    tmp.set(player.x, player.y + player.height/2, player.width, player.height/2);

    if (Intersector.overlaps(ball, tmp)){
        //top half (or both top and bottom) hit
        Gdx.app.log("overlaps", "yes");
    } else {
        //bottom half hit
    }
}

//Mobile acceleration
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer)) {
    player.x -= Gdx.input.getAccelerometerX();
    player.y += Gdx.input.getAccelerometerY();
}

if (player.y > Gdx.graphics.getHeight() - 100)
    player.y = Gdx.graphics.getHeight() - 100;

if (player.x < 0) {
    player.x = 0;
    player.x += Gdx.graphics.getDeltaTime() * catSpeed;
}

if (player.x > Gdx.graphics.getHeight() - 250) {
    player.x = Gdx.graphics.getHeight() - 250;
}

```

# Answer
In your collision detection code you can do this to stop your player when he collides with the ball:

```
// check collision
if(Intersector.overlaps(ball, player)){
    tmp.set(player.x, player.y + player.height/2, player.width, player.height/2);

    if (Intersector.overlaps(ball, tmp)){
        //top half (or both top and bottom) hit
        Gdx.app.log("overlaps", "yes");
    } else {
        //bottom half hit
    }
} else {
    //Mobile acceleration
    if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer)) {
        player.x -= Gdx.input.getAccelerometerX();
        player.y += Gdx.input.getAccelerometerY();
    }
}

```

I've simply moved the movement code inside of the new `else { ... }` statement. This should completely stop the player if the player collides with the ball. Although this introduces a problem; if we collide with the ball we can never move our player again. To counteract this we have to move the player at least 1px outside of the ball. A very simple and inaccurate solution might look something like this:

```
if(Intersector.overlaps(ball, player)) {
    tmp.set(player.x, player.y + player.height/2, player.width, player.height/2);

    // The center of the ball
    Vector2 ballCenter = new Vector2(ball.x + ball.radius, ball.y + ball.radius);
    // The center of the cat
    Vector2 catCenter = new Vector2(cat.x + cat.width / 2, cat.y + cat.height / 2);
    // The vector pointing from the ball's center to the cat's center.
    Vector2 catBallVector = new Vector2(ballCenter).sub(catCenter);
    catBallVector.limit(pushDistance); //pushDistance is how far you should push your cat

    cat.setPosition(cat.x + catBallVector.x, cat.y + catBallVector.y);

    ... rest of code ...
} else {
    ... rest of code ...
}

```

Hopefully I answered your question. If you have any concerns feel free to post a comment!
> 3 votes

---
Tags: java, libgdx, collision-detection, intersection
---