# Question
Title: Constraining an orthographic camera to an isometric world
I am using Unity3D, and I am building an isometric world by rotating a plane on the Y axis by 4.205 units.

I am using an orthographic camera. I want to constrain the camera so that the viewport never shows the area outside of the world (in green).

1. How can I calculate the corner points of my rotated plane in screen coordinates, represented by green?
2. How do I stop the camera from scrolling to prevent it from showing the area outside the world, represented by gray?

# Answer
> 3 votes
**Restrict only camera viewport centre to ground plane**

You can find the working Unity project containing this code here.

```
using UnityEngine;
using System.Collections;

public class CameraAnchorController : MonoBehaviour
{
    public float xAcceleration = 0;
    public float yAcceleration = 0;
    public float accelerationRate; //set to 1 in inspector
    public Vector2 acceleration;
    public Vector2 velocity;

    float friction = 0.98f;
    public float xMin; //set to -5 in inspector
    public float xMax; //set to 5 in inspector
    public float yMin; //set to -5 in inspector
    public float yMax; //set to 5 in inspector
    //these -5/+d5 are because a Unity plane's origin is in the centre.

    void Update()
    {
        xAcceleration = 0;
        yAcceleration = 0;

        //acceleration
        xAcceleration += Input.GetKey(KeyCode.LeftArrow)    ? -1 : 0;
        xAcceleration += Input.GetKey(KeyCode.RightArrow)   ? +1 : 0;
        yAcceleration += Input.GetKey(KeyCode.UpArrow)      ? +1 : 0;
        yAcceleration += Input.GetKey(KeyCode.DownArrow)    ? -1 : 0;
        acceleration = new Vector2(xAcceleration, yAcceleration); //use Vector2 here or we incur extra, costly sqrt calls in magnitude.
        acceleration = Vector2.ClampMagnitude(acceleration, 1.0f); //normalize it.
        acceleration *= accelerationRate;

        //speed
        velocity += acceleration;
        velocity *= friction;

        //position
        float xPos = transform.localPosition.x + velocity.x * Time.deltaTime;
        float yPos = transform.localPosition.z + velocity.y * Time.deltaTime; //note the interchanged y/z here due to Unity's coord system.

        //We'd usually just use 2 Mathf.Clamp(val, min, max) calls here, but we need to know
        //the outcome of the clamping, so as to also restrict velocity if we hit a map side.
        if (xPos < xMin)
        {
            xPos = xMin;
            velocity = new Vector2(0, velocity.y);
        }
        if (xPos > xMax)
        {
            xPos = xMax;
            velocity = new Vector2(0, velocity.y);
        }
        if (yPos < yMin)
        {
            yPos = yMin;
            velocity = new Vector2(velocity.x, 0);
        }
        if (yPos > yMax)
        {
            yPos = yMax;
            velocity = new Vector2(velocity.x, 0);
        }

        xPos = Mathf.Clamp(xPos, xMin, xMax); //limit to the plane's x     extent in local space
        yPos = Mathf.Clamp(yPos, yMin, yMax); //limit to the plane's y (z) extent in local space

        //update transform
        transform.localPosition = new Vector3(xPos, 0, yPos);
    }
}

```

In Unity: Create a plane, create a sphere, then drag the sphere onto the plane so the plane is its parent. Now the sphere is moving in the plane's local space. You can name it "Camera anchor". Drag the Camera onto the anchor so that the anchor is its parent. Set your camera's x rotation to the required tilt in the inspector and its y rotation to 45; zero its position and then drag it out along local z axis to required viewing distance to see ground and anchor. Drag this script onto the anchor. Create a directional light. Using the arrow keys, you will see how the anchor restricts the camera's look vector (in centre of its viewport) so that it never leaves the ground plane. Notice that your controls are a bit funny, and treat up/down and left/right as diagonal planes. Fix is to replace:

```
    xAcceleration += Input.GetKey(KeyCode.LeftArrow)    ? -1 : 0;
    xAcceleration += Input.GetKey(KeyCode.RightArrow)   ? +1 : 0;
    yAcceleration += Input.GetKey(KeyCode.UpArrow)      ? +1 : 0;
    yAcceleration += Input.GetKey(KeyCode.DownArrow)    ? -1 : 0;

```

with

```
    if (Input.GetKey(KeyCode.UpArrow))
    {
        xAcceleration += +1;
        yAcceleration += +1;
    }
    if (Input.GetKey(KeyCode.DownArrow))
    {
        xAcceleration += -1;
        yAcceleration += -1;
    }
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        xAcceleration += -1;
        yAcceleration += +1;
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        xAcceleration += +1;
        yAcceleration += -1;
    }

```

Note that you can effectively zoom in and out by changing ortho camera's `size` in the inspector.

This eliminates any need to perform matrix transforms, and solves other problems (below).

**Restrict to camera edges to *near* ground plane edges**

Let's say things are exactly as in your diagram - tiny world relative to large camera viewport. In that case, I can see exactly how you expect this to work. We'd pan the red rectangle around in a screen-axis aligned rectangle that is a bit larger, and exactly contains the isometric ground plane. We'll call this Implementation Style A. This is what Bálint has very reasonably suggested, given your diagram. But what if you have a large map with smaller viewport? I doubt then that this will be the ideal solution for you: even with a map just 4x the size of that in your diagram, you're going to be able to scroll into large, dark spaces in the top left, top right, bottom left and bottom right of the map, because you're only restricting by a screen-space rectangle. Not good?

I imagine you'd then want a different mechanism, one which locks the camera so its centre can't leave the bounds of the ground plane; you could then never run the camera into large, void spaces. I've supplied this above, call it Implementation Style B.

In either implementation, you'll need sufficient dummy tiles on the outside of the ground plane to ensure that at maximum zoom, you will never see black space. I've seen this done in some of the XCom / UFO games. Calculating how many rows / columns of extra tiles you would need exactly, is going to depend on the `size` value on your camera (which links directly to viewport height in unity), and some calculation of your tile width as against your tile height, which can be accomplished with `Mathf.Sin()`. You may also need a `size` value that relates to horizontal vs vertical - that is as simple as `size * Screen.width / Screen.height`. Still, all of this is probably unnecessary as you can manually test how many tiles worth of buffering works for you. Test against a 2:1 screen ratio to be very sure you've got it covered.

For the above solution, to create a buffer space *inside your existing tile map*, replace this:

```
    //position
    float xPos = transform.localPosition.x + velocity.x * Time.deltaTime;
    float yPos = transform.localPosition.z + velocity.y * Time.deltaTime; //note the interchanged y/z here due to Unity's coord system.

```

with:

```
       //position
        float xPos = transform.localPosition.x + velocity.x * Time.deltaTime;
        float yPos = transform.localPosition.z + velocity.y * Time.deltaTime; //note the interchanged y/z here due to Unity's coord system.

        float buffer = 2f; //2 units in world space which might be 2 tiles across in your code.
        float xMinLimited = xMin + buffer;
        float xMaxLimited = xMax - buffer;
        float yMinLimited = yMin + buffer;
        float yMaxLimited = yMax - buffer;

        //We'd usually just use 2 Mathf.Clamp(val, min, max) calls here, but we need to know
        //the outcome of the clamping, so as to also restrict velocity if we hit a map side.
        if (xPos < xMinLimited)
        {
            xPos = xMinLimited;
            velocity = new Vector2(0, velocity.y);
        }
        if (xPos > xMaxLimited)
        {
            xPos = xMaxLimited;
            velocity = new Vector2(0, velocity.y);
        }
        if (yPos < yMinLimited)
        {
            yPos = yMinLimited;
            velocity = new Vector2(velocity.x, 0);
        }
        if (yPos > yMaxLimited)
        {
            yPos = yMaxLimited;
            velocity = new Vector2(velocity.x, 0);
        }

```

# Answer
> 0 votes
An isometric coordinate system is basically just a rotated, and scaled coordinate system.

First you need to create a rotation matrix with an angle of -45 degrees if your forward is to the top-left and 45 degrees if it's to the top-right.

Then you create a scaling matrix with a scale `vec3(1, d, 1)` where `đ` depends on the angle of the isometric view. Take the height of the tile and divide it with the width.

You can't use Matrix4.TRS for this, you have to multiply the scale matrix with the rotation matrix first:

```
screenPos = rot * scale * pos

```

Pos is the original position of the corner before rotation.

This'll give you the screen position of the corners.

# Answer
> -1 votes
You need to check the X coordinates. In the above picture 50 units is the center i'm guessing and 100 units would be maximum. So check if your camera scrolling more than 100 units or less than 0 units. If the condition is true, stop scrolling.

---
Tags: unity, camera, isometric
---


# Question
Title: How to change the Rect Transform of a panel in Unity using C#
I am trying to create a sort of menu for a game. I have put my main content on one panel and the menu contents on another. The menu panel is kept to the side of the main panel. I want to place a button on the main panel which when clicked would position the menu panel on top of my main panel. A button on the menu panel would push it back to its original position. What would be the script for these buttons?

# Answer
This worked:

```
public GameObject leadersPanel;
public void ShowLeaders()
    {
        leadersPanel.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0f);
    }
    public void ShowMain()
    {
        leadersPanel.GetComponent<RectTransform>().anchoredPosition = new Vector2(-800, 0f);
    }

```
> 2 votes

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


title: How can I apply a Camera Shader to UI?

