# Question
Title: Nestling into contact with a group of physics objects without exerting forces on them
I'm making a pool game, and would like the circle (imaginary) to be in contact with the table and balls, and to fit perfectly as a ball would.

Now I thought I would use Rigidbody and lerp the position of the circle to the raycast hit, and its collider it would force it into a fitting position.

The problem I encountered is that since it has a collider, it also pushes the balls, which I do not want.

So my question is, how do I make an object act like it's touching & blocked by other GameObjects with Colliders and Rigidbodies, without pushing them?

# Answer
> 7 votes
Here's a way to do this using Physics.SphereCast to test against the bodies' colliders without actually exerting any forces on them.

It assumes that your cursor object is placed on exactly the same y plane as the centers of the balls, so that all the collisions are in-plane against their widest circumference, and the camera is looking straight down at the playfield. (This can be adjusted for a camera at an oblique angle, I just haven't done that bit)

It also currently only works for colliders at rest - it tests that the cursor doesn't move into a ball, but not if a ball moves into the cursor. That could be added if needed.

```
public class ContactCursor : MonoBehaviour {

    // Limits our maximum travel to keep the complexity down.
    public float maxSpeed = 15f;

    public float radius = 0.5f;

    // Remember to set this to include the layer your balls are on.
    public LayerMask collisionLayers;

    Camera _camera;
    float _cameraPlane;

    // Cache camera and our distance from it, for positioning relative to cursor.
    void Start () {
        _camera = Camera.main;
        _cameraPlane = _camera.WorldToScreenPoint(transform.position).z;
    }

    void LateUpdate () {
        // Transform the mouse into a position on our travel plane.
        Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = _cameraPlane;
        mousePosition = _camera.ScreenToWorldPoint(mousePosition);

        Vector3 offset = mousePosition - transform.position;
        Vector3 direction = offset.normalized;
        float maxDistance = Mathf.Min(offset.magnitude, maxSpeed * Time.deltaTime);

        Vector3 targetPosition = transform.position + direction * maxDistance;

        // Currently set to do 2 passes:
        // 1: Beeline toward the mouse until you hit something.
        // 2: Use any remaining movement to move perpendicular to the obstacle.
        // In my tests this was enough, but you can increase this
        // if you have more complex arrangements or a faster cursor.
        int limit = 2;
        for (int i = 0; i < limit; i++) {

            // Check for a collision in the direction we're trying to move.
            RaycastHit hit;
            if (Physics.SphereCast(transform.position, radius, direction, out hit, maxDistance, collisionLayers)) {

                // Back up to closest non-intersecting point.
                // (Plus a small fudge factor for stability).
                offset = hit.point + radius * hit.normal - transform.position;
                float distance = Vector3.Dot(offset, direction) - 0.001f;
                targetPosition = transform.position + direction * distance;

                transform.position = targetPosition;

                if (i + 1 == limit)
                    return;

                // Determine a new move to approach the cursor without
                // penetrating deeper into whatever we hit.
                maxDistance = Mathf.Max(maxDistance - distance, 0f);

                offset = mousePosition - transform.position;

                // Make sure we don't overshoot the closest point on this line
                // to the mouse (prevents vibrating when close-but-mot-quite).
                distance = offset.sqrMagnitude;
                float forbidden = Vector3.Dot(offset, hit.normal);
                distance -= forbidden * forbidden;
                // Shouldn't happen with infinite-precision real numbers,
                // but rounding errors happen in practice.
                if (distance < 0f)
                    return;
                maxDistance = Mathf.Min(maxDistance, Mathf.Sqrt(distance));

                // Calculate new movement direction.
                offset -= forbidden * hit.normal;
                offset.y = 0f;
                direction = offset.normalized;

                targetPosition = transform.position + direction * maxDistance;
            }
            else {
                // No collision! Complete the move.
                transform.position = targetPosition;
                return;
            }
        }
    }
}

```

# Answer
> 2 votes
If your problem here is that when player is placing the ball, it pushes other balls back, then why not just turn isKinematic on and off?

Turn off physics for all the other balls on the playing field, let the player make ball placement and when the player presses "OK" button, enable physics and let the player make the shot.

---
Tags: unity, c#, physics, rigidbody, collider
---


# Question
Title: How can I diagnose a Unity crash when running the game on a phone?
I have a 2D android game that is in beta on Google Play. It has about 100 installations, but no testers. I'm the only developer. Some of the users have reported app crashes, and because they are not developers, they can not help me with a diagnosis.

I think the origin of the problem is the phone not having enough memory to run the app. When I rub the app in a LG-D213c running Android 4.4.2, the game opens, and you can navigate the main screen (the title screen). When I select any stage, the game displays the "loading" screen that runs in the same scene as the main title, and `SceneManager.LoadScene ()` is called with the play scene (battle). Then, the game closes. When I do the same procedure with a Galaxy S5 neo (SM-G903M) running Android 6.0.1, the app runs normally.

I have collected a log uaing Android Monitor. Both of them include the moment of the app crash (the name is com.empresa.aplicacion, but this is not the real name).

This is the profiler capture in both cases.

* LG phone case.
* Galaxy S5Neo case

So. I have some questions.

* What is the real origin of the problem? How can I diagnos the issue? I'm not seeing the cause, this is the filtered Log, and this is the complete log.
* How can I control this error from inside Unity? Is there a way to catch exceptions from the Unity core, so that it can generate a report?
* How can I make a diagnosis to the installations that I do not have access to, like a production installation or a client that has the app in their phone?

All of my questions are relative to Unity platform.

# Answer
If you did not manage these in production, you'll probably have a really hard time doing it now. Best way to do these tests would be with a virtual android device, just get crash reports from the devices that are getting the crashes then using the same kind of device with the AVD go into detailed diagnostics for mobile devices. That's how I would do it and how I'm planning to do it for my game.
> 3 votes

# Answer
i hade errors maybe not like you but it was happening on some devices and not others, changing the graphics api to gles 2 ,maybe removing 32 bit buffer in player settings solved the problem
> 0 votes

---
Tags: unity, android, debugging
---


# Question
Title: Dynamic length increment of of an object-LibGdx
I want to implement something in my LibGdx game, where a small stick is positioned vertically.On tap,I have to increase the length of the stick with tap frequency.Later I want to rotate,perform collision and do all those things that a sprite can do.It is an advanced form of fly Swatter game. I am wondering how can I do it.I found some ways.But I am not sure it will work nicely.

1.Creating an array of small sticks and adding it to the base stick to increase the length.(Rotating array of object at a time is difficult,I know.)

2.Scale the image to increase the size of the stick.

Important thing is that this stick and rotation is an super important event in my game.

I only have experience of a simple running in LibGdx. It would be very helpful if experienced persons give some ideas to implement this game in LibGdx.

# Answer
> 0 votes
If your stick is unicolor, you could just resize it like you want, you'll have no loss of quality. If your stick is multicolor and you don't need too much states, you could do as much textures as you have sticks.

For solution one, juste use

```
// Keep in mind : scale is from sprite origin
sprite.setScale(scaleX, scaleY);

```

For solution two,

```
int nbStates = 10; // Number of texture you need
Texture textures[nbStates];

// Maybe use a for loop to load textures
for (int i = 0; i < nbStates; i++)
    textures[i] = new Texture("sprites/stick" + i + ".png");

```

Then on tap use :

```
sprite.setTexture(textures[stickState]);

```

---
Tags: libgdx
---


# Question
Title: Resize Label automatically with the text content in LibGDX?
In LibGDX, I want to add some long text content to several Labels. I'm creating those labels in a loop, and the text content is different in each iteration. I want the `Label` to have a size that fits the text exactly. Is there a way to do this? I did `setWrap(true)` to the Label.

For reference, consider a Label:

```
+------------------+
|                  |
+------------------+

```

One copy of that may be:

```
+------------------------------------+
| Lorem ipsum dolor sit amet,        |
| consectetur adipiscing elit.       |
| Nec vero alia sunt quaerenda       |
| contra Carneadeam illam sententiam.|
+------------------------------------+

```

Another one should resize to the content:

```
+------------------------------------+
| Uterque enim summo bono fruitur,   |
| id est voluptate. Illud non        |
| continuo, ut aeque incontentae.    |
| Occultum facinus esse potuerit,    |
| gaudebit; Multoque hoc melius nos  |
| veriusque quam Stoici. Id Sextilius|
| factum negabat. Ita nemo beato     |
| beatior.                           |
+------------------------------------+

```

---

**EDIT:**

Please note that the horizontal wrapping is working perfectly. I need the Label size to adjust with the text content vertically. Width is fixed. Height is not.

# Answer
> 0 votes
this may not be exactly what you are looking for, but it might help. I made this function which replace the closest space from the middle of the string by a space line. There is no much to adapt for multi line

It produces this :

```
+--------------------------+
|Lorem ipsum dolor sit amet|
+--------------------------+

+--------------+
|Lorem ipsum   |
|dolor sit amet|
+--------------+

```

The code :

```
public cutAtMiddle()
{
    // Init values needed for the function
    int delta = getText().length; // This need to be high as possible
    int computedDelta; // We declare here so we don't have to do it in the for loop
    int charIndexToReplace = 0; // The char index to replace by the space line

    // Search for the best index to replace
    for (int i = 0; i < label.getText().length; i++)
    {
        // If char is a space
        if (getText().chars[i] == ' ')
        {
            // Compute distance from the middle of the string
            computedDelta = Math.abs(getText().length / 2 - i);

            // If less than current delta : keep in mind index
            if (computedDelta < delta)
            {
                delta = computedDelta;
                index = i;
            }
        }
    }

    // Replace space by space line
    getText().chars[index] = '\n';
}

```

Then i use it like this :

```
if (myLabel.getWidth() > maxWidth)
     myLabel.cutAtMiddle();

```

It's not such difficult to do the same thing line by line and not specifically by the middle. Hope it helps

---
Tags: android, libgdx, gui
---


# Question
Title: Why aren't game bullets implemented as if they were real bullets?
Let's say I'm working on a 3D first-person shooter and the boss is a stickler for realism, and orders me to implement the bullets as tiny projectiles that travel, say, 1000 meters per second. What might be some implementation difficulties, gameplay experience changes, etc. that would result from that decision?

# Answer
The main problem is **tunneling**.

Game physics engines typically use discrete collisions. That means they advance all the bodies by one short time step, then check if they're intersecting, and handle collisions in response.

This works well for medium-sized objects at medium speeds.

But if you have a small object (like a bullet) moving very fast (like a bullet) then a single time step might take it from just about to hit some poor person's face to just past the far side of that person's head. Since the objects are small, they don't intersect in either position, and the physics engine says "great, no collisions to deal with!" and moves on.

But from a player's perspective, a bullet just went through someone's head without affecting it, like it had "quantum tunneled" through it.

Ways to fix this are:

* Bigger, slower collision objects (you can probably get away with extruding the bullet's collider along its flight direction so it's more like a flying lance and more likely to intersect rather than tunnel completely through. You just need to make sure your gun doesn't hit you or things behind you when you fire it, or hit things on the far side of a wall if you shoot directly into it)
* Smaller time steps, but this means more calculations which is slower.
* Continuous collision detection, which models motion swept over time rather than as a series of discrete hops. This can be even slower still - especially against complex collider objects.

You may also find some physics engines rebel when you try to make objects travel above a certain speed. They might refuse, by enforcing an arbitrary speed limit on everything (usually a good thing, as it clamps how badly things can explode when physics glitches happen, and bounds the worst case for some calculations, helping us get faster & more predictable performance). Or they might behave unrealistically - a tiny 8-gram bullet sending a 200 kg soldier flying because the collision system doesn't handle momentum transfer correctly for such huge disparities in mass & velocity. You might need to treat the bullet as a trigger volume if the impact reactions get unruly.
> 12 votes

# Answer
For most games it doesn't make a difference.

Take the Counter Strike series, for example. It simulates firearms combat on rather short distances. On the distances where the average CS shootout takes place, the gameplay difference between the simple hit-scan solution and the far more CPU-intense physics simulation of bullets would be negligible.

On the other hand, there are also games which simulate firearms combat over far larger areas. When you fight over distances of hundreds of meters, bullet drop and bullet velocities start to make a difference. Such games can benefit from a more accurate simulation. But keep in mind that it makes the game harder to play. Players need to develop a feeling for how far they need to lead their target and how far they have to aim above with what gun on what distance. That means a much steeper learning curve and a much wider skill gap between newbies and experienced player.
> 2 votes

# Answer
Depending on the game, implementing realistic bullets would just be a waste of framerate. I mean, FPS's have plenty of moments where multiple people are firing at a massive rate, if bullet objects were to be pumped out like that. Say GOODBYE to 60fps.
> -6 votes

---
Tags: first-person-shooter, projectile-physics
---


# Question
Title: According to Collision Change Rotation of Car
Basically I want to give rotation to player car as per collision occur with wall. Following image gives you over all idea.

I have following code that giving me correct collision reflection but its in position form not for rotation.

```
void OnCollisionEnter2D (Collision2D other)
{
    ContactPoint2D contact = other.contacts [0];
//      Vector3 reflectedVelocity = Vector3.Reflect (direction, contact.normal);
//      direction = reflectedVelocity;

    Quaternion reflectedRot = Quaternion.FromToRotation (transform.up, contact.normal);
    transform.rotation *= reflectedRot;
}

```

What I have to do for getting correct collision rotation for car? As well smooth turn for car on same rotation so car start moving on that way.

Please give me some help for this.

# Answer
> 0 votes
Here is a script I wiped up I think it does what you want. Its pretty self explanatory.

```
   using UnityEngine;

public class Test : MonoBehaviour {
    Vector3 velocity;
    float speed = 5;
    float rotationSpeed = 5;
    void Start()
    {
       // velocity = -transform.up;// This just makes the my cube "fall" in my test scene
         velocity = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), 0f);
    }
    void Update()
    {
        if (velocity != Vector3.zero)
        {
            //transform.rotation = Quaternion.Slerp(
            //    transform.rotation,
            //    Quaternion.LookRotation(velocity),
            //    Time.deltaTime * rotationSpeed
            //);
            float angle = Mathf.Atan2(velocity.y, velocity.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.AngleAxis(angle -90, Vector3.forward),Time.deltaTime*rotationSpeed);
        }
        transform.position += velocity * Time.deltaTime * speed;
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        ContactPoint2D contact;
        contact = other.contacts[0];
        velocity = 2 * (Vector3.Dot(velocity, Vector3.Normalize(contact.normal))) * Vector3.Normalize(contact.normal) - velocity; //Following formula  v' = 2 * (v . n) * n - v

        velocity *= -1;// Dont know why I had to multiply by -1 but it's inversed otherwisae
    }
}

```

---
Tags: unity, rotation
---


title: Fading Text in one character at a time

text:
# Question
Title: Fading Text in one character at a time
I'm a Unity game developer. I have a bit of a conundrum. I have two enumerators, one that displays text one character at a time, and the other takes the whole text and fades it in over time:

```
private IEnumerator FadeTo(float aValue, float tValue)
{
    float alpha = GameText.GetComponent<Text>().color.a;
    for (float i = 0; i < 1.0f; i += Time.deltaTime / tValue)
    {
        Color alphaChange = new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, i));
        GameText.GetComponent<Text>().color = alphaChange;
        yield return null;
    }
}
private IEnumerator CharXChar(string text)
{
    for (int i = 0; i < text.Length; i++)
    {
        yield return new WaitForSeconds(0.1f);
        GameText.GetComponent<Text>().text = GameText.GetComponent<Text>().text + text[i];
    }
}

```

The problem is, I do not know how to get the FadeTo enumerator to modify each character individually. I just need a step in the right direction. Any help would be greatly thanked.

# Answer
> 4 votes
Here's a very ugly solution using rich text. It wraps a `<color=#FFFFFF00> </color>` tag around every letter, then updates the alpha values as the fade progresses along the string.

I'm using the StringBuilder to cut down on unnecessary string allocations, but this still generates one new allocation every frame while the fade is running (fortunately it's always the same size so it shouldn't cause much trouble).

There are probably more efficient options, like positioning a second text element to hold the fading characters, but this was quick and dirty:

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

[RequireComponent(typeof(Text))]
public class TextFade : MonoBehaviour {

    [Tooltip("Number of seconds each character should take to fade up")]
    public float fadeDuration = 2f;

    [Tooltip("Speed the reveal travels along the text, in characters per second")]
    public float travelSpeed = 8f;

    // Cached reference to our Text object.
    Text _text;

    Coroutine _fade;

    // Lookup table for hex characters.
    static readonly char[] NIBBLE_TO_HEX = new char[] {
        '0', '1', '2', '3',
        '4', '5', '6', '7',
        '8', '9', 'A', 'B',
        'C', 'D', 'E', 'F'};

    // Use this for initialization
    void Start () {
        _text = GetComponent<Text>();

        // If you don't want the text to fade right away, skip this line.
        FadeTo(_text.text);
    }

    public void FadeTo(string text)
    {
         // Abort a fade in progress, if any.
         StopFade();

         // Start fading, and keep track of the coroutine so we can interrupt if needed.
         _fade = StartCoroutine(FadeText(text));
    }

    public void StopFade() {
         if(_fade != null)
               StopCoroutine(_fade);
    }

    // Currently this expects a string of plain text,
    // and will not correctly handle rich text tags etc.
    IEnumerator FadeText(string text) {

        int length = text.Length;

        // Build a character buffer of our desired text,
        // with a rich text "color" tag around every character.
        var builder = new System.Text.StringBuilder(length * 26);
        Color32 color = _text.color;
        for(int i = 0; i < length; i++) {
            builder.Append("<color=#");
            builder.Append(NIBBLE_TO_HEX[color.r >> 4]);
            builder.Append(NIBBLE_TO_HEX[color.r & 0xF]);
            builder.Append(NIBBLE_TO_HEX[color.g >> 4]);
            builder.Append(NIBBLE_TO_HEX[color.g & 0xF]);
            builder.Append(NIBBLE_TO_HEX[color.b >> 4]);
            builder.Append(NIBBLE_TO_HEX[color.b & 0xF]);
            builder.Append("00>");
            builder.Append(text[i]);
            builder.Append("</color>");
        }

        // Each frame, update the alpha values along the fading frontier.
        float fadingProgress = 0f;
        int opaqueChars = -1;
        while(opaqueChars < length - 1) {
            yield return null;

            fadingProgress += Time.deltaTime;

            float leadingEdge = fadingProgress * travelSpeed;

            int lastChar = Mathf.Min(length - 1, Mathf.FloorToInt(leadingEdge));

            int newOpaque = opaqueChars;

            for(int i = lastChar; i > opaqueChars; i--) {
                byte fade = (byte)(255f * Mathf.Clamp01((leadingEdge - i)/(travelSpeed * fadeDuration)));
                builder[i * 26 + 14] = NIBBLE_TO_HEX[fade >> 4];
                builder[i * 26 + 15] = NIBBLE_TO_HEX[fade & 0xF];

                if (fade == 255)
                    newOpaque = Mathf.Max(newOpaque, i);
            }

            opaqueChars = newOpaque;

            // This allocates a new string.
            _text.text = builder.ToString();
        }

        // Once all the characters are opaque,
        // ditch the unnecessary markup and end the routine.
        _text.text = text;

        // Mark the fade transition as finished.
        // This can also fire an event/message if you want to signal UI.
        _fade = null;
    }
}

```

Here's an example of the effect:

# Answer
> -1 votes
There are a couple things you could try but not necessarily with the code you have right now, but rather with tools Unity provides.

You could first try adding in a canvas with the text, when you add it in, from there you can directly modify the alpha value of the canvas which would fade it in/out. More Here.

You can also try GUITextures as they have fade properties as well. They have access to colors too. More Here.

And here is a C# solution I found, I am only linking this one because I can't take credit for it ;) It seems to be similar to yours in that it uses enumerators but it also does the update to it with input from the keyboard, which you could easily alter so whatever you want can call those methods.

---
Tags: unity
---


title: multiply matrix4x4 with vec4

text:
# Question
Title: multiply matrix4x4 with vec4
I'm developing a game and I'd like to make model * pos4 calc (that's usual in glsl vertex shader) in cpu instead of doing it in gpu. I'm using LWJGL and for the math impl I use JOML. Anyone know how to multiply a vec4 with a matrix 4x4? It would be nice showing me the JOML code but also the way to mul the mat values with the vec4 values is fine!

# Answer
Matrix-vector multiplication works the same as matrix-matrix multiplication, because a 4d vector is basically matrix with one of the dimensions equal to 1.

---

If we have a vector `v = (x; y; z; w)` and a matrix

```
    a b c d
M = e f g h
    i j k l
    m n o p

```

Then `M * v` is equal to

```
(x*a + y*b + z*c + w*d;
 x*e + y*f + z*g + w*h;
 x*i + y*j + z*k + w*l;
 x*m + y*n + z*o + w*p)

```

And `v * M` is equal to

```
(x*a + y*e + z*i + w*m;
 x*b + y*f + z*j + w*n;
 x*c + y*g + z*k + w*o;
 x*d + y*h + z*l + w*p)

```

---

To do `M * v` in JOML, you need to use the matrix's `transformPosition()` method:

```
yourMatrix.transformPosition(yourVector);

```
> 4 votes

# Answer
**You should read these nice tutorials about matrices and vectors.**

`matrix × vector` is a degenerate case of `matrix × matrix` multiplication.

(A vector can be considered a matrix with width or height equal to 1.)

---

Here is how `matrix × matrix` multiplication is performed:

Assume we have two matrices, `A` and `B`.

If `A` has size `m×n` and B has size `n×p`, then the resulting matrix `C` will have size `m×p`.

(We're using mathematical notation here. In `α×β` the first letter denotes height and the second letter denotes width.)

Notice how the same letter `n` denotes both the width of `A` and height of `B`. If they are different, you can't multiply such matrices.

Let's call resulting matrix `C(m×p)`.

Then, to get a single element `C[y][x]` of the resulting matrix, you must take y-th row from the `A` and x-th column from the `B`, multiply them component-wise and add together the results.

Here is some pseudocode:

```
const int m = ...;
const int n = ...;
const int p = ...;

float a[m][n] = {...};
float b[n][p] = {...};
float c[m][p];

for (int i = 0; i < m; i++)
{
    for (int j = 0; j < p; j++)
    {
        c[i][j] = 0;

        for (int k = 0; k < n; k++)
        {
            c[i][j] += a[i][k] * b[k][j];
        }
    }
}

```

---

For example, if

```
    / 1 2 5 \         / 0 5 \
A = | 3 5 4 |     B = | 3 9 |
    \ 0 7 9 /         \ 1 4 /

```

Then `C` will be 2 numbers wide and 3 numbers high.

Let's compute a single element:

```
C[2][1] = A[2][0] * B[0][1] +
          A[2][1] * B[1][1] +
          A[2][2] * B[2][1] =

        =    0    *    5    +
             7    *    9    +
             9    *    4    =

        = 99

```

---

As I said, when you multiply a vector and a matrix together, the vector is treated as a matrix too. If you do `vector × matrix`, then `vector` is treated as a matrix of size `1×n`. If it's `matrix × vector`, then `vector` has size `n×1`.

It's not too hard to understand. If you orient your vector incorrectly (`1×n` instead of `nx1` or vice versa), then the width of `A` would no longer be equal to the height of `B`.

Resulting vector will always have the same orientation (row or column) as the original vector.

---

**P.S.** I'm not familiar with JOML, but if @Bálint is correct, then `yourMatrix.transformPosition(yourVector);` performs `matrix × vector`, which is what you need.

---

**P.P.S.** @Bálint 's claim that memory ordering of a matrix (row or column major) affects computations is not correct. The above formula always holds true.
> 1 votes

---
Tags: opengl, mathematics, glsl, matrix, lwjgl
---


# Question
Title: Questions related to rendering to texture and rendering to buffer (OpenGL)
I am experimenting with off-screen rendering. I understand there is two solutions to this:

1. rendering to texture (you attach a texture to one of the FBO's attachment point which can be a color, depth, etc.)
2. use a render buffer.

## Question 1

I first experimented with using render-buffers. I have a FBO and 2 RBOs, one for color (attached to COLOR0) and one for depth (attached to DEPTH). When I want to visualise the content of what I rendered to the render buffer, I use the `glBlitFramebuffer` function to copy the content from the FBO to the Window frame buffer (index 0).

```
glBindFramebuffer(GL_READ_FRAMEBUFFER, fboId);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);

```

First I would like to know if this the best way? (of passing the image from the a render buffer back to the window buffer).

## Question 2

My second question. The method I described above works but I can only see the "color" buffer of the FBO, not the depth buffer (I would also like to visualise the depth buffer). So I was wondering how/if this was possible using this approach? I tried to use the index of the depth render buffer in place of the `fboIdx` in `glBindFramebuffer` but it didn't change anything. Can I make it work without using render-to-texture approach?

## Question 3

My end goal is to render two images using an off-screen approach and blend them together. The result of the mix between the two rendered images is what I want to display to the screen. To keep things fast, I understand this can be done in hardware. What's the best way for doing this? Can it be done using the render-buffer approach or do I need to go the render-to-texture approach (aka render to two textures and then blend these textures using a fragment shader when I do my final pass in which I render a quad stretched over the surface of the screen?

# Answer
Although I'm not an expert (I'm still trying to find my way through the blitting and all its problems) I'll try to help you out (since I can't comment).

Q.1

Yes blitbuffer is a neat way of copying data back and forth between buffers, and it was specifically introduced to provide such functionality, without the need of messing around with copyPixels and drawPixels functions of the API.

Q.2

I think the reason why it doesn't work for you is because you haven't included the GL\_DEPTH\_BUFFER\_BIT flag in the clearmask option of the glBlitFramebuffer call. Especially if the draw and read buffers were created with exactly the same size, options and attributes this should work out of the box.

Q.3

I think the answer to your problems is the glFramebufferTexture2D() function. In addition to your renderbuffers, you can also attach textures to specific attachments of the framebuffer (e.g ColorAttachment0, DepthAttachment) just like you would do in the render-to-texture case. This way, the fbo stores its information on only to the renderbuffers, but also to textures, which you can use whatever way you like afterwards.

Now concerning the mixing, because I'm not sure what exactly you want to do, I would suggest to just prepare the fbo textures (offsreen rendering) then bind the default framebuffer, render a quad and mix the 2 textures whichever way you like in the fragment shader.

If you want to make some serious post processing after the rendering stages i think you should stay with the render to texture approach, because this is what you need eventually. If you just want to copy data from one framebuffer to the other without any serious blending between them, I think blitbuffer should do the job for you.
> 1 votes

---
Tags: opengl
---


# Question
Title: Room Based User Authentication without having a user database
I'm looking to make a web-app/game where people do not need an account to play, but the game is room based, and once the game has started the room closes. I'm most familiar with Spring/REST services as a back-end.

The best example for this type of system is the Jackbox Games backend (Quiplash, Drawful, etc). The way theirs works is:

1. Go to landing page
2. Enter desired username and also a "room code" of the room to join (note: anyone can join, no account needed)
3. Click start game when all users are in
4. Play game, no more users can join

Anyone have any ideas of how to approach this?

I'm familiar with having users authenticate against a database on a login call to the server. And also I'm pretty familiar with how I might pass around payloads via JWT, but I'm having a bit of trouble piecing together how I might create the rooms and then close them. Also keeping users "logged in" until the game ends.

Any suggestions would be wonderful.

Thanks.

# Answer
# Keep a list of room codes for opened rooms, and when the game begins, remove the room code from the list to close it

You can keep the room codes for currently open rooms on the server-side in some sort of a list. Any room which is open for joining will have its code on this list, whereas any room which hasn't been created yet or is not open for joining does not have an entry on that list.

# Room joining flow

1. When user enters the username and room code, you check whether the room code is present on the "open rooms" list. If it does, you add the user to the list of users waiting for the game in a room to begin.
2. When all players have joined, the game begins. You close the room by removing its entry from the "open rooms" list. Players start playing now.
3. No-one can now join the room, as the "open rooms" list no longer has an entry for it. The room code is no longer valid for anyone who wants to join, so the room is effectively closed to everyone outside of the game session.

(Note: this assumes that there are no passwords for individual user accounts. In this case a separate user authentication feature needs to be added, as otherwise users can pick any username they want.)
> 2 votes

# Answer
From your comment on the other answer you are saying that you are primarily having trouble about how to keep the user logged in.

From the games I've worked on, a standard practice is to create an anonymous player account when the game is first loaded using a randomised identifier and secret. You then log in by providing these access details to the backend server in exchange for a session token that can be used to authenticate subsequent requests. Session tokens are usually time-limited and must be refreshed using the original identifier and secret.

You've mentioned JWT tokens - they are indeed a good way to handle session authentication for these types of services. One of the main benefits of JWT is that the tokens are stateless, so you server does not need to maintain a list of valid tokens - this has scaling benefits as there is no need to maintain a central store amongst all your servers.

The JWT standard also contains built-in support for token expiry times. There are many libraries available for validating and constructing JWT tokens. One the disadvantages of JWT is that there is n oway to invalidate an existing token, aside from maintaining a list on your server and checking that list every time you validate a token.

Alternatively, you could also use an existing game backend service to store your player accounts and your room list. These will come with login and authentication support already and could simplify what you are trying to do. ChilliConnect offers both these features. Full disclaimer: I work for ChilliConnect.
> 1 votes

---
Tags: java
---


# Question
Title: Why add a transparent border to a texture?
I've seen game developers give advice to add a transparent border around sprites, for example around 3:00 minutes into this tutorial.

Why should we leave a transparent border around a texture before using it in these cases?

And how broad should this border be?

Also I found one of my friends saying to me that when he rendered multiple copies of same texture by u v coordinates, he got some white lines at texture to texture intersections.

Adding borders fixed that as per the answer he got from his question at this site.

# Answer
> 7 votes
> Why do we leave a transparent border in any texture before using it in opengl or any other texture loading place in games.

We don't always.

Sometimes we do, however. It all depends on the requirements of the texture we are loading. Some examples:

* If it is a standard texture for a wall, floor or similar, and if the texture is to be tiled, we don't use a border at all. A border will break up the tiling and look horrible.
* If it is in a texture atlas and is not to be mipmapped, we might consider a 1 texel border to prevent adjacent textures in the atlas from bleeding into each other with linear filtering. Mipmapped textures in an atlas will need a larger border.
* If it is a sprite texture we might consider adding a border so that linear filtering at the edges looks correct.
* If it is a cubemap for a skybox, environment map, or similar, we don't don't use a border at all. A border will prevent seamless blending between adjacent faces.
* If it is a spritesheet for an animated character or effect, we might add borders so that all frames in the animation are the same size, which simplifies texture addressing.

# Answer
> 7 votes
A border helps to to avoid some artifacts of upscaling with linear interpolation.

Note that bottom and right corners remain smooth, while top and left ones do not.

Since the author of the video doesn't use linear filtering, the border seems to be completely pointless.

# Answer
> 1 votes
The "border" around the texture you linked is simply empty space, because the character has multiple animation states and at some point her width is bigger than on other points (like when her arms are right next to her body versus when her arms are in front of her). It's easier to make every state have the same width than to make the engine guess how wide they are.

---
Tags: opengl, textures
---


title: Unity3d saving with prefabs: Bad Idea?

text:
# Question
Title: Unity3d saving with prefabs: Bad Idea?
I am developing for Android.In my game data is in objects which aren't derived from MonoBehaviour.So I am using binary serializer and taking references from the gameobject.It works, but I have too many variables to save most of variables are in script attached to gameobject Gamemanager So I made a prefab of gameobject of Gamemanager and saved it using prefabutility and load it again It works but Can someone tells me whether this is right approach or not, please??

# Answer
This is going to work as long as you run your project from the editor. But when you try to actually build it, you will notice that it doesn't compile. The reason for that is that the class PrefabUtility is part of the UnityEditor packet, which doesn't get added to real builds of your game.

I ran into the same trap in my last project. I was lucky that I only used PrefabUtility in my map editor which I was going to dummy out of the release build anyway.

You will have to find a different solution to serialize your gamestate.

One possible alternative is the class JSONUtility which allows you to convert objects to JSON and back. It doesn't work on complete game objects, but it works with anything which extends `MonoBehaviour` or `ScriptableObject` and with any plain C# class when it has the `[System.Serializable]` attribute. Note that it will only serialize the `public` variables and properties of your classes.
> 5 votes

# Answer
Use a ScriptableObject instead and mark the classes you want to serialize in it with \[System.Serializable\]. Mark each field you want to serialize into the .asset file with \[SerializeField\] or make it public.

When you've created the asset file, put it in the Resources folder and load it runtime with Resources.Load("assetPath"). Since it's an asset you should not have to Instantiate it once you load.

This handles serialization in the same way as a monobehaviour, but in an asset file on disk instead. It can handle arbitrarily much data up to a certain limit. If you have more than that, you should reorganize your data in multiple files instead.
> 2 votes

---
Tags: unity
---


# Question
Title: Isometric tile picking algorithm not working
Starting to gamedev again and Trying an isometric game. However, all I try, I can't seem to figure out tile picking properly.. Using SFML

Here's how I'm detecting the clicks and moving around a sf::View. Sprites are 64\*32

```
#include "GameWorld.h"
#include <math.h>
GameWorld::GameWorld()
{
    this->camX = 0;
    this->camY = 0;
    this->factories.push_back(new Factory("Factory 1"));
}

void GameWorld::draw(sf::RenderWindow * win, ContentManager* contentManager) {
this->factories.at(this->activeFactory)->render(win,contentManager, this->camX, this->camY);
}

void GameWorld::update(float delta, sf::RenderWindow* win) {
    float speed= 128;
    sf::View view = win->getView();

if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
    this->camY -= speed*delta;

}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
    this->camX -= speed*delta;

}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
    this->camY += speed*delta;

}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
    this->camX += speed*delta;
}
view.setCenter(this->camX,this->camY);