text:
# Question
Title: How can I apply a Camera Shader to UI?
I am trying to make a shader that applies a black image with 50% transparency to the entire screen, with the exception of a designated area. I am starting by just trying to apply a shader to the entire screen. So I am using the default `ImageEffect Shader`.

This is my before and after when applying my shader, which should invert everything. It inverts everything except for the Balmer's Peak, which is a Unity Image:

Before:

After:

Example of what I am going for:

I attached a script using `OnRenderImage` to the Camera, and the attached material is being applied to everything in sight, except the UI. What can I do to make my material applied to everything on the screen, including the UI?

I am new to shaders, so this may seem like a bit of a dumb question. But I am not sure what direction I should be headed. Here are my scripts, although I did not really change anything from what Unity provided me:

Script attached to camera:

```
using UnityEngine;

public class ButtonHighlight : MonoBehaviour
{
    [Tooltip("Material which is to be applied")]
    [SerializeField]
    private Material material;

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        Graphics.Blit(source, material);
    }
}

```

Shader attached to material above:

```
Shader "Magic/Magic Shader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                // just invert the colors
                col = 1 - col;
                return col;
            }
            ENDCG
        }
    }
}

```

What is the correct approach to apply a shader to the entire screen? (Keeping in mind, that the purpose is to add a filter to most, but not all, of the screen.)

# Answer
> 7 votes
The default behavior for Unity's UI is to draw after the post-processing effects have been applied. This is dictated by the `Render Mode` setting on your scene's `Canvas` object.

Switch the `Render Mode` to `Screen Space - Camera`, and drag your scene's main camera into the `Render Camera` property (which will appear when you change the render mode). Now your canvas's UI will draw before that camera's post-processing.

There's more information about render modes in the Unity documentation about Canvas.

---
Tags: unity, shaders, gui
---


# Question
Title: Graphical mesh lags behind collision shape in BulletPhysics debug drawing
In Bullet Physics when I debug draw physics world the graphical mesh lags behind the collsion shape.

```
m_DynamicsWorld->stepSimulation(1 / 60.0f, 10);

btTransform trans, trans2;
trans2 = m_RigidBodies.at("CubeMesh")->m_Body->getWorldTransform();

m_RigidBodies.at("CubeMesh")->m_Body->getMotionState()->getWorldTransform(trans);
/*
 * using
 * m_RigidBodies.at("CubeMesh")->m_Body->getMotionState()->getWorldTransform(trans);
 *
 * causes the graphical mesh to lag behind the collision shape in DebugDraw call
 * Checking with debugger shows that the lag error keeps on increasing
 * */
//
//
glm::mat4 M;
trans.getOpenGLMatrix(glm::value_ptr(M));
m_RigidBodies.at("CubeMesh")->GetGraphicalObject()->Model = M;

if (m_DebugDraw) {
    m_DynamicsWorld->debugDrawWorld();
}

```

If I use the OpenGL matrix from **trans2** then debug drawing is perferct. But with **trans** the graphical mesh lags behind the collision shape in debug draw.

I am using **btDefaultMotionState** when setting the CubeMesh rigid body.

```
btTransform tr;
    tr.setIdentity();
    tr.setOrigin(btVector3(0.0f, 90.0f, 0.0f));
    cubeMesh->m_PhysicsBody->m_MotionState = new btDefaultMotionState(tr);

```

Can anyone explain reason for this lag?

# Answer
*Note that this answer could be more complete, but, as I'm not a Bullet/physics engine guru, and that I'm not able to easily set up a project right now, I did not have the chance to try and debug the code to see exactly what was going on.*

<sup>*I have formatted the code a bit from the source to ease the reading.*</sup>

After digging around a bit in the code, then remembering that something was said about motion states in the documentation, I found this page again that discussed `MotionState`s in BulletPhysics, which states:

> Bullet knows how to interpolate body movement for you. As mentioned, implementation of interpolation is handled through MotionStates.
>
> If you attempt to ask a body for its position, it will return the position at the end of the last physics tick. That's useful for many things, but for rendering you will want some interpolation. Bullet interpolates the transform of the body before passing the value to setWorldTransform.
>
> If you want the non-interpolated position of a body \[which will be the position as it was calculated at the end of the last physics tick\], use btRigidBody::getWorldTransform() and query the body directly.
>
> To get the interpolated values for rendering it is necessary to call StepSimulation(deltaTime) in your rendering loop. Only include a deltaTime parameter, no other arguments.

Furthermore, browsing the code of Bullet, stemming from `int btDiscreteDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, btScalar fixedTimeStep)`s part:

```
for (int i=0;i<clampedSimulationSteps;i++)
{
  internalSingleStepSimulation(fixedTimeStep);
  synchronizeMotionStates();
}

```

we find this function:

```
void btRigidBody::predictIntegratedTransform(btScalar timeStep,btTransform& predictedTransform)
{
  btTransformUtil::integrateTransform(
    m_worldTransform,
    m_linearVelocity,
    m_angularVelocity,
    timeStep,
    predictedTransform );
}

```

that is called at some point to do a simulation step to update the `body` world transform (`predictedTransform` here is called with `body->getInterpolationWorldTransform()`); and this other method that is called to update the `MotionState`:

```
void btDiscreteDynamicsWorld::synchronizeSingleMotionState(btRigidBody* body)
{
  btAssert(body);

  if (body->getMotionState() && !body->isStaticOrKinematicObject())
  {
    btTransform interpolatedTransform;
    btTransformUtil::integrateTransform(
      body->getInterpolationWorldTransform(),
      body->getInterpolationLinearVelocity(),
      body->getInterpolationAngularVelocity(),
      (m_latencyMotionStateInterpolation && m_fixedTimeStep) ?
        m_localTime - m_fixedTimeStep :
        m_localTime*body->getHitFraction(),
      interpolatedTransform);
    body->getMotionState()->setWorldTransform(interpolatedTransform);
  }
}

```

We see that there is an extra step done to `synchronizeMotionStates`, which seems to base it's calculations on the calculated `body` information and potentially on a different time step for the integration.

The key element here is `m_latencyMotionStateInterpolation` which is `true` by default. Looking at the documentation for this variable (emphasis mine):

> Interpolate motion state between **previous and current transform**, instead of current and next transform. This can relieve discontinuities in the rendering, due to penetrations

*This* seems to be why you get lag when using the motion state's value instead of the body's value.

---

In your situation, if you are able to update your graphics 60 times per second, and you're able to update your physics simulation 60 times per second, and you do it on a 1:1 basis, and don't care about movement prediction, it seems to be recommended to call:

```
m_DynamicsWorld->stepSimulation(1 / 60.0f, 1, 1 / 60.0f);

```

and to get your transform directly from the body, as you have discovered.

I hope it helps :)
> 4 votes

---
Tags: opengl, c++, bullet-physics, debugging
---


# Question
Title: How do modern game engines handle many shadow casting lights?
This is a very general question, and not aimed at any particular language or graphics API; I am more interested in the theories & algorithms behind the solutions.

I'm reasonably familiar with the basic idea behind shadow mapping:

Each spotlight and directional light requires a rendering pass to generate it's shadow map, and each point light requires 6 such passes, prior to any lighting calculations.

Such a potentially large number of rendering passes could quite easily have a substantial negative impact on performance and texture bandwidth, so how do modern game engines deal with this problem, especially in the case with deferred rendering systems, where many lights are involved?

Consider the following scenario:

A scene contains a reasonable amount of geometry, spread out over a "level". That level has a certain number (let's say 20, for brevity) stationary point lights dotted around the level. The player can place lights around the level too, and carries a torch (spotlight).

The rendering system uses the deferred shading model, given the potentially high number of lights in the scene.

How does the renderer decide which lights to render shadowmaps for? Of those lights, during the "light pass", how is that variable number of shadow maps handled dynamically, bearing in mind that they could be 2d textures (spots and directional), or cube maps (points)?

Do graphics API's have the capability to support shaders with arrays of maps/lights, or would the shadow maps require a single discrete lighting pass for each individual light?

# Answer
I don't really see the intent of the question, but I will give a stab at it anyway. For a start, there is no silver bullet, if you want shadows, you need to some form of shadow test. Commonly in current hardware this is achieved with shadow maps. But there are a few "hacks" that can be used to speed up the entire process.

**Deferred Rendering**

Speeds up the rendering of large amount of light sources. Normally with forward rendering you have to render each geometry (G) for each light (L), resulting in cubic complexity. O(G\*L) Deferred rendering allows you to render the geometry once and each light separately, resulting in linear complexity. O(G+L) The only downside here is that you need to have some special handling for transparency. But if you want to do that properly, you need to do it separately anyway.

**Baked Light & Shadow Maps**

One trick that the Unreal Engine uses a lot, is pre-computing or baking the lighting information for everything static. The engine separates the geometry and lights into static and dynamic items. Static lights on static geometry are backed into a light map with lightmass. This uses a high quality global illumination solution and results in nice looking shadows. They are "free" since they are just blended onto the geometry in the standard render pass. Everything dynamic computes a shadow map on the fly. The renderer then decides based on the dynamic / static light and geometry if to apply shadows or not. But since the number of dynamic objects tend to be few, this works quite well.

If you can live with dynamic objects not casting shadows, you can pre-compute the shadow map from all static lights.
> 3 votes

# Answer
I can't answer to the question "how do they do it" but i can tell you how did I. In fact, I wrote a 3D Rasterizer / Renderer with dynamic interpolated directional lighting and had some performance problems while dealing with several spot lights or light sources.

As long as I worked on it, I discovered there are some tricks that one can implement in order to reduce the iterations and shadow map complexity:

1. *dark by default*

My models where rendered as rgb-50,50,50, my textures colors were several points lower than the final color I wanted to achieve (related to points bellow)

2. *don't aplly shadows but lights*

I realized that casting light is lot easier than computing shadows, get a spot light, get the angle between the poligon normal and the light vector and interpole the result in a "brightness" scale, by doing this, you can just ignore all those polygons that are not in a given angle relative to the light source, speeding up the process. If the scene has many of these light points, just repeat the process.

3. *baked shadows*

In fact, I decide to use ambient oclusion as standard, since it can be easily baked into the 3D object at load time, just decide your "incidence angle" (i used the camera initial position) and apply the color mutation. after the dynamic lighting explained above, the result is real enough to look as if it were all dynamic.

4. *Blending*

I'm not sure if this is a good point or if it just works for my pet project, but i used to blend the SSAO into each texture so it were just calculated once.

5. *Cache*

Same as point 4, i used to do it but not sure if it's done like that in the industry, i made a cache for each drawable entity to store the "main" poligons affected in each angle, so the engine had to iterate every objects polygons just once in each position, after that, the cache knew exactly which indexes were affected in each angle for each object so just one array of indexes had to be calculated, and, if the angle was between two cached angles, then both index arrays were used, it got pretty fast after doing this

Hope it helps :)
> 2 votes

# Answer
Here is how I do it in my engine:

The scene can hold an arbitrary amount of lights, of which arbitrary amount can be tagged as shadow caster.
There is a shadow budget which is the number of the maximum amount of shadow maps allowed to be rendered in a frame. Usually, the closest lights are prioritized, but screen space area occupancy could also be taken into account. If there are more lights tagged as shadow casters than the budget, then the shadow rendering ends, and remaining lights will have no shadows. This kind of simple logic can however result in popping, so it could be beneficial to smooth the transition of a shadowed light from "rendering shadow in this frame" to "unable to render shadow in this frame so bypass shadow".
You mentioned that point lights need 6 shadow passes, but it can be easily achieved in a single rendering pass with a recent graphics API eg. DirectX 11.
For deferred rendering, you could render the shadow map just before rendering the light so you can have a single shadow map for each light if they have the same resolution requested. But in case of a Tiled Forward (or Forward+) renderer, you are looping through each light in the mesh object shader, so you have to provide all shadow maps up front. You have to render shadows into multiple textures in this case, I recommend storing them inside a texture array or texture atlas.

For performance reasons it is very important to avoid rendering objects into the shadow map which are not inside the range of the light. The trivial way to do this is just to check for each object if it is intersecting with the light bounds (AABB, sphere or frustum).
There are further optimizations possible with this.

* You could use a space partitioning accelerator structure like an octree so you could query the intersecting objects faster.
* For point lights, only render objects to the minimal amount of cubemap faces it intersects. It complicates things when you want to render in one pass, but doable none the less with instancing.

An advanced optimization is to only re-render objects to the shadow maps which are changed from the previous frame (or all if the light position has changed). For this you have to keep the static parts of the shadow maps in a separate texture, and the dynamic parts in an other (or different parts of a texture atlas). I haven't implemented this, but the new Doom game has this working as I've heard.

There are other techniques used for shadow rendering apart from shadow mapping though:

* Shadow volumes. It was widely used after Doom 3 came out, but once shadow mapping got efficient to do on GPUs, it got overlooked because of high CPU requirements. It could still be relevant if GPU is overcommitted I think. Oh and I reckon something about patenting issues for this technique.
* Ray traced shadows. Trivial to implement in a ray traced renderer, but for game engines, it could be implemented in screen space in the form of ray marching.
* Voxel based shadows. There are some engines capable of voxel based global illumination (like mine :P), and for a voxelized scene there can also be shadowing information retrieved from ray marching ("cone tracing") the scene.

There are also light maps or some form of baked lighting which is calculated offline and needs only a single texture sample when rendering. This is obviously the fastest, many engines support it by default, but it can be hard to sync it with real time lighting while still getting accurate results.
> 1 votes

---
Tags: algorithm, graphics, shadow-mapping
---


# Question
Title: How do I handle a lot of big textures for a visual novel?
I am writing a visual novel on my desktop, using SDL and C++. I'm having trouble handling my sprites, in SDL.

1. I am getting the "not enough video memory" error when I create all of my sprites to texture at once. I load the textures in the background process, while it was being rendered. I forgot that textures should be created in the main rendering thread, but if I load the image file in the background and load the textures in the foreground, the screen freezes. How do I fix this?
2. Our target base resolution is 1980x1080 pixels; that is why I am getting the "not enough video memory" error. The sprites should be detailed and huge in a single sprite frame, as they should look like 2/3 in the screen. That means my sprite sheet is as huge as 8k x 2k or a single row of sprites.

How should I handle it? Do I need to resize our base resolution to a lower size, and just do the bitblock resize of the entire screen/canvas to the screen? Do we do the work, or base the art on a lower screen resolution instead and just resize it to fit the player's screen at runtime? My problem, if we work at smaller resolutions and just resize at runtime, is that it might become blocky or blurry.

The sprite sheets are too big, because the screen resolution is too big. We have one hundred sprite sheets that can not be loaded together, but cannot be loaded in a separate thread. How do I handle a lot of big textures for a visual novel?

# Answer
There are couple of things you can do, if you haven't already:

* Use texture compression to decrease memory footprint. OpenGL supports this out of the box nowdays.
* Don't use 32 bit textures. Sometimes textures with lower bit-depth can look as good as the 32 bit versions. For example if you don't absolutely need very precise transparency, you could use GL\_RGB5\_A1 (which is basically 1 bit for alpha, like cutout) and you will save half of the texture memory you would use with 32 bit textures. If the textures look worse in lower bitrate, try tonemapping.
* Don't have the textures you don't need loaded in memory. This basically means you have to load the textures to the memory only when you need them and at the same time unload those you don't need. Should you want to use loading screens or some background-loading thread is completely up to you. Either work fine. Split up the sprite atlases. You do not need all the sprites loaded in the memory all the time. Load the proper atlas to the memory only when you know a sprite in the atlas is being used in the current scene, or maybe in the next scene if you're preloading in background.
* Reuse your textures if at all possible. Recolor them using a shader or just reuse them everywhere. Super mario did this for example. You could use this technique to create a forest or a city. Be creative.
* Instead of having all the text in the game as separate images, create a font atlas and a text engine to draw all the text. If you feel wild enough, you could implement Signed Distance Field (SDF) fonts which can be used very flexibly to render text in many different ways and with different effects, all with just one pretty small texture. If SDF does not give enough quality (your font has lots of sharp corners) you could try MSDF, multichannel SDF.
* Scale down your textures. If you store your textures in memory with way larger resolution than what you are targetting, you basically are wasting some memory. If your game is running currently in 1080p resolution display, you don't need 4K resolution textures in memory. Measure how large your sprites are on the screen, and load the properly sized textures in to the memory based on the resolution the game is running on the current machine.
> 6 votes

# Answer
Don't load all textures at once. Only load those you need for the current scene, and release the textures when the scene is over. Visual novels are slow-paced games, so a few milliseconds of load-time between scenes (and even within scenes) isn't an issue. You can usually hide it with a fade-effect anyway.

You can reduce the number of images you need to load by splitting characters into individual images. When you have a character with 10 different poses, put them in 10 individual image files.

Also look into modularizing character sprites. You would be surprised how many different facial expressions you can create by layering a blank face and a few different variations of eyes (looking up, looking down, looking sideways, looking at viewer, closed), eyebrows (neutral, raised, tensed) and mouths (neutral, smile, frown, open).
> 2 votes

---
Tags: opengl, sdl
---


# Question
Title: Why does Physics2D.Raycast automatically fail if applying a layer mask?
I have been troubleshooting a problem I have encountered with some of my raycasts, and have arrived at a perplexing brick wall. I fire a `Physics2D.Raycast` in order to determine if my character is grounded; however, it would not always return a reference to the ground object in situations where it should.

---

Breaking down the method call, I have fired a raycast *without* a layer mask. This returns the correct reference; I then send the layer mask associated with the reference transform to the debug log.

```
public void FireTestRay()
{
    RaycastHit2D hit = Physics2D.Raycast(startPosition, Vector2.down, 0.1f);
    Debug.Log(hit.transform.gameObject.layer);
}

```

> 8

I want to be checking against my platform objects, which I have proven to contain the layer index of `8`. However, when I use layer masks, the raycast fails.

```
public void FireTestRay()
{
    RaycastHit2D hit = Physics2D.Raycast(startPosition, Vector2.down, 0.1f, 8);
    Debug.Log(hit.transform.name);
}

```

> NullReferenceException: Object reference not set to an instance of an object

I am not moving my game object; in fact, the only thing that changes *at all* is the above mentioned lines of code.

---

I seem to be able to successfully hit the intended object if I do not use a layer mask, and in turn, can successfully retrieve the value of the intended objects layer mask. As soon as I filter my raycast to only hit that layer mask, it fails.

Why does Physics2D.Raycast automatically fail if applying a layer mask?

# Answer
A Layer Mask is an integer, so that's right.

But if you want to test against Layer 8, you don't pass in 8 as the value. What if you want to check against 8 *and* 7? Well, 15 is the wrong answer there (as are both 8 and 7).