win->setView(view);

if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {

sf::Vector2i selectedTile;
int x = sf::Mouse::getPosition(*win).x - this->camX;
int y = sf::Mouse::getPosition(*win).y - this->camY;
selectedTile.x = (y + x/2)/32;
selectedTile.y = (y - x/2)/32;

        printf("%d %d %d %d\n",sf::Mouse::getPosition(*win).x,sf::Mouse::getPosition(*win).y, selectedTile.x,selectedTile.y);
   }

}

```

The map is a 2d vector, which gets drawn like so

```
float screenX = (indexX - indexY) * this->sprite->getGlobalBounds().width/2;
float screenY = (indexX + indexY) * this->sprite->getGlobalBounds().height/2;

this->sprite->setPosition(sf::Vector2f(screenX,screenY));

win->draw(*this->sprite);

```

Here's what this currently prints out: When the game is loaded initially - clicking the first tile rendered (0,0) outputs 21 0 as the computed coords. As you can see, the X value is completely off, and the Y value goes off aswell as soon as I move the view in any direction. How could I get this picker to work properly?

# Answer
> 1 votes
Problem solved.

Working code thanks to https://www.twitch.tv/siegegames

```
    sf::Vector2f view_mouse_position = win->mapPixelToCoords(sf::Mouse::getPosition(*win));
    float x = view_mouse_position.x / 64;
    float y = view_mouse_position.y / 32;

    int tile_x = x + y;
    int tile_y = x - y;