The value you need to pass to check against layer 8 is `1<<8`

This is why there are *exactly 32 layers* numbered from 0 to 31, as the layer number corresponds to a single bit in an integer-sized bitmask. So why's it called a layer mask? Why a *bitmask* for a given *physics layer.*
> 11 votes

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


title: Game logic in mvc: model or controller?

text:
# Question
Title: Game logic in mvc: model or controller?
Sorry if the title is too broad, I'll try to explain this in a more specific way down here.

We need to create a board-game in Java for an University project and we have to use the mvc pattern for it.

We found helpful to view this board game as a Finite State Machine, so we implemented a slight variation of the State pattern, where the context is the Controller and each state manipulates the model in different ways using commands from the Command pattern.

The states are also responsible to get the user input needed to perform their logic from the view, by displaying widgets and getting the user selection.

So for now, the Model is just a "box", a stateless container of data without any game-logic in it. We had a discussion with our tutor and he frowned us upon because he said we were deviating from the OOP approach. For example, we have cards in the game which give different effects; in our implementation, we have an "Effect State" which is handling the different effects by controlling their type:

```
if (effect.type == RESOURCE){
    Command c = new GiveResources(player, effect.resources);
    c.execute();
}else if (effect.type == BONUS_ACTION){
    controller.state = BONUS_STATE;
}...

```

Whereas he would so something like:

```
effect.execute(controller);

```

By passing the controller as a "callback" (forgive me the improper usage) to get inside the effect the input needed to perform its execution.

Now, I understand that our approach is violating in some way the Separations of Concerns principle, by putting game logic in the controller and outside the effects. But, considering that the set of effects is limited (that's why we chose the enum approach), isn't going back and forth between model and controller introducing way too much overhead? Or should the model "own" the game-logic (relating to this question, substituting the boolean with a State field) and call the Controller every time it needs user input?

# Answer
> 1 votes
Your lecturer is teaching you best practices through software design patterns - in this case, The Strategy Pattern (known in simpler languages like C as function pointers). You can follow your lecturer's guidelines AND be elegant / efficient at the same time:

```
enum EffectType
{
   EXPLODE,
   GAIN_HEALTH,
   LOSE_SCORE
}

public interface Effect //strategy pattern: class encapsulates function pointer
{
    EffectType type; //optional - see hashtable below
    public void execute(object args = null);
}

public class ExplodeEffect implements Effect
{
    public override void execute(object args = null)
    {
        Body body = (Body)args;
        body.Fragment(); //or whatever
    }
}
//...etc. for all types

public class EffectManager //or whatever you call yours
{
    Hashtable<EffectType, Effect> effectsByType =
                  new Hashtable<EffectType, Effect>();

    void Initialise() //could also do in constructor?
    {
        effectsByType.put(EXPLODE, ExplodeEffect);
        //...etc. for all types
    }

    void RunEffects()
    {
        //for each effect?
        EffectType type = ...; //get the effect enum value / ordinal somewhere
        Effect effect = effectsByType.get(type); //no if / switch block - efficient!
        effect.execute(); //you can also pass args in here if req'd
    }
}

```

You are not wrong to question bringing in additional classes each just to handle a couple of lines of code for each implementation of `Effect`. This is one pet hate of mine in languages like Java, where everything is broken down into classes, and functions aren't first-class citizens. In C or JS, I'd just have another function in the same or another module / namespace, instead of having to implement a whole new class like you will have to, just to wrap `execute`'s implementation.

As for the model/controller separation, I have spent a LOT of time on MVC for games and separating model from controller for the same concept (in your case, `Effect`) is IMO overkill and makes matters nigh unmanageable, especially as a codebase grows. (Then again, I'm the kind of guy that couldn't care less about `public`, `private` etc. either.) MC+V architecture is much simpler than M+V+C... but if you do this, you must be very careful about which functions you allow your View to run on the ModelController, since it will need to have a reference to it to read Model state, and could abuse that by calling all kinds of functions that change the state unintentionally.

I would say that in your case, efficiency should not be the primary concern. Writing code in a good architectural form comes first at your level. So listen to and learn from your teacher.

---
Tags: java, architecture, logic, mvc, board-game
---


title: AnimatedActor class don´t work

text:
# Question
Title: AnimatedActor class don´t work
Let me explain: I´m reading a book I got given that is called "Beginning Java Game Development with LibGDX", and get to the section where the book talks about animating actors, or animating "sprites". The example code they presented is as follows:

```
    public class AnimatedActor extends BaseActor {
    private float elapsedTime;
    private Animation anim;

    public AnimatedActor(){
        super();
        elapsedTime=0;
    }

 public void setAnimation(Animation a)
 {
 Texture t = a.getKeyFrame(0).getTexture();
 setTexture( t );
 anim = a;
 }

 public void act(float dt)
 {
  super.act( dt );
  elapsedTime += dt;
 if (velocityX != 0 || velocityY != 0)
  setRotation( MathUtils.atan2( velocityY, velocityX ) * MathUtils.radiansToDegrees );
 }

 public void draw(Batch batch, float parentAlpha)
 {
  region.setRegion( anim.getKeyFrame(elapsedTime) );
  super.draw(batch, parentAlpha);
  }
}

```

I'm running the examples, using android studio, and surprisingly I find the following situation: the code that proposes the book marks an error ... and it is exactly in this line:

```
 public void setAnimation(Animation a)
 {
 Texture t = a.getKeyFrame(0).getTexture(); <------- getTexture() is the error
 setTexture( t );
 anim = a;
 }

```

The error I'm getting is

> cannot resolve method getTexture()

I'm a bit surprised, since I'm not supposed to have any errors, since I'm reading from a book ... trying to implement something similar for my project, but ... I found this. Surely, it should be that the function should be removed in recent versions of LibGDX.

The only thing I try to do is that the moment you click on an actor on the stage, the texture set, change to the animated sprite. How can you create an animation in LibGDX?

# Answer
The reason you're getting your error is because the `Animation` class doesn't know what key frame class it should use. The `Animation` class is generic, meaning you have to supply the type of keyframe it should use within `<>`. I suspect that your example is supposed to use `TextureRegion` since a texture region has a method called `getTexture()`.

To fix it just change all of your:

```
Animation

```

To this:

```
Animation<TextureRegion>

```
> 2 votes

---
Tags: libgdx
---


# Question
Title: Math behind drawing one game object relative to another?
Let's say I have a square (a) and I want to draw another square (b) that stays on one corner of the square (a).

Square (a) can rotate and move around the game world, what math would be used to keep square (b) on the same relative point on square (a) ?

My current thought process would be:

You give Square b an offset from square a, which would be a distance and an angle.

Then using trigonometry you could update the location of square b to stay in the correct location.

# Answer
The way this is usually handled in games is something called a transformation hierarchy.

Here objects are arranged in a parent-child relationship, where each object's position, rotation, etc is specified in a local coordinate system relative to its parent's transformation. So to arrange square B so that it stays attached to the corner of square A, you'd set B as a child of A - then B will follow it wherever it goes, by inheriting the motion of A.

To keep the math consistent, these transformations are usually converted to matrices. Then computing the resulting "local to world" transformation (ie from B's local coordinates to A's coordinates to your stage / scene / canvas / world) is just a matter of multiplying each matrix up the parent chain.

For a typical 2D case, an object with local scale factors of \\$(S\_x, S\_y)\\$, a rotation of \\$\theta\\$ radians, and a translation of \\$(T\_x, T\_y)\\$ units relative to its parent could be represented by a local transform matrix like this:

$$ M\_{toParent} = \begin{bmatrix} S\_x \cdot cos(\theta) & -S\_y \cdot sin(\theta) & T\_x \\ S\_x \cdot sin(\theta) & S\_y \cdot cos(\theta) & T\_y \\ 0 & 0 & 1 \end{bmatrix} $$

Then you can transform any point \\$(P\_x, P\_y)\\$ from the original object into its parent's coordinate system by multiplying it by this matrix (with an extra 1 added as a "z" coordinate to enable translations)

$$ P\_{parentSpace} = M\_{toParent} \cdot \begin{pmatrix}P\_x \\ P\_y \\ 1\end{pmatrix} $$

You can compute a single matrix representing the entire transformation up the parent chain by multiplying those matrices together:

```
this.M_toWorld = this.M_toParent
currentTransform = this.parent
while(currentTransform != null)
{
    M_toWorld = currentTransform.M_toParent * this.M_toWorld;
    currentTransform = currentTransform.parent;
}

```

Or, you can do it recursively:

```
if(this.parent == null)
    this.M_toWorld = this.M_toParent
else
     this.M_toWorld = this.parent.M_toWorld * this.M_toParent

```

Now instead of walking up the whole chain anytime you want to transform a point, you can use this `M_toWorld` matrix as a shortcut:

```
P_worldSpace = M_toWorld * P

```

Any time an object moves, you need to update its transform and cascade these changes down its tree/DAG of child objects, ensuring that they all move together.
> 4 votes

---
Tags: mathematics, trigonometry
---


# Question
Title: How to get the center position for AABB of rotated mesh right?
I want to calculate the AABB for my rotated & translated mesh, but whatever I tried, I can't calculate the center position correctly if the mesh is rotated.

My mesh is defined by an array of vertices, located around the coordinate origin `(0,0,0)` and a TRS matrix (containing translation & rotation only). To calculate the AABB I multiply each vertex of my mesh with the TRS matrix and check for min/max values on all three axes. My AABB is simply defined as `glm::vec3 center, extend;` (`extend` = length from center to outer border of the AABB; `extend * 2` = length of the AABB). My TRS matrix is defined as:

```
 glm::translate(glm::mat4(), meshPosition) * glm::eulerAngleY(glm::radians(angle));

```

For each vertex I calculate:

```
glm::vec4 vert4 = glm::vec4(vertex.x, vertex.y, vertex.z, 1.0) * trsMatrix;
vert4 = vert4 / vert4 .w;

```

And search for the minimum/maximum x, y and z components in all `vert4`. Once the min/max values of all these vertices is found, the AABB is calculated as following:

```
extend = (max - min) * 0.5f;
center = min + extend;

```

First strange thing I noticed, is: even though my TRS matrix contains the translation for my model, the resulting AABB is still centered around the coordinate origin rather than the translation contained in my transformation matrix. I couldn't fully understand the reason yet, but it's not a big deal because I have the mesh position available anyway: so I thought I could just set the center position to the sum of the mesh position and the AABB center position.

```
center = center + meshPosition;

```

Unfortunately wrong: this works only as long as the angle of my rotation is around 0 or 180 degrees: In case of 90 or 270 degrees the position of the AABB relative to the mesh position is wrong (inverted on one axis).

I figured out the reason must be because the center of my mesh and the center of the AABB are different; the AABB center is "rotated" around the mesh center, when the mesh is rotated. If the mesh is facing in x+ or x- position, the center is correct calculated, if the mesh is facing in z+ or z- position the center of the AABB is in front of the mesh, instead behind it (and because of that not fully covering the mesh). How can I fix this/where is my error?

Note: This question is loosely related to my last question: How to recalculate AABB after rotation?

# Answer
According to this tutorial, the vector you are transforming should be the right-hand operand in the matrix multiplication expression, when using glm. Having it on the left will cause your vector to be multiplied against the matrix's translation instead of being summed with it. This will also cause your vector to be multiplied against the *transpose* of your transform's rotation component. You don't see an issue when rotating 180 degrees about a single axis because the transpose of this transformation is equivalent to the same axis-rotation at 0 degrees.
> 2 votes

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


title: AABB vs Rectangle

text:
# Question
Title: AABB vs Rectangle
I'm trying to wrap my head around 2D physics and stumbled upon Axis Aligned Bounding Boxes, and I have a couple of questions regarding them.

In all AABB structs I could find out there, people prefer naming their AABB vectors: `LowerBounds` & `UpperBounds`, or `Max` & `Min`. What do those values actually represent?

Is `LowerBound` the x and y of a rectangle and `UpperBound` x+width, y+height? If so, why not call them `TopLeft` & `BottmRight`? (since a boundary isn't a point) Same thing with `max` & `min`, the naming makes no sense to me.

The other question is: In every AABB collision detection guide out there people seem to present two AABB boxes, and call the the first one `A`, and the second one `B`, almost like an AABB doesn't even represent a box.

Could someone show me how to make a AABB box, out of a Rectangle (x,y,width,height)? That would clarify a lot for me.

# Answer
The primary difference is how they're used and how they're expected to respond. For example, AABBs do not rotate, rectangles are allowed to. You're right, they're very similar and you could use a rectangle like an AABB if you applied some restrictions to it. AABBs are essentially rectangles that are always positioned to be aligned with the axes of the world. When you can make the assumption that none of your bounds are rotated, this makes many things simpler with algorithms for collision detection.

The reason for the way the properties are named is because of the way it's used. AABBs are used for bounding, thus the properties describe the bounds, and so are called `UpperBound` and `LowerBound`. Yes, they're points. You need two values to define bounds on any given axis. The `LowerBound` contains the minimum values for the x and y axis, and the `UpperBound` contains the maximum values for the x and y axis.

The reason for naming the two AABBs `A` and `B` is just preference. Typically in these scenarios, you just have two objects, where (usually) the order you compare them isn't particularly important. `A` and `B` are arbitrary names.

Typically the `LowerBound` does equal the x and y of a rectangle and `UpperBound` equals the x+width and y+height of the rectangle. As long as the width and height are positive numbers.
> 5 votes

# Answer
Speaking to the naming part, left/right up/down are avoided because they are expressions of relative direction, whereas AABB's are concerned with operations which are rotationally invariant. For practical purposes, you *could* consider the invariant frame of reference to be your computer screen, which may be intuitively be visualized as having up/down directions corresponding with the Y axis and left/right directions corresponding to the X axis. However, this expresses directions as seen from the perspective of the observer, and is only intuitive because you wouldn't observe your screen from behind your monitor.

To further complicate the issue, AABBs are also used in 3-dimensions, where there are differing conventions. In some coordinate system implementations, positive x represents "right", and in others it represents "left". Worse yet, some 3D systems consider Y to represent up/down, while others use Z for up/down.
> 2 votes

---
Tags: 2d, collision-detection, physics, aabb
---


# Question
Title: How can I implement a directional melee attack?
I am attempting to make a top down game similar to the SNES Zelda games, in Unity 4.3, in 2D. When my character swings their sword, every enemy within a radius takes damage. I want to make sure that melee attacks only damage enemies the player is facing.

How can I do this?

---

The relevant code in `PlayerAttack.cs` looks like this:

```
// Update is called once per frame
void Update () {
    // have the player initiate an attack on the object
    if(Input.GetKeyUp(KeyCode.F)){
        MeleeAttack();
    }
}

private void MeleeAttack(){
    // create a variable called distance to make sure the distance is close enough
    // to inflict damage from a melee attack target.transform.positon = the position
    // of the object to attack and transform.position is the position of the players
    // transform
    float distance = Vector3.Distance(target.transform.position, transform.position);

    // make sure the distance is not greater than 1.5 so the player cannot
    // melee an enemy from to far away
    if(distance < 1.5f){
            // get a reference to the enemy's health script and type cast it.
            EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
            // now call the function that will decrease the enemy's health
            eh.AdjustCurrentHealth(-10);
    }
}

```

# Answer
> 4 votes
Compare the direction your character is facing with the direction to the enemy. The dot product of vector A and vector B divided by the magnitude of vector B will tell you the projection of A onto B. If you're using normalized vectors, you can skip the division. The results can be interpreted as follows:

* Result = 1: Vectors overlap completely
* Result = 0: Vectors are perpendicular
* Result = -1: Vectors are exactly opposite

Play with the results, see what ranges you want to allow. I'd suggest a result \> .85f.

```
public float CheckProjection(Vector2 a, Vector2 b) {
    return Vector2.Dot(a.normalized(), b.normalized());
}

private void MeleeAttack(){
    ...
    if(CheckProjection(directionToTarget, directionFacing) < .85f) {
        //facing towards the target, do the attack
    }
    ...
}

```

# Answer
> 2 votes
Algorithm description: You need the following:

1. The position (x1, y1) of your character.
2. The angle alpha in which it is facing.
3. The positions (and possibly sizes) of all enemy creatures.

Decide if you want the sword slash to be single target or hit all enemies in a cone in the direction you are facing.

General algorithm:

1. Create a list of all enemies in the vicinity.
2. Compute distance from each enemy. If not within melee range, remove it.
3. Iterate over all remaining enemies (within melee range) and compute the angle of the vector of their position minus your position.
4. Deduct this angle from the angle the character is facing (get absolute value). If the value is closer to 2 * Pie (or 360 degrees) than to zero, deduct 2 * Pie from it and get absolute value again.
5. Compare the result with what you consider an acceptable cone slice (for instance Pie / 5).
6. If the enemy is within the range, deduct health.
7. If you only wanted to hit one target, take the one closest to the character and inside the cone and deduct its health.

Normally you calculate the angle between two characters' positions like this:

```
Math.atan2(enemy.y - player.y, enemy.x - player.x);

```

This function or a compatible one probably exists in the language of your preference.

Please specify which part of this algorithm is not clear if you want further assistance.

More details: A melee attack is simply (in game mechanics terms) a ranged attack with a short range. There are generally two kinds of attacks, a single target attack where you only damage one enemy at most and AoE where you damage multiple foes (every character within the range of the area of effect).

In your case, I think you headed in the right direction. Checking the distance. Now you need to check the angle between your character and that enemy and compare it to the angle you are facing. If the difference is too large `(PI / 4)` then it doesn't hit.

So get the absolute value of the difference between the angles and compare it to some constant.

# Answer
> 2 votes
One solution is clearerer pictorially:

Left is what's happening; right is what you want.

Clearly, *distance* from the player is not the only important factor. There's also the enemies' *direction*.

The direction *relative to the player's facing* that is:

If you know the position vector of the player `p` and that of the enemy `e`, you can observe by a basic trigonometric identity that

`tan(angle) = opp / adj`, where `opp = | p.y - e.y |` and `adj = | p.x - e.x |`.

Hence, `angle = atan(abs(p.y - e.y)/abs(p.x - e.x))`.

You then filter down the list of enemies, first by whether they're in the radius, then further by whether the angle to them is within the angle of the attack. Everything left gets hit.

# Answer
> 1 votes
There are many ways to achieve this. Here's one way, which should be easy to make work with your existing code.

Create a Transform and make it a child of your player character. Position it where the attack lands and then add it as a public Transform of the PlayerAttack script. Let's call it attackPositionTransform. Now in your MeleeAttack function, you can compare the position of the attackPositionTransform with the target.

```
float distance = Vector3.Distance(target.transform.position, attackPositionTransform.position);

```

# Answer
> 0 votes
Just make a circle collider to check when an object enters your attack radius, then use `foreach` to access all the objects near you:

```
foreach(var item in objects)
    if(item.transform.position - transform.position).sqrMagnitude < 2)
        DamageCandidates.add(item);

```

Now you have a list with everthing close to you, and you can just use the dot product to check back stabs, and add a effect like stun.

---

To do the damage, you can just make a box collider, and size it to your needs. This will be the hit area. If the collider intersects with one of all damage candidates, fire your damage method.

```
OnAttackSend(Damageable victim)
{
    var tmp = new DamageEvent(myDamage, Owner, myEffects, PushMagnitude);
    victim.ApplyDamage(tmp);
}

```

---

To update the collider position, just normalize your velocity vector, and the collider position will be that position.

```
if(velocity != vector2.zero)
    collider.transform.position = parent.position + Velocity.normalized;

```

---
Tags: 2d, movement, vector
---


# Question
Title: How to display full website in Unity WebGL?
I want to display the complete website within the WebGL in Unity. I have tried Awesomium plugin but it doesn't work in WebGL. Please tell me is there any way to display the webpage.

Thank you.

# Answer
> 1 votes
There is currently no plugin that renders a website and supports WebGL.

I conclude two things from this. **A**, you have to do it yourself, get ready to research website rendering, suitable libraries for Mono maybe and probably a lot more.

And **B**, it won't be easy or even possible to do it (with acceptable performance). Rendering webpages is a feature many people want but plugins doing that mostly only support one platform (only windows or only android, etc.).

---
Tags: unity, c#, webgl, .net
---


title: Python float 32bit to half float 16bit

text:
# Question
Title: Python float 32bit to half float 16bit
I'm trying to write a 3D model exporter addon for Blender in Python and need some help.

The spec of the 3D format uses some compression on the vertices, there is a vertex buffer that contains vertices as 32bit floats. When this is compressed it is stored as 16bit float or half precision float.

I've seen lots of examples online of code in C to convert a 32bit float to 16bit float but not much luck with Python.

I was wondering if anyone here can help?

So far I've attempted to take some of the code here conversion of float and put it into Python. I managed to get this working and testing with a triangulated cube rendered only half the cube.

```
F16_EXPONENT_BITS = 0x1F
F16_EXPONENT_SHIFT = 10
F16_EXPONENT_BIAS = 15
F16_MANTISSA_BITS = 0x3ff
F16_MANTISSA_SHIFT =  (23 - F16_EXPONENT_SHIFT)
F16_MAX_EXPONENT =  (F16_EXPONENT_BITS << F16_EXPONENT_SHIFT)

for byte in self._byteBuffer:
   f32 = int(byte)
   f16 = 0
   sign = (f32 >> 16) & 0x8000
   exponent = ((f32 >> 23) & 0xff) - 127
   mantissa = f32 & 0x007fffff

   if exponent == 128:
       f16 = sign | F16_MAX_EXPONENT
       if mantissa:
           f16 |= (mantissa & F16_MANTISSA_BITS)
   elif exponent > 15:
       f16 = sign | F16_MAX_EXPONENT
   elif exponent > -15:
       exponent += F16_EXPONENT_BIAS
       mantissa >>= F16_MANTISSA_SHIFT
       f16 = sign | exponent << F16_EXPONENT_SHIFT | mantissa
   else:
       f16 = sign
   file.write(struct.pack(">H",f16))

```

# Answer
After some trial and error and trying various different things I finally got something that works for me. I hope this helps someone else - I've posted the code I used on my website. Quoted here:

---

I’ve been working with python for a while to create some addons for Blender which allowing me to import and export various formats that aren’t supported by default. One of these file formats I’ve been working with compresses the vertices/uv/tangent/normal data to reduce the space used. This data is usually stored as 32bit floating point values but in this case it is reduced to 16bit floating point or Half Precision floating point. Halfing the final size of this data.

I had a hard time recreating this with python, I’d never used python before starting using Blender so my understanding was still fairly new and most examples online I failed to understand or struggled to implement.

Finally I cobbled together something that works from different examples online and got the results I wanted. Like most things on my site I felt the need to share this with anyone else who may be trying a similar thing.

Here is my class in python:

```
class Float16Compressor:
    def __init__(self):
        self.temp = 0

    def compress(self,float32):
        F16_EXPONENT_BITS = 0x1F
        F16_EXPONENT_SHIFT = 10
        F16_EXPONENT_BIAS = 15
        F16_MANTISSA_BITS = 0x3ff
        F16_MANTISSA_SHIFT =  (23 - F16_EXPONENT_SHIFT)
        F16_MAX_EXPONENT =  (F16_EXPONENT_BITS << F16_EXPONENT_SHIFT)

        a = struct.pack('>f',float32)
        b = binascii.hexlify(a)

        f32 = int(b,16)
        f16 = 0
        sign = (f32 >> 16) & 0x8000
        exponent = ((f32 >> 23) & 0xff) - 127
        mantissa = f32 & 0x007fffff

        if exponent == 128:
            f16 = sign | F16_MAX_EXPONENT
            if mantissa:
                f16 |= (mantissa & F16_MANTISSA_BITS)
        elif exponent > 15:
            f16 = sign | F16_MAX_EXPONENT
        elif exponent > -15:
            exponent += F16_EXPONENT_BIAS
            mantissa >>= F16_MANTISSA_SHIFT
            f16 = sign | exponent << F16_EXPONENT_SHIFT | mantissa
        else:
            f16 = sign
        return f16

    def decompress(self,float16):
        s = int((float16 >> 15) & 0x00000001)    # sign
        e = int((float16 >> 10) & 0x0000001f)    # exponent
        f = int(float16 & 0x000003ff)            # fraction

        if e == 0:
            if f == 0:
                return int(s << 31)
            else:
                while not (f & 0x00000400):
                    f = f << 1
                    e -= 1
                e += 1
                f &= ~0x00000400
                #print(s,e,f)
        elif e == 31:
            if f == 0:
                return int((s << 31) | 0x7f800000)
            else:
                return int((s << 31) | 0x7f800000 | (f << 13))

        e = e + (127 -15)
        f = f << 13
        return int((s << 31) | (e << 23) | f)

```

and here is how to use it

```
#read half float from file and print float
h = struct.unpack(">H",file.read(struct.calcsize(">H")))[0]
fcomp = Float16Compressor()
temp = fcomp.decompress(h)
str = struct.pack('I',temp)
f = struct.unpack('f',str)[0]
print(f)

#write half float to file from float
fcomp = Float16Compressor()
f16 = fcomp.compress(float32)
file.write(struct.pack(">H",f16))

```
> 5 votes

# Answer
For some reason none of the other answers worked for me. So I tried to convert the C solution given here. I used the `ctypes` module to emulate C unions and types. I have no idea how efficient this is, or even if it is crossplatform, but it is working for me. If I haven't made any mistake it should be fully IEEE compliant and branchless.

```
import ctypes

class Bits(ctypes.Union):
    _fields_ = [('f', ctypes.c_float), ('si', ctypes.c_int), ('ui', ctypes.c_uint)]

def compress(f):
    SIGN_N = 0x80000000
    SHIFT_SIGN = 16
    MUL_N = 0x52000000
    MIN_N = 0x38800000
    INF_N = 0x7F800000
    MAX_N = 0x477FE000
    SHIFT = 13
    INF_C = INF_N >> SHIFT
    NAN_N = (INF_C + 1) << SHIFT
    MIN_C = MIN_N >> SHIFT
    MAX_C = MAX_N >> SHIFT
    SUB_C = 0x003FF
    MAX_D = INF_C - MAX_C - 1
    MIN_D = MIN_C - SUB_C - 1

    v = Bits(f=f)
    s = Bits(si=MUL_N)
    sign = v.si & SIGN_N
    v.si ^= sign
    sign >>= SHIFT_SIGN
    s.f *= v.f
    v.si ^= (s.si ^ v.si) & -(MIN_N > v.si)
    v.si ^= (INF_N ^ v.si) & -((INF_N > v.si) & (v.si > MAX_N))
    v.si ^= (NAN_N ^ v.si) & -((NAN_N > v.si) & (v.si > INF_N))
    v.ui >>= SHIFT
    v.si ^= ((v.si - MAX_D) ^ v.si) & -(v.si > MAX_C)
    v.si ^= ((v.si - MIN_D) ^ v.si) & -(v.si > SUB_C)

    return v.ui | sign

```
> 2 votes

# Answer
```
h = ((f32>>16)&0x8000)|((((f32&0x7f800000)-0x38000000)>>13)&0x7c00)|((f32>>13)&0x03ff)

```

The above should work assuming that none of the below "fatal flaws" are fatal in your situation: "The above expression suffers from a few fatal flaws, however. It doesn't handle zero, Infinity, NaN, or small float numbers which are only representable as subnormal half-floats" Otherwise I would make the table as demonstrated in near the bottom of the paper.

Source
> 1 votes

---
Tags: mathematics, python, floating-point
---


# Question
Title: Change screen dimensions in libgdx in HTML
Can i change the screen dimensions in libGDX in HTML?

If I inspect the element (the game) in Chrome and I change canvas width or height it changes the screen dimensions, but I don't know how to do it in the HTML file. I have the default file generated by libGDX.

The CSS path to the canvas containing the screen size is: #embed-html \> table \> tbody \> tr \> td \> canvas

The HTML is:

```
   <body>
          <a class="superdev" href="javascript:%7B%20window.__gwt_bookmarklet_params%20%3D%20%7B'server_url'%3A'http%3A%2F%2Flocalhost%3A9876%2F'%7D%3B%20var%20s%20%3D%20document.createElement('script')%3B%20s.src%20%3D%20'http%3A%2F%2Flocalhost%3A9876%2Fdev_mode_on.js'%3B%20void(document.getElementsByTagName('head')%5B0%5D.appendChild(s))%3B%7D">↻</a>
          <div align="center" id="embed-html"></div>
          <script type="text/javascript" src="html/html.nocache.js"></script>
   </body>

   <script>
          function handleMouseDown(evt) {
            evt.preventDefault();
            evt.stopPropagation();
            evt.target.style.cursor = 'default';
          }

          function handleMouseUp(evt) {
            evt.preventDefault();
            evt.stopPropagation();
            evt.target.style.cursor = '';
          }
          document.getElementById('embed-html').addEventListener('mousedown', handleMouseDown, false);
          document.getElementById('embed-html').addEventListener('mouseup', handleMouseUp, false);
   </script>

```

# Answer
> 1 votes
(OP's own answer)

The solution to change the screen dimensions directly in the HTML/CSS is:

```
<style>
   div#embed-html table tbody tr td canvas{
     width:320px;
     height: 480px;
   }
</style>

```

That's where the screen is located.

# Answer
> 0 votes
I don't know if i understand your question correctly but in case you want to change the screen size of the game for webpage, you can do that by going to html game directory \> src \> yourpackage.client \> HtmlLauncher.java and then modify resolution 480x320 to something else.

```
@Override
public GwtApplicationConfiguration getConfig () {
    return new GwtApplicationConfiguration(480, 320);
}

```

---
Tags: libgdx, html, css
---


title: How to save and load scene in realtime?

text:
# Question
Title: How to save and load scene in realtime?
I'm working on an editor where one important feature is to save and load changes (all type of changes like adding and removing objects and their components and components property values)

I want to know there isn't a Unity solution for that and I have to make a data format to save all of them on a string and load all of them? As I searched there is class serialization solutions that works like I said and has its own difficulties. Is there any thing or asset that performs all of this simply?

# Answer
> 3 votes
I believe you are talking about serializing MonoBehaviours. This is something we have struggled with since the dawn of humankind.

There are third party tools available on the asset store, but they each have their own limitations and learning curves.

You can write your own tool using reflection, but considering what a strong desire there is for a tool that does this, I am guessing the third party assets have already done an amazing job with the restrictions they have.

I suggest you save the individual aspects you need to, one at a time. It's less elegant than serializing and saving an entire MonoBehaviour, but it's what I have chosen to do after days of my own research into the matter.

There are several ways to save an individual field. First you must make sure it is serialized, and then you can save. There are many resources available on how to save a single field. (EasySave2 (paid) is my personal preference.)

---
Tags: unity, savegame, realtime
---


# Question
Title: Enemies are penetrating in each other when following player
As you can see the image my enemy (when following my player), penetrate each other. How can i avoid it? I am using NevMeshagent to follow the player.

```
void Update () {
    currentNavMeshAgent.destination = player.transform.position;
}

```

I have added a Rigidbody and a Collider to my enemy object but they are still penetrating each other

# Answer
> 2 votes
To avoid penetration, increase each NavMeshAgent's radius so it's equal to or larger than your agent's collider.

# Answer
> 0 votes
There are several solutions to this, but, based on the image you posted i assume that your "enemies" are zombies, so, they don't have or need to "think" by themselves, right?

In this particular case I'd bet for a swarm approach, by doing this instead of managing each of the zeds one by one, you can have a logic 2D Matrix and check where your monsters are before moving, by A\* or any other pathfinding approach you want to use. By doing this, you would be able to skip AABB collision checks between your enemy entities, boosting your performance and knowing that your main enemy puppet master wont let them collide.

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


title: Picking up items and references

text:
# Question
Title: Picking up items and references
Just a heads up, I'm sure there are much more efficient ways to do what I'm trying to do. I've even thought of some myself. However, at the moment, I'm mostly interested in getting this code to work. I think I understand exactly why it doesn't work, but I'm not sure how to fix it.

Firstly, there is an ItemPickupTrigger script attached to the drop prefab. The purpose of this script is simply to modify a variable's truth value depending on whether or not the player is in range. This script must be attached to the drop prefab because it uses OnTriggerEnter/OnTriggerExit. No problem here.

Secondly, there is a pretty standard EnemyDrops script.

```
public class EnemyDrops : MonoBehaviour {

    private EnemyHealth enemyHealth;

    public GameObject dropPrefab;

    private float randomNumber;

    public bool objectDropped;
    private bool numberGenerated;

    public GameObject drop;

    // This is the correct offset for enemies' current y-position of 1.083333
    private Vector3 dropPositionOffset = new Vector3(0f, -0.958333f, 0f);

    void Start()
    {
        enemyHealth = GetComponent<EnemyHealth>();
    }

    void Update()
    {
        if (enemyHealth.isDead && !objectDropped && !numberGenerated) {

            randomNumber = Random.value;
            numberGenerated = true;

            if (randomNumber <= 1.0)
            {
                DropObject();
            }
        }
    }

    private void DropObject()
    {
        objectDropped = true;

        drop = GameObject.Instantiate(dropPrefab, transform.position + dropPositionOffset, Quaternion.identity);
    }
}

```

It drops the object where the enemy has been killed. This script is attached to each enemy. As it's currently set up for testing purposes, an item will always drop. I'm sure there are better ways to do this, but it works, so no problem here.

Finally, there is an ItemPickup script attached to an ItemController object which is otherwise pretty empty. I'm not even really sure why I decided to do it this way, I just thought that it might be better for things I wanted to do in the foreseeable future to not have this script attached to each enemy. Now get ready because the code below is problematic.

```
public class ItemPickup : MonoBehaviour {

    private GameObject pickupWindow;

    private bool windowOpen;

    private GameObject drop;
    private ItemPickupTrigger itemPickupTrigger;

    void Start()
    {
        pickupWindow = GameObject.Find("Pickup Window");
        pickupWindow.SetActive(false);

        drop = GameObject.Find("Drop");
        itemPickupTrigger = drop.GetComponent<ItemPickupTrigger>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.R) && itemPickupTrigger.playerInRange && !windowOpen) {
            pickupWindow.SetActive(true);

            windowOpen = true;
        }
        else if (Input.GetKeyDown(KeyCode.R) && windowOpen)
        {
            pickupWindow.SetActive(false);

            windowOpen = false;
        }
    }
}

```

For starters, it only works if there is a drop object already present when the script begins, but there shouldn't be a drop object then. Second, if I don't set the reference there, I'm not sure how to set itemPickupTrigger's reference, since I'm using it in update and need the reference set before then. Make a function called SetReferences() and call it early in Update()? Yeah, I'm pretty lost. Basically, I want to be able to open the "loot window" near any instantiated drop object in the game. Currently, that functionality only in a limited capacity (either only on a "preexisting" drop object in the scene or on one random instantiated drop object(?) depending on how I have been modifying the code). Help!

# Answer
> 1 votes
> it only works if there is a drop object already present when the script begins, but there shouldn't be a drop object then

Well, that's because you find a drop(ped) object during `Start()` which is when (surprise) the script first starts running:

```
void Start() {
    ...
    drop = GameObject.Find("Drop");
    itemPickupTrigger = drop.GetComponent<ItemPickupTrigger>();
}

```

So if you want it to look for drops when the player presses a key, you need to move this into the area of code that handles the keypress.

> Second, if I don't set the reference there, I'm not sure how to set itemPickupTrigger's reference, since I'm using it in update and need the reference set before then.

How about right before accessing the reference?

```
void Update()
{
    drop = GameObject.Find("Drop");
    itemPickupTrigger = drop.GetComponent<ItemPickupTrigger>();
    if (Input.GetKeyDown(KeyCode.R) && itemPickupTrigger.playerInRange && !windowOpen) {
        pickupWindow.SetActive(true);

        windowOpen = true;
    }

```

Of course, this is still going to fail if there are more than one of these in the scene and the player is standing near any of them other than the one that was first added to the scene.

Additionally, `GameObject.Find()` is *slow* and should be avoided. Given that you have a trigger for detecting if the player is in range, you should use *that* function to give a reference to the dropped object to the `ItemPickup` instance. Something like this:

```
void OnTriggerEnter(Collider other) {
    // some method of determining that yes, the thing that entered
    // the trigger volume is in fact the player
    if(other.gameObject == ThePlayer) {
        other.GetComponent<ItemPickup>().drop = this;
    }
}

```

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


title: SpriteSheets with XML and without XML

text:
# Question
Title: SpriteSheets with XML and without XML
I'm very new to game development, and I'm working with `Godot` engine. I'm making a platform game and I downloaded a package from the web with assets, it contained some sheets. I have used a 2D atlas importer in Godot before bt it requires a `.json` file which contains the coordinates. The sprite sheet i downloaded does not have a xml or json. How can i get sperate images from that sheet? Or any work around to make a tiled map in Godot?

# Answer
> 1 votes
You can use the Tiled Map Importer Extension to import tile maps defined with the Tiled Map Editor.

The extension handles both `tmx`(`xml`) and `json` files, and the editor can generate `tmx` files.

---
Tags: spritesheet, godot
---


# Question
Title: Can a loading screen be implemented using one thread only? If so, how?
I have seen guides on how to implement a loading screen using more than one thread. But sure it must be possible to do so with one thread, since older (even 2D) games that run on single-threaded machines had loading screens as well.

So, how do you do it?

# Answer
You basically have to break down the loaded data into smaller chunks, and intersperse UI updates in between those bits of processing. The finer the granularity of the chunks of data you synchronously load / process, the more frequently your UI can update. In essence, poor man's multi-threading. (This is how it was done before the advent of multi-core machines.)

Breaking down into smaller chunks may well not be possible unless you do one or more of:

* Gut any system libraries for loading and substitute your own logic
* Restructure your data (possibly a major change).

So you'd do something like:

```
while (chunksRemaining > 0)
{
    LoadNextChunk();
    UpdateUI();
}

```

Notice that the `LoadNextChunk()` call could take nanoseconds or whole seconds, but prevents us proceeding to `UpdateUI()` until Chunk's processing is done. So ensure `LoadNextChunk()` runs fast!
> 3 votes

# Answer
In very, very generic terms, you write something like this (pseudo-code):

```
while (!isNewLevelLoaded) {
    UpdateAndRenderLoadingScreen(percentageOfNewLevelLoaded);
    LoadNewLevelBytes(numberOfBytesTOLoad);
}

LoadNewLevelBytes (int bytes) {
   for (int i = 0; i < bytes; i++) {
        LoadByte();
    }
    if (endOfFileReached) isNewLevelLoaded = true;
}

```
> 1 votes

# Answer
I'm not sure what kind of "single-threaded machines" you have in mind, but you could also have a single-threaded programme running on a system that supports asynchronous I/O. In this case there is stuff happening in parallel with your code being executed but it's handled by the OS.

So in pseudocode your programme might look like this:

```
for (fileToLoad) {
    asyncRead(fileToLoad);
}

while(numberOfFilesLoaded != numberOfFilesToLoad) {
    updateLoadingScreen();
}

// all files loaded here

```
> 1 votes

# Answer
Some languages provide `coroutines`, which are similar to threads in that they allow a degree of multi-tasking, but can actually exist on one thread.

A `couroutine` is essentially a block of code that at some point decides to `yield` back to its caller, so you get code like this:

(Hypothetical Lua code)

```
function loadFile(path)
  --code
end

function loadFiles(paths)
  for i, file in ipairs(fileList) do
    local result = loadFile(file)
    coroutine.yield(result)
  end
end

function updateLoadingScreen()
--code
end

function drawLoadingScreen()
--code
end

function loadingScreen(files)
  updateLoadingScreen()
  drawLoadingScreen()
  local loadFilesCo = coroutine.create(loadFiles)
  local results = {}
  while coroutine.status(loadFileCo) ~= "dead" do
    local success, result = coroutine.resume(loadFilesCo, files)
    if ~success then error(result) end
    table.insert(results, result)
    updateLoadingScreen()
    drawLoadingScreen()
  end
  return results
end

```
> 0 votes

---
Tags: multithreading, loading
---


# Question
Title: How can I accurately lerp Colors over seconds?
I have some code to lerp between two colors over a set number of seconds, and the lerp works fine:

```
private Color lerpingColor;

private IEnumerator LerpColorsOverTime(Color startingColor, Color endingColor, float time)
{
    float step = 0.0f;
    while (step < 1.0f)
    {
        step += Time.deltaTime / time;
        yield return new WaitForSecondsRealtime(Time.deltaTime);
        lerpingColor = Color.Lerp(startingColor, endingColor, step);
    }
}

```

The problem is, the lerp time takes longer than the time I provide in my parameter. For example, `LerpColorsOverTime(Color.white, Color.black, 5.0f);` takes over 8 seconds to lerp.

My best guess is that I am being very inefficient in the way I am lerping. I tried accounting for the calculation time, but it does not seem to work. In the particular case shown, it is because `calculationTime` is always 0, since the code to update the time is never run between my `Time.time` checks. I tried various approaches, with this being my best:

```
private Color lerpingColor;

private IEnumerator LerpColorsOverTime(Color startingColor, Color endingColor, float time)
{
    float calculationTime = Time.time;
    float step = 0.0f;
    while (step < 1.0f)
    {
        step += Time.deltaTime / time;
        calculationTime = Time.time - calculationTime;
        yield return new WaitForSecondsRealtime(Time.deltaTime - calculationTime);
        calculationTime = Time.time;
        lerpingColor = Color.Lerp(startingColor, endingColor, step);
    }
}

```

I also tried other variations of `Time.time`, such as `DateTime.Now.Miliseconds / 1000.0f` and `Time.realtimeSinceStartup`, but they failed as well.

How can I make this code efficient enough to run in the expected time, or make some sort of change with the seemingly same effect?

# Answer
Keep in mind that `Time.deltaTime` is the time between the current frame and the **last** frame. When calling `new WaitForSecondsRealtime(Time.deltaTime)` you "guess" the next frame will be in `Time.deltaTime` seconds. Which may not be true ! And, since Unity is not very precise, you may wait for 2 frames instead of one, resulting in your problem. Yielding `null` will wait for the next frame.

```
private IEnumerator LerpColorsOverTime(Color startingColor, Color endingColor, float time)
{
    float inversedTime = 1 / time ; // Compute this value **once**
    for( step = 0.0f; step < 1.0f ; step += Time.deltaTime * inversedTime )
    {
        lerpingColor = Color.Lerp(startingColor, endingColor, step);
        yield return null ;
    }
}

```
> 2 votes

---
Tags: unity, color, timestep, lerp, realtime
---


# Question
Title: Add sprite flickering to a LibGDX object
**How can I make a LibGDX Actor object flicker over a set duration?**

Many 2D platformers have the player character 'flicker' after taking damage to indicate temporary invincibility, (ie: invincibility frames). For an example, see the below gif from Shovel Knight.

It's fairly simple to make an object fade in or out over time using LibGDX's Actions library.

```
Actor player = new Actor();
// fade out in 0.25 seconds
player.addAction(Actions.fadeOut(0.25));

```

But searching through the documentation, I couldn't find any method for `Actions.flicker()`. How can I implement sprite flickering in LibGDX?

# Answer
> 0 votes
Create a flickering `SequenceAction` and have it repeat a preset number of times.

```
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;

if (playerDamaged) {
    SequenceAction flicker = new SequenceAction(Actions.fadeOut(0.25f), Actions.fadeIn(0.25f));
    player.addAction(Actions.repeat(6, flicker));
}

```

---
Tags: libgdx, sprites
---


# Question
Title: How do I create a ToggleButton via code?
How do I create a `ToggleButton` via code? I tried using `ButtonGroup`. Using a `CheckBox` works, but `TextButton` does not:

```
...
CheckBox checkBox = new CheckBox("one", skin);
CheckBox checkBox2 = new CheckBox("two", skin);
CheckBox checkBox3 = new CheckBox("three", skin);

ButtonGroup buttonGroup = new ButtonGroup(checkBox, checkBox2, checkBox3);
...

...
TextButton playButton = new TextButton("one", skin);
TextButton playButton2 = new TextButton("two", skin);
TextButton playButton3 = new TextButton("three", skin);

ButtonGroup buttonGroup = new ButtonGroup(playButton, playButton2, playButton3);

```

I found this example, but I still can not adjust the background:

```
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.font = someBitmapFont;
textButtonStyle.fontColor = Color.WHITE;
textButtonStyle.downFontColor = Color.BLACK;
//Optional color to toggle between when pressed
textButtonStyle.checkedFontColor = Color.GREEN;
final TextButton textButton = new TextButton("Text", textButtonStyle);
final TextButton textButton2 = new TextButton("Text", textButtonStyle);
final TextButton textButton3 = new TextButton("Text", textButtonStyle);

ButtonGroup buttonGroup = new ButtonGroup(textButton, textButton2,textButton3);

```

On the left is what I am left with; on the right is what I want.

Here is my current code:

```
com.badlogic.gdx.scenes.scene2d.ui.Button$ButtonStyle: {
    default: { down: default-round-down, up: default-round },
    toggle: { down: default-round-down, checked: default-round-down, up: default-round }
},

com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: {
    default: {
        down: default-round-down, up: default-round, font: default-font, fontColor: white
    },
    toggle: {
        down: default-round-down, up: default-round, checked: default-round-down,
            font: default-font, fontColor: white, downFontColor: red
    }
},

```

# Answer
> 3 votes
Quoting the javadocs of the `Button` class:

> Each time a button is clicked, the checked state is toggled.

So the buttons are probably checked, you just can't see it. The reason for not being able to see it might be that your `Skin` (or `ButtonStyle`) does not contain a drawable for the `checked` state. This means that the button will not show when it is actually checked. If you want to double-check if your buttons are checked you can call `Button#isChecked()` and see what value it returns.

Also, if you want to make your buttons act as radio buttons (i.e. only one can be toggled at a time) you want to set `ButtonGroup#setMaxCheckedCount(count)` and `ButtonGroup#setMinCheckedCount(count)` both to 1 so that no more or no less than one button can be toggled at a time.

**Update**: to use your "toggle" style from your skin do this:

```
new TextButton("text", skin, "toggle");

```

---
Tags: libgdx, scene2d
---