```

---
Tags: c++, tiles, isometric, sfml, picking
---


title: Measure elapsed gpu time of draw call

text:
# Question
Title: Measure elapsed gpu time of draw call
I'm rendering to a texture via DrawIndexedPrimitive (SharpDx). In some specific situations, the framerate drops significantly when doing this render. The framerate can be improved by rendering to a smaller texture.

I want to gracefully degrade the quality of the graphics performance at runtime by measuring the impact of this particular pass and rendering to a smaller texture if the framerate would be impacted by this pass. Later, when the impact of this pass is smaller I want to restore the larger texture size.

Is there some way to measure at runtime the impact of a particular draw on the gpu? It's ok if the results of the measurement are delayed to the next frame.

# Answer
> 1 votes
First up the best place to start is the MSDN docs about GPU queries

The basic idea is to wrap your calls in a queries begin and end functions and then wait a few frames to read the info back from the GPU.

I haven't done much query work in DX9 so I cant help much more than showing you how I setup DX11 occlusion queries.

Best bet would be to do this in a none blocking way something like this every frame to check if the query has returned

```
  //Setup Query
  Dim qdesc As QueryDescription
  qdesc.Flags = QueryFlags.None
  qdesc.Type = QueryType.Occlusion
  g_pPredicate = New Query(_device, qdesc)

  //Running the Query
 _context.ImmediateContext.Begin(g_pPredicate)
 BoundingBoxRenderer.DrawEX(_device, Bounding, _camera, Color.Red, _context)
 _context.ImmediateContext.End(g_pPredicate)

 // Checking If The Query Has Returned
 HasData = _context.IsDataAvailable(g_pPredicate)
 If HasData then
   return pPredicate
 end if

 //Using The Query Data
 If HasData Then
  Dim value As UInt64 = _context.ImmediateContext.GetData(Of UInt64)(g_pPredicate)
    If value > 0 Then
      IsVisible = True
    Else
      IsVisible = False
    End If
   HasData = False
 End If

```

> There are several types of queries which are designed to query the status of resources. The status of a given resource includes graphics processing unit (GPU) status, driver status, or runtime status. To understand the difference between the different query types, you need to understand the query states. The following state transition diagram explains each of the query states.

> The diagram shows three states, each defined by circles. Each of the solid lines are application-driven events that cause a state transition. The dashed line is a resource-driven event that switches a query from the issued state to the signaled state. Each of these states has a different purpose:
>
> •The signaled state is like an idle state. The query object has been generated and is waiting for the application to issue the query. Once a query has completed and transitioned back to the signaled state, the answer to the query can be retrieved.
>
> •The building state is like a staging area for a query. From the building state, a query has been issued (by calling D3DISSUE\_BEGIN) but has not yet transitioned to the issued state. When an application issues a query end (by calling D3DISSUE\_END), the query transitions to the issued state.
>
> •The issued state means that the resource being queried has control of the query. Once the resource finishes its work, the resource transitions the state machine to the signaled state. During the issued state, the application must poll to detect the transition to the signaled state. Once the transition to the signaled state occurs, GetData returns the query result (through an argument) to the application.

---
Tags: directx, performance, gpu
---


# Question
Title: How do I need to tag different (but a little similar) entities with Entity-Component-System pattern
I have some count of weapons - pistol, shotgun, rifle. And I have one system which deals with all weapons, and another system which deals only with pistol. So I need to create both components "weapons" and "pistol", and I add them both to the entity - "Pistol". So now we have next components - "Weapons", "Pistol", "Rifle", "Shotgun", becase probably I will need to have separate system for different weapons in future. Then in the same reasons I create next Components - "Character", "Player", "Enemy", "Friend" (maybe more types of Enemies and Friends), "Ammo", "AmmoForPistol", "AmmoForRifle" ... And there are too much different components only for tagging different entities regarding to the types. How can I avoid this amount of Components?

# Answer
There is really no harm in adding a single `WeaponComponent` which holds a `TYPE` attribute to describe whether it's a Pistol, Rifle, Shotgun, Knife, etc.

Nothing dictates however that you must store all `WeaponComponent` instances in the same list inside your `WeaponSystem` either. In fact, to avoid branching on specific use cases, it might be advantageous to store each `WeaponComponent` in a type-specific list and simply iterate over multiple lists as part of your update loop.

I also don't believe that *Character* and *Player* make sense to be represented as components.

In order to determine hostility vs friendly could simply be derived by checking whether the entity in question has a specific type of component, perhaps `HostileComponent`. The assumption here being that all entities are friendly unless that component exists.

There are plenty of ways to split / tag things through components without going overboard.
> 1 votes

# Answer
> How can I avoid this amount of Components?

You can't.

ECS are made to decouple and *specialize* your game logic. You'll want your components to represent something specific. By doing so, you won't have a choice: you have many tiny components.
> 0 votes

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


# Question
Title: How can I make part of a JLabel visible under mouse movement?
The JLabel has an image of a room. I want the mouse to act as a flashlight, and only display around the mouse the part of the JLabel/image that the mouse is hovering over, in a large circumference.

How do I make a part of the JLabel, relative to the position of the mouse, visible only under the location of the mouse?

# Answer
> 1 votes
There are a few different solutions on Stack Overflow that describe in detail how to do this:

Personally, I think the RadialGradientPaint solution is the one best suited to your needs, since it can make it so that the edges are dimmer than the center, which better emulates the flashlight effect you are looking for.

---
Tags: java, mouse, swing
---


# Question
Title: How can i draw Arc in center of the screen on canvas in android
`RectF rectf = new RectF(10, 100, 700, 800);
c.drawArc(rectf, 0, 90, true, paint);`

the above code is draw the arc using drawArc() method of canvas but i try to draw arc in a center of the screen.

# Answer
This worked for me: in `onDraw()` method:

```
int height = canvas.getHeight() / 2;
int width = canvas.getWidth() / 2;
mRectF.set(width - 100, height - 100, width + 100, height + 100);

```

Don't initialize `rectF` in `onDraw`, do it in a separate method like `init()` or something else. Set the co-ordinates in `onDraw()`.
> 2 votes

# Answer
The following code will draw an arc in the center of your view:

```
int y = c.getHeight();
RectF rectf = new RectF(getLeft(), y - 100, getRight(), y);
c.drawArc(rectf, 0, -180, true, paint);

```

Note: `c` is an instance of Canvas as used in the question.
> 0 votes

---
Tags: android
---


# Question
Title: LibGDX moving game window with mouse drag
## TL;DR

How can I move window with mouse without tide effect.

## Long Version

So when I tried to move my game window via InputListener(just to test if it would work). I got some strange result. The window goes back and forth between last two locations when mouse drags and while button is held.

Game Part

```
Gdx.input.setInputProcessor(new InputAdapter() {
    int b;
    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        b = button;
        // TODO Auto-generated method stub
        Rectangle.tmp.set(0, 0, 100, 100);
        if (Rectangle.tmp.contains(screenX, screenY)) {
            lastx = screenX;
            lasty = screenY;
            System.err.println("Touch ( " + screenX + " , " + screenY + " )");
        }

        return true;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        if (lastx != null && tr != null) {
            tr.translate(screenX - lastx, screenY - lasty);
            System.err.println("Drag  ( " + lastx + " - " + screenX + " , " + lasty + " - " + screenY + " )");
            lastx = screenX;
            lasty = screenY;
        }
        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        lastx = null;
        lasty = null;
        System.err.println("Up ( " + lastx + " , " + lasty + " )");
        return true;
    }
});

```

DesktopLauncher Part

```
Game.tr = new Translator() {

    @Override
    public boolean translate(int x, int y) {
        Display.setLocation(Display.getX() + x, Display.getY() + y);
        return true;
    }
};

```

PS: What I try&tried to make may look stupid.

Edit: Actually I noticed that window moves less than actual mouse movement. Edit2: When I move the movement code to touchUp I get exact result as movement.

# Answer
> 1 votes
So I changed my code as this.

Game Code

```
    Gdx.input.setInputProcessor(new InputAdapter() {
        int offsetX;
        int offsetY;
        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            offsetX = screenX;
            offsetY = screenY;
            System.err.println("Touch (" + screenX + " , " + screenY + ")");
            return true;
        }

        @Override
        public boolean touchDragged(int screenX, int screenY, int pointer) {
            tr.translate(offsetX, offsetY);
            return true;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            offsetX = 0;
            offsetY = 0;
            return true;
        }
    });

```

Desktop Launcher Code

```
    MyGame.tr = new Translator() {

        @Override
        public boolean translate(int x, int y) {
            // WINDOW_HEIGHT is a static variable on launcher code. In my case that would be enough but there is Display.getHeight function if someone needs.
            Display.setLocation(Display.getX() + (Mouse.getX() - x), Display.getY() + (WINDOW_HEIGHT- Mouse.getY() - y));
            return true;
        }
    };

```

So instead of trying to use touchDragged to move window. I cache the relative location of my window where the mouse pressed. And move the window to catch that point. this may or may not change the fact that game would pause rendering or not cause I currently do not have anything to render.

---
Tags: libgdx
---


# Question
Title: Is it possible to use animated .gif images in lbgdx?
Is it possible to use animated .gif images in lbgdx? If not how whats the alternative? We need to include animated buttons.

When I use an animated gif, the animation won't play. This question (and many others) states that Libgdx doesn't support it, I'm wondering if something has changed over the years

# Answer
> 7 votes
There is a `GifDecoder` class that turn a **.gif** file into a **libGDX** `Animation`. With it, you can render animated **.gif**s like this;

```
public class SandboxGame extends ApplicationAdapter {
    SpriteBatch batch;
    Animation<TextureRegion> animation;
    float elapsed;

    @Override
    public void create () {
        batch = new SpriteBatch();
        animation = GifDecoder.loadGIFAnimation(Animation.PlayMode.LOOP, Gdx.files.internal("throbber.gif").read());
    }

    @Override
    public void render () {
        elapsed += Gdx.graphics.getDeltaTime();
        Gdx.gl.glClearColor(1, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        batch.draw(animation.getKeyFrame(elapsed), 20.0f, 20.0f);
        batch.end();
    }

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

```

The `GifDecoder` reads all the frames of the **.gif** and sticks them into an `Array` of `TextureRegions`, this gives you a lot of control of the playback.

The `GifDecoder` isn't part of the **libGDX** library, it was written by Johannes Borchardt and converted to **libGDX** by Anton Person, below is an updated version where I've taken their code and updated it to fit the latest version of **libGDX**;

```
/* Copyright by Johannes Borchardt */
/* LibGdx conversion 2014 by Anton Persson */
/* Released under Apache 2.0 */
/* https://code.google.com/p/animated-gifs-in-android/ */

package com.holidaystudios.tools;

import java.io.InputStream;
import java.util.Vector;

import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Array;

public class GifDecoder {
    /**
     * File read status: No errors.
     */
    public static final int STATUS_OK = 0;
    /**
     * File read status: Error decoding file (may be partially decoded)
     */
    public static final int STATUS_FORMAT_ERROR = 1;
    /**
     * File read status: Unable to open source.
     */
    public static final int STATUS_OPEN_ERROR = 2;
    /** max decoder pixel stack size */
    protected static final int MAX_STACK_SIZE = 4096;
    protected InputStream in;
    protected int status;
    protected int width; // full image width
    protected int height; // full image height
    protected boolean gctFlag; // global color table used
    protected int gctSize; // size of global color table
    protected int loopCount = 1; // iterations; 0 = repeat forever
    protected int[] gct; // global color table
    protected int[] lct; // local color table
    protected int[] act; // active color table
    protected int bgIndex; // background color index
    protected int bgColor; // background color
    protected int lastBgColor; // previous bg color
    protected int pixelAspect; // pixel aspect ratio
    protected boolean lctFlag; // local color table flag
    protected boolean interlace; // interlace flag
    protected int lctSize; // local color table size
    protected int ix, iy, iw, ih; // current image rectangle
    protected int lrx, lry, lrw, lrh;
    protected DixieMap image; // current frame
    protected DixieMap lastPixmap; // previous frame
    protected byte[] block = new byte[256]; // current data block
    protected int blockSize = 0; // block size last graphic control extension info
    protected int dispose = 0; // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
    protected int lastDispose = 0;
    protected boolean transparency = false; // use transparent color
    protected int delay = 0; // delay in milliseconds
    protected int transIndex; // transparent color index
    // LZW decoder working arrays
    protected short[] prefix;
    protected byte[] suffix;
    protected byte[] pixelStack;
    protected byte[] pixels;
    protected Vector<GifFrame> frames; // frames read from current file
    protected int frameCount;

    private static class DixieMap extends Pixmap {
        DixieMap(int w, int h, Pixmap.Format f) {
            super(w, h, f);
        }

        DixieMap(int[] data, int w, int h, Pixmap.Format f) {
            super(w, h, f);

            int x, y;

            for(y = 0; y < h; y++) {
                for(x = 0; x < w; x++) {
                    int pxl_ARGB8888 = data[x + y * w];
                    int pxl_RGBA8888 =
                            ((pxl_ARGB8888 >> 24) & 0x000000ff) | ((pxl_ARGB8888 << 8) & 0xffffff00);
                    // convert ARGB8888 > RGBA8888
                    drawPixel(x, y, pxl_RGBA8888);
                }
            }
        }

        void getPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height) {
            java.nio.ByteBuffer bb = getPixels();

            int k, l;

            for(k = y;  k < y + height; k++) {
                int _offset = offset;
                for(l = x; l < x + width; l++) {
                    int pxl = bb.getInt(4 * (l + k * width));

                    // convert RGBA8888 > ARGB8888
                    pixels[_offset++] = ((pxl >> 8) & 0x00ffffff) | ((pxl << 24) & 0xff000000);
                }
                offset += stride;
            }
        }
    }

    private static class GifFrame {
        public GifFrame(DixieMap im, int del) {
            image = im;
            delay = del;
        }

        public DixieMap image;
        public int delay;
    }

    /**
     * Gets display duration for specified frame.
     *
     * @param n
     *          int index of frame
     * @return delay in milliseconds
     */
    public int getDelay(int n) {
        delay = -1;
        if ((n >= 0) && (n < frameCount)) {
            delay = frames.elementAt(n).delay;
        }
        return delay;
    }

    /**
     * Gets the number of frames read from file.
     *
     * @return frame count
     */
    public int getFrameCount() {
        return frameCount;
    }

    /**
     * Gets the first (or only) image read.
     *
     * @return BufferedPixmap containing first frame, or null if none.
     */
    public Pixmap getPixmap() {
        return getFrame(0);
    }

    /**
     * Gets the "Netscape" iteration count, if any. A count of 0 means repeat indefinitely.
     *
     * @return iteration count if one was specified, else 1.
     */
    public int getLoopCount() {
        return loopCount;
    }

    /**
     * Creates new frame image from current data (and previous frames as specified by their disposition codes).
     */
    protected void setPixels() {
        // expose destination image's pixels as int array
        int[] dest = new int[width * height];
        // fill in starting image contents based on last image's dispose code
        if (lastDispose > 0) {
            if (lastDispose == 3) {
                // use image before last
                int n = frameCount - 2;
                if (n > 0) {
                    lastPixmap = getFrame(n - 1);
                } else {
                    lastPixmap = null;
                }
            }
            if (lastPixmap != null) {
                lastPixmap.getPixels(dest, 0, width, 0, 0, width, height);
                // copy pixels
                if (lastDispose == 2) {
                    // fill last image rect area with background color
                    int c = 0;
                    if (!transparency) {
                        c = lastBgColor;
                    }
                    for (int i = 0; i < lrh; i++) {
                        int n1 = (lry + i) * width + lrx;
                        int n2 = n1 + lrw;
                        for (int k = n1; k < n2; k++) {
                            dest[k] = c;
                        }
                    }
                }
            }
        }
        // copy each source line to the appropriate place in the destination
        int pass = 1;
        int inc = 8;
        int iline = 0;
        for (int i = 0; i < ih; i++) {
            int line = i;
            if (interlace) {
                if (iline >= ih) {
                    pass++;
                    switch (pass) {
                        case 2:
                            iline = 4;
                            break;
                        case 3:
                            iline = 2;
                            inc = 4;
                            break;
                        case 4:
                            iline = 1;
                            inc = 2;
                            break;
                        default:
                            break;
                    }
                }
                line = iline;
                iline += inc;
            }
            line += iy;
            if (line < height) {
                int k = line * width;
                int dx = k + ix; // start of line in dest
                int dlim = dx + iw; // end of dest line
                if ((k + width) < dlim) {
                    dlim = k + width; // past dest edge
                }
                int sx = i * iw; // start of line in source
                while (dx < dlim) {
                    // map color and insert in destination
                    int index = ((int) pixels[sx++]) & 0xff;
                    int c = act[index];
                    if (c != 0) {
                        dest[dx] = c;
                    }
                    dx++;
                }
            }
        }
        image = new DixieMap(dest, width, height, Pixmap.Format.RGBA8888);
        //Pixmap.createPixmap(dest, width, height, Config.ARGB_4444);
    }

    /**
     * Gets the image contents of frame n.
     *
     * @return BufferedPixmap representation of frame, or null if n is invalid.
     */
    public DixieMap getFrame(int n) {
        if (frameCount <= 0)
            return null;
        n = n % frameCount;
        return ((GifFrame) frames.elementAt(n)).image;
    }

    /**
     * Reads GIF image from stream
     *
     * @param is
     *          containing GIF file.
     * @return read status code (0 = no errors)
     */
    public int read(InputStream is) {
        init();
        if (is != null) {
            in = is;
            readHeader();
            if (!err()) {
                readContents();
                if (frameCount < 0) {
                    status = STATUS_FORMAT_ERROR;
                }
            }
        } else {
            status = STATUS_OPEN_ERROR;
        }
        try {
            is.close();
        } catch (Exception e) {
        }
        return status;
    }

    /**
     * Decodes LZW image data into pixel array. Adapted from John Cristy's BitmapMagick.
     */
    protected void decodeBitmapData() {
        int nullCode = -1;
        int npix = iw * ih;
        int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
        if ((pixels == null) || (pixels.length < npix)) {
            pixels = new byte[npix]; // allocate new pixel array
        }
        if (prefix == null) {
            prefix = new short[MAX_STACK_SIZE];
        }
        if (suffix == null) {
            suffix = new byte[MAX_STACK_SIZE];
        }
        if (pixelStack == null) {
            pixelStack = new byte[MAX_STACK_SIZE + 1];
        }
        // Initialize GIF data stream decoder.
        data_size = read();
        clear = 1 << data_size;
        end_of_information = clear + 1;
        available = clear + 2;
        old_code = nullCode;
        code_size = data_size + 1;
        code_mask = (1 << code_size) - 1;
        for (code = 0; code < clear; code++) {
            prefix[code] = 0; // XXX ArrayIndexOutOfBoundsException
            suffix[code] = (byte) code;
        }
        // Decode GIF pixel stream.
        datum = bits = count = first = top = pi = bi = 0;
        for (i = 0; i < npix;) {
            if (top == 0) {
                if (bits < code_size) {
                    // Load bytes until there are enough bits for a code.
                    if (count == 0) {
                        // Read a new data block.
                        count = readBlock();
                        if (count <= 0) {
                            break;
                        }
                        bi = 0;
                    }
                    datum += (((int) block[bi]) & 0xff) << bits;
                    bits += 8;
                    bi++;
                    count--;
                    continue;
                }
                // Get the next code.
                code = datum & code_mask;
                datum >>= code_size;
                bits -= code_size;
                // Interpret the code
                if ((code > available) || (code == end_of_information)) {
                    break;
                }
                if (code == clear) {
                    // Reset decoder.
                    code_size = data_size + 1;
                    code_mask = (1 << code_size) - 1;
                    available = clear + 2;
                    old_code = nullCode;
                    continue;
                }
                if (old_code == nullCode) {
                    pixelStack[top++] = suffix[code];
                    old_code = code;
                    first = code;
                    continue;
                }
                in_code = code;
                if (code == available) {
                    pixelStack[top++] = (byte) first;
                    code = old_code;
                }
                while (code > clear) {
                    pixelStack[top++] = suffix[code];
                    code = prefix[code];
                }
                first = ((int) suffix[code]) & 0xff;
                // Add a new string to the string table,
                if (available >= MAX_STACK_SIZE) {
                    break;
                }
                pixelStack[top++] = (byte) first;
                prefix[available] = (short) old_code;
                suffix[available] = (byte) first;
                available++;
                if (((available & code_mask) == 0) && (available < MAX_STACK_SIZE)) {
                    code_size++;
                    code_mask += available;
                }
                old_code = in_code;
            }
            // Pop a pixel off the pixel stack.
            top--;
            pixels[pi++] = pixelStack[top];
            i++;
        }
        for (i = pi; i < npix; i++) {
            pixels[i] = 0; // clear missing pixels
        }
    }

    /**
     * Returns true if an error was encountered during reading/decoding
     */
    protected boolean err() {
        return status != STATUS_OK;
    }

    /**
     * Initializes or re-initializes reader
     */
    protected void init() {
        status = STATUS_OK;
        frameCount = 0;
        frames = new Vector<GifFrame>();
        gct = null;
        lct = null;
    }

    /**
     * Reads a single byte from the input stream.
     */
    protected int read() {
        int curByte = 0;
        try {
            curByte = in.read();
        } catch (Exception e) {
            status = STATUS_FORMAT_ERROR;
        }
        return curByte;
    }

    /**
     * Reads next variable length block from input.
     *
     * @return number of bytes stored in "buffer"
     */
    protected int readBlock() {
        blockSize = read();
        int n = 0;
        if (blockSize > 0) {
            try {
                int count = 0;
                while (n < blockSize) {
                    count = in.read(block, n, blockSize - n);
                    if (count == -1) {
                        break;
                    }
                    n += count;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (n < blockSize) {
                status = STATUS_FORMAT_ERROR;
            }
        }
        return n;
    }

    /**
     * Reads color table as 256 RGB integer values
     *
     * @param ncolors
     *          int number of colors to read
     * @return int array containing 256 colors (packed ARGB with full alpha)
     */
    protected int[] readColorTable(int ncolors) {
        int nbytes = 3 * ncolors;
        int[] tab = null;
        byte[] c = new byte[nbytes];
        int n = 0;
        try {
            n = in.read(c);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (n < nbytes) {
            status = STATUS_FORMAT_ERROR;
        } else {
            tab = new int[256]; // max size to avoid bounds checks
            int i = 0;
            int j = 0;
            while (i < ncolors) {
                int r = ((int) c[j++]) & 0xff;
                int g = ((int) c[j++]) & 0xff;
                int b = ((int) c[j++]) & 0xff;
                tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
            }
        }
        return tab;
    }

    /**
     * Main file parser. Reads GIF content blocks.
     */
    protected void readContents() {
        // read GIF file content blocks
        boolean done = false;
        while (!(done || err())) {
            int code = read();
            switch (code) {
                case 0x2C: // image separator
                    readBitmap();
                    break;
                case 0x21: // extension
                    code = read();
                    switch (code) {
                        case 0xf9: // graphics control extension
                            readGraphicControlExt();
                            break;
                        case 0xff: // application extension
                            readBlock();
                            String app = "";
                            for (int i = 0; i < 11; i++) {
                                app += (char) block[i];
                            }
                            if (app.equals("NETSCAPE2.0")) {
                                readNetscapeExt();
                            } else {
                                skip(); // don't care
                            }
                            break;
                        case 0xfe:// comment extension
                            skip();
                            break;
                        case 0x01:// plain text extension
                            skip();
                            break;
                        default: // uninteresting extension
                            skip();
                    }
                    break;
                case 0x3b: // terminator
                    done = true;
                    break;
                case 0x00: // bad byte, but keep going and see what happens break;
                default:
                    status = STATUS_FORMAT_ERROR;
            }
        }
    }

    /**
     * Reads Graphics Control Extension values
     */
    protected void readGraphicControlExt() {
        read(); // block size
        int packed = read(); // packed fields
        dispose = (packed & 0x1c) >> 2; // disposal method
        if (dispose == 0) {
            dispose = 1; // elect to keep old image if discretionary
        }
        transparency = (packed & 1) != 0;
        delay = readShort() * 10; // delay in milliseconds
        transIndex = read(); // transparent color index
        read(); // block terminator
    }

    /**
     * Reads GIF file header information.
     */
    protected void readHeader() {
        String id = "";
        for (int i = 0; i < 6; i++) {
            id += (char) read();
        }
        if (!id.startsWith("GIF")) {
            status = STATUS_FORMAT_ERROR;
            return;
        }
        readLSD();
        if (gctFlag && !err()) {
            gct = readColorTable(gctSize);
            bgColor = gct[bgIndex];
        }
    }

    /**
     * Reads next frame image
     */
    protected void readBitmap() {
        ix = readShort(); // (sub)image position & size
        iy = readShort();
        iw = readShort();
        ih = readShort();
        int packed = read();
        lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace
        lctSize = (int) Math.pow(2, (packed & 0x07) + 1);
        // 3 - sort flag
        // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color
        // table size
        interlace = (packed & 0x40) != 0;
        if (lctFlag) {
            lct = readColorTable(lctSize); // read table
            act = lct; // make local table active
        } else {
            act = gct; // make global table active
            if (bgIndex == transIndex) {
                bgColor = 0;
            }
        }
        int save = 0;
        if (transparency) {
            save = act[transIndex];
            act[transIndex] = 0; // set transparent color if specified
        }
        if (act == null) {
            status = STATUS_FORMAT_ERROR; // no color table defined
        }
        if (err()) {
            return;
        }
        decodeBitmapData(); // decode pixel data
        skip();
        if (err()) {
            return;
        }
        frameCount++;
        // create new image to receive frame data
        image = new DixieMap(width, height, Pixmap.Format.RGBA8888);
        setPixels(); // transfer pixel data to image
        frames.addElement(new GifFrame(image, delay)); // add image to frame
        // list
        if (transparency) {
            act[transIndex] = save;
        }
        resetFrame();
    }

    /**
     * Reads Logical Screen Descriptor
     */
    protected void readLSD() {
        // logical screen size
        width = readShort();
        height = readShort();
        // packed fields
        int packed = read();
        gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
        // 2-4 : color resolution
        // 5 : gct sort flag
        gctSize = 2 << (packed & 7); // 6-8 : gct size
        bgIndex = read(); // background color index
        pixelAspect = read(); // pixel aspect ratio
    }

    /**
     * Reads Netscape extenstion to obtain iteration count
     */
    protected void readNetscapeExt() {
        do {
            readBlock();
            if (block[0] == 1) {
                // loop count sub-block
                int b1 = ((int) block[1]) & 0xff;
                int b2 = ((int) block[2]) & 0xff;
                loopCount = (b2 << 8) | b1;
            }
        } while ((blockSize > 0) && !err());
    }

    /**
     * Reads next 16-bit value, LSB first
     */
    protected int readShort() {
        // read 16-bit value, LSB first
        return read() | (read() << 8);
    }

    /**
     * Resets frame state for reading next image.
     */
    protected void resetFrame() {
        lastDispose = dispose;
        lrx = ix;
        lry = iy;
        lrw = iw;
        lrh = ih;
        lastPixmap = image;
        lastBgColor = bgColor;
        dispose = 0;
        transparency = false;
        delay = 0;
        lct = null;
    }

    /**
     * Skips variable length blocks up to and including next zero length block.
     */
    protected void skip() {
        do {
            readBlock();
        } while ((blockSize > 0) && !err());
    }

    public Animation<TextureRegion> getAnimation(PlayMode playMode) {
        int nrFrames = getFrameCount();
        Pixmap frame = getFrame(0);
        int width = frame.getWidth();
        int height = frame.getHeight();
        int vzones = (int)Math.sqrt((double)nrFrames);
        int hzones = vzones;

        while(vzones * hzones < nrFrames) vzones++;

        int v, h;

        Pixmap target = new Pixmap(width * hzones, height * vzones, Pixmap.Format.RGBA8888);

        for(h = 0; h < hzones; h++) {
            for(v = 0; v < vzones; v++) {
                int frameID = v + h * vzones;
                if(frameID < nrFrames) {
                    frame = getFrame(frameID);
                    target.drawPixmap(frame, h * width, v * height);
                }
            }
        }

        Texture texture = new Texture(target);
        Array<TextureRegion> texReg = new Array<TextureRegion>();

        for(h = 0; h < hzones; h++) {
            for(v = 0; v < vzones; v++) {
                int frameID = v + h * vzones;
                if(frameID < nrFrames) {
                    TextureRegion tr = new TextureRegion(texture, h * width, v * height, width, height);
                    texReg.add(tr);
                }
            }
        }
        float frameDuration = (float)getDelay(0);
        frameDuration /= 1000; // convert milliseconds into seconds
        Animation<TextureRegion> result = new Animation<TextureRegion>(frameDuration, texReg, playMode);

        return result;
    }

    public static Animation<TextureRegion> loadGIFAnimation(Animation.PlayMode playMode, InputStream is) {
        GifDecoder gdec = new GifDecoder();
        gdec.read(is);
        return gdec.getAnimation(playMode);
    }
}

```

As a side note, using animated **.gif**s might not be the best format to use for a game, but if you already have all the animations done in **.gif**-format then I guess it could be a way to get quickly up and running.

# Answer
> 4 votes
You **can't use .gif** in libgdx. But you can make yours. A .gif is a list of images displayed frame by frame at a fixed framerate.

You could decompose the .gif into several .png which can be loaded as *textures* and then animate them like below. I won't cover the .gif decomposition here.

This is an *example of implementation* as Sprite (same way to do it from an actor). This is not THE solution, but this is one.

```
public class AnimatedSprite extends Sprite
{
    // Attributes
    private Texture[] frames; // Your frames
    private int currentFrame; // This value will iterate over frames to display the right frame
    private float fps; // Your frame rate in frame per second
    private float timer;

    // Constructor
    public AnimatedSprite(Texture[] frames, float framePerSecond)
    {
        super(frames[0]); // Init your sprite with the first frame texture

        fps = framePerSecond;
        currentFrame = 0;
        timer = 0;
    }

    public void update(float elapsedTime)
    {
        if (timer < 1.0 / fps)
            timer += elapsedTime;
        else
        {
            timer -= 1.0 / fps;
            nextFrame();
        }
    }

    public void nextFrame()
    {
        // Change frame
        if (currentFrame < frames.length)
            currentFrame++;
        else
            currentFrame = 0;

        // Set the good frame texture
        setTexture(frames[currentFrame]);
    }
}

```

You could also override the **draw** method of sprite to draw *texture\[currentFrame\]* instead of *texture*

This subject is also covered in the libgdx's wiki

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


# Question
Title: How to add event listener to Gifdecoder in Libgdx?
I asked this question and implemented the accepted answer. One last piece of the puzzle remains, how to add event listener to the button?

I'm working with a teammate, I suggested to try `Gdx.input.justTouched()` but he wonders if it's possible to add event listeners like you would do for normal buttons.

# Answer
One way to achieve this could be to extend the existing `Button` class and provide an implementation that sets the `up`, `down`, `checked` and `disabled` `Drawable`s of the `ButtonStyle` to whatever the last key-frame of the animation loaded is.

That way you'd get standard button behavior and the only thing that changes is the (somewhat weird) continuously updating style.

Such a `Button` might look something like this; package com.bornander.sandbox;

```
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;

public class AnimatedButton extends Button {

    private float elapsed;
    // Technically you'll need one of these for each state of the ButtonStyle, but I'll just cover up and down here.
    private final Animation<TextureRegion> upAnimation;
    private final Animation<TextureRegion> downAnimation;
    private final ButtonStyle overrideStyle = new ButtonStyle();
    private final TextureRegionDrawable upDrawable = new TextureRegionDrawable();
    private final TextureRegionDrawable downDrawable = new TextureRegionDrawable();

    public AnimatedButton(Animation<TextureRegion> upAnimation, Animation<TextureRegion> downAnimation) {
         this.upAnimation = upAnimation;
         this.downAnimation = downAnimation;
    }

    @Override
    public void act(float delta) {
        super.act(delta);
        elapsed += delta;

        upDrawable.setRegion(upAnimation.getKeyFrame(elapsed));
        downDrawable.setRegion(downAnimation.getKeyFrame(elapsed));
        overrideStyle.up = upDrawable;
        overrideStyle.down = downDrawable;

        setStyle(overrideStyle);
    }
}

```

And it would be instantiated with a list of animations (possibly created using a `GifDecoder`) for each state. Then it is possible to add listeners for clicked just like any other button owned by a `Stage`;

```
package com.bornander.sandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Animation;
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.ui.Button;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.holidaystudios.tools.GifDecoder;

public class SandboxGame extends ApplicationAdapter {

    Stage stage;

    @Override
    public void create () {
        stage = new Stage(new ScreenViewport());

        Animation<TextureRegion> upAnimation = GifDecoder.loadGIFAnimation(Animation.PlayMode.LOOP, Gdx.files.internal("throbber.gif").read());
        Animation<TextureRegion> downAnimation = GifDecoder.loadGIFAnimation(Animation.PlayMode.LOOP, Gdx.files.internal("throbber.gif").read());
        // Instanciate an AnimatedButton, providing animations for up and down states
        Button button = new AnimatedButton(upAnimation, downAnimation);

        button.setPosition(100, 100);
        button.setSize(32, 32);

        // Here the click listener is added by passing an anonymous type
        button.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                super.clicked(event, x, y);

                //Add click handler here!

            }
        });

        // Add the button to the Stage
        stage.addActor(button);

        // And set the processor of input to be that stage
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void render () {
        // Make sure to update the state of the stage
        stage.act(Gdx.graphics.getDeltaTime());
        Gdx.gl.glClearColor(1, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // Draw the state of the stage
        stage.draw();
    }

    @Override
    public void dispose () {
    }
}

```
> 3 votes

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


# Question
Title: If condition true, but code is not executed in Unity
I have a script which triggers a movement when a rotation is completed. The script casts the Euler angle of a transform to an `int`. If it is `true`, the condition is executed. For some weird reason, the code in the `if` condition does not execute, even if the condition is `true`. I have confirmed the condition is `true` through both my compiler and the debug log.

---

Here is my code:

```
if(rotationInitiate)
{
    transform.eulerAngles = Vector3.Slerp(transform.eulerAngles,
        new Vector3(0, 0, angleOfRotation), Time.deltaTime * speedOfRotation);

    Debug.Log(transform.eulerAngles.z);

    if((int)transform.eulerAngles.z == 180)
    {
        Debug.Log("Hurray we have successfully executed the if statement");

        // More rotation stuff
    }
}

```

As you can see by my log, the angle returns an exact value of 180, but does not enter the `if` statement to perform the second log output:

---

Why might my `if` statement not be executing?

# Answer
> 2 votes
The problem is that `Debug.Log(transform.eulerAngles.z);` printing `180` does not mean that `z` has the value `180`. It means it has a floating point value very close to `180`, but that could be for instance `179.999969482421875`.

This means that the `if((int)transform.eulerAngles.z == 180)` test will not work, because casting `179.999969482421875` to `int` yields `179`, not `180`.

A possible solution is to round the value: `if (Math.Round(transform.eulerAngles.z) == 180.0)`.

# Answer
> 1 votes
I copy pasted your code into a coroutine:

```
private IEnumerator TestCoroutine()
{
    GameObject newGameObject = new GameObject();

    while (true)
    {
        newGameObject.transform.eulerAngles = Vector3.Slerp(
            newGameObject.transform.eulerAngles,
            new Vector3(0, 0, 180), Time.deltaTime * 10);

        Debug.Log(newGameObject.transform.eulerAngles.z);

        if ((int)newGameObject.transform.eulerAngles.z == 180)
        {
            Debug.Log("Hurray we have successfully executed the if statement");
        }

        yield return null;
    }
}

```

I ran it, and it worked:

# Answer
> 0 votes
Since you are using a slerp and casting to int, your rotation doesn't actually ever hit 180, since casting cuts off anything after the comma (179.999999999999.. =\> 179). The Debug.Log rounds instead, so if you want the behavior to be the same try Mathf.Round instead of the int cast.

It is better to use the solution Wondra posted in the comment above though, this is just to make it clear why it broke before.

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


# Question
Title: Generate random point inside Perlin noise?
I’m working on terrain generation for a game of mine and has run into a slight problem. The terrain itself within the game procedurally generates as your character moves around. This means that all the world generation needs to somehow be based off of the position a certain tile—or region (chunk)—has in the world.

The world generation is rock solid so far and looks quite gorgeous! But I require one more component to make it complete—I need to somehow retrieve a random point within a piece of Perlin noise.

Let’s assume we had something like this:

```
int scale = 100;
float noise = perlinNoise.noise3(x / scale, y / scale, z / scale)

if(noise > .2f)
    setPixel(x, y, 0xffffff);

```

We’re drawing the result to the screen in form of pixels to try and see what happens. This way, we achieve regularly spaced out areas of noise. Now, what I would like to do is randomly generate one point located somewhere within a chunk of noise following the above “schematic”.

The above might look something along the lines of this:

```
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxoooxxxxx
xxxxoooooxxxx
xxxxxoopooxxx
xxxooooooxxxx
xxxxxoooxxxxx
xxxxxxxxxxxxx

```

Where the *x*’s are what is not affected by the perlin noise in the above code example and *o*’s are affected—the *o*’s are plotted out on the screen by it—they’re the white pixels in the above example.

The little *p* as opposed to from the *o*’s and *x*’s, is the random point I’d like to have randomized inside every chunk of randomized *Perlin noise*, without having to pre-generate the world.

Is there a way in which this can be achieved? I’ve wrapped my mind inside out thinking of potential solutions—I’ve searched the web, but as though in vain. There appears to be nothing written on the subject.

# Answer
> 1 votes
Using traditional Perlin noise, you cannot know in advance what values a 'section' will have without actually generating - underneath it all, you're using a PRNG & the very nature of a PRNG is you cannot predict future values (short of pre-generating the sequence or doing some serious math on the generating algorithm).

The two possible alternatives:

1) If you are building your noise with layers of octaves, traditionally, the first couple of octaves have the biggest influence on the outcome. thus, it might be possible to find candidate locations without fully pre-generating a region.

2) Decide in advance where you want the random 'p' locations to be & design your noise function to give you values to accommodate them.

# Answer
> 0 votes
Keep a list of the positions for `o`s for each chunk. When the chunk done with the Perlin noise generation, select an `o` randomly from the list to be replaced by a `p`.

---
Tags: java, libgdx, procedural-generation, perlin-noise
---


# Question
Title: 'NullReferenceException: Object reference not set to an instance of an object' when similar code works
I am getting an error when accessing a function from `VirtualRotationStick`, despite the fact that a similar `VirtualJoystick` works fine.

> NullReferenceException: Object reference not set to an instance of an object PlayerScript.FixedUpdate () (at Assets/Code/PlayerScript.cs:19)

---

Here is my `PlayerScript`:

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

public class PlayerScript : MonoBehaviour
{
    public float moveSpeed = 5.0f;
    public VirtualJoyStick DirJoyStick;
    public VirtualRotationStick RotJoyStick;

    void FixedUpdate ()
    {
        Vector3 Dir = new Vector3(DirJoyStick.Horz()/10,0,DirJoyStick.Vert()/10);
        float rot = RotJoyStick.Rotation ();
        this.gameObject.transform.position = this.gameObject.transform.position + Dir;
    }
}

```

# Answer
When you have a public variable in Unity, it makes the variable visible to the Inpector, but it does not give it a valid value. Object types will be initialized to `null`. You have to give it a value by dragging an appropriate component into that slot in the Inspector or you have to initialize the variable yourself (i.e. this.RotJoyStick = new VirtualRotationStick())
> 1 votes

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


# Question
Title: GAMEMAKER : Assign variable value as variable key
I tried something without success, so I ask myself if it's possible to perform this with Gamemaker.

```
array[0] = "example";
global.array[0] = 3;

```

Explicitly I want

```
array[0] = "example";
global.example = 3;

```

So;

* Is it possible to convert a value as a variable name ?
* Is it possible to convert this variable as a global ?

Thanks in advance.

# Answer
> 0 votes
No, you can't do something like that. If you write:

```
array[0] = "example";
global.example = 3;

```

you are declaring `array[0]` for the current instance equal to the string `"example"` (without quotes), and the variable `example` of the special object `global` equal to `3`.

I guess you are trying to use the `"example"` string as a key, so I suggest you to take a look to DS Maps. Maps are data structures in which you can look for a "key", which lets you to edit the related value. Think of a dictionary: you look for a word, and find out its meaning; well, a DS Map lets you to store "keys" (numbers, strings, any value you would assign to a simple variable) within it, and associate a value to such key. You can access the value bonded to a particular key by using the `ds_map_find_value()` function.

---
Tags: game-maker
---


# Question
Title: Why does applying force to a game object apply force to children, as well?
I have a script on my player to move. I do not have root motion applied because, root motion does not work perfectly so I'm manually adding velocity to the player.

The player is holding a ball and the ball is a child of the player. However, when I apply force to the player it seems to apply force to the ball so he stops holding it and it is just floating around instead.

My player and my ball both have rigidBodies and I'm applying force like this.

```
    var velocityX = horizontal * HorizontalSpeed * Time.deltaTime;
    var velocityZ = vertical * VerticalSpeed * Time.deltaTime;

    rigidBody.velocity = new Vector3(velocityX, 0f, velocityZ);

```

I know as a hack I can apply a late update to the ball, but I'd rather understand what is going on.

Can anyone help me figure this out?

# Answer
When we parent a game object to another game object, we make the `Transform` values of the *child* object local to the `Transform` values of the *parent* object.

This is very useful, *if used correctly*. In the above situation, we have a character holding a ball. While we move the character *with the assumption of still holding on to the ball*, we can simply move the character. As it is *local* to the character, the ball moves with it. However, this does *not* work when we parent separate objects containing `Rigidbody` components. A `Rigidbody` interprets every child object as part of that `Rigidbody`, where a child `Rigidbody` can break this assumption, and lead to odd behaviour.

As detailed at Unity Answers, you should use joints to attach `Rigidbody` game objects.
> 4 votes

---
Tags: unity, physics, rigidbody
---


# Question
Title: Is the 'partially checked' build sufficient to run the debug version of Direct3D 9?
To run Direct3D 9 in debug, it is necessary to "install a 'checked' version of the OS".

The checked version of Windows comes in both full and partial flavors. It seems that the partial version is much less obtrusive to install than the full version. But, will that be sufficient to run Direct3D 9 in debug mode?

# Answer
A partial checked build only has the kernel and HAL built 'checked', so you would have a retail (non-checked) version of user-mode `D3D9.DLL`.

To get debugging support, you need a checked version of `D3D9.DLL` which means a 'Full checked' build.

Note that the only real debugging tool for Direct3D 9, PIX for Windows, is not compatible with Windows 8.x or Windows 10.

> Of course the real question is why are you still developing/debugging legacy Direct3D 9 apps?
> 0 votes

---
Tags: directx9, debugging
---


# Question
Title: Null instance on manager class extending from singleton class
I have four classes:

* **class A**, which is abstract and partial extending from singleton **class C**.
* **class A1**, which is partial and extending from **class A** .
* **class B**, extending from **class A**.
* **class C**, a singleton which has code to throw an exception if the instance is `null`, and otherwise uses `DoNotDestroyOnLoad()`.

In scene view, I add **class B** to the scene. It works, but throws a null instance exception for **class A**, as it's instance is not present in scene. I think this is because **class A** extends from a singleton class, and it has ability to throw exceptions when the instance is null. I can not add the **class A** to the scene because it is abstract.

What can I do to in order to add the **class A** component to the scene, or otherwise not to get this error?

# Answer
Yes I had to do exception handling on every point throwing null exception. Done.!!
> -1 votes

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