# Question
Title: let me know how to save an integer for game stage level?
I am trying to make a game which there are many stages. For example, If users are done stage 3 of the game, and then turn off the game, they can play the game at stage 3 anytimes.

simply, I tried to make this logic, so when you press space bar, the level goes up. However, after turning off and on, lev will start at 0. I guess when program are ruining every single times, the lev is initialized 0.

I tried to use preference.

please let me know solutions..

AppPreferences.java

```
public class AppPreferences {

   private static final String PREFS_NAME = "Adventure";
   private static final String PREF_LEVEL = "Level";
   private Preferences preferences;

   protected Preferences getPrefs(){
    if (preferences == null)
        preferences = Gdx.app.getPreferences(PREFS_NAME);
       return preferences;
}

public void setPrefLevel(int level){
    getPrefs().putInteger(PREF_LEVEL,level);
    getPrefs().flush();
}

public int getPrefLevel(){
    return getPrefs().getInteger(PREF_LEVEL);
}

}

```

PlayScreen.java

```
public class PlayScreen implements Screen {
 int lev=0;

 public void render(float delta) {

     if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){

        advanture.getPreferences().setPrefLevel(i);
        System.out.println(advanture.getPreferences().getPrefLevel()+"!!!!!!!!!");
        i++;
   }

 }

```

# Answer
You don't seem to be assigning the `lev` variable anywhere. In the top of your `show` method you can put something like this:

```
@Override
public void show() {
    lev = advanture.getPreferences().getPrefLevel();
    // do other stuff like load level from number
}

```

This should make the level start at the loaded level. Your code would then look something like this:

```
public class PlayScreen implements Screen {
    int lev = 0;

    @Override
    public void show() {
        lev = advanture.getPreferences().getPrefLevel();
        // do other stuff like load level from number
    }

    public void render(float delta) {
        if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
            lev++; // Increase level by 1
            advanture.getPreferences().setPrefLevel(lev); // Save level
            System.out.println(lev+"!!!!!!!!!"); // Print level
        }
    }
}

```
> 1 votes

# Answer
You need to look into persistent storage e.g. a database or similar. Since your level variable is 0, every time you instantiate your program the level will be 0. You should read the level from persistent storage for the desired result.

If you deploy for Android, you could read or write to a file or an embedded database. If you target desktop PC:s you could use a database of any kind. Just store the level for the game in the database and then read it when the game starts again.
> 0 votes

---
Tags: libgdx, box2d
---


title: Why aren't VAOs/VBOs needed here?

text:
# Question
Title: Why aren't VAOs/VBOs needed here?
I have this code where I can draw as many rectangles I want without no VAO/VBOs warm up.

```
// Shader sources
const GLchar* vs = R"glsl(
    #version 330 core

    vec2[4] position = vec2[4] (
        vec2(0.5, 0.5),   vec2(0.5, -0.5),
        vec2(-0.5, -0.5), vec2(-0.5, 0.5)
    );

    void main()
    {
        gl_Position = vec4(position[gl_VertexID] - 0.5, 0.0, 1.0);
    }
)glsl";

const GLchar* fs = R"glsl(
    #version 330 core
    out vec4 outColor;

    void main()
    {
        const vec3 color = vec3(1.0, 0.5, 0.2);
        outColor = vec4(color, 1.0);
    }
)glsl";

void useShader(const char *vs, const char *fs) {
    // Create and compile the vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vs, NULL);
    glCompileShader(vertexShader);

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fs, NULL);
    glCompileShader(fragmentShader);

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);
}

int main()
{
    //..window, gl init..
    GLuint elements[6] = {  0, 1, 3,  1, 2, 3 };
    while (true)
    {
        // Clear the screen to black
        glClearColor(0.4f, 0.4f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw a rectangle from the 2 triangles using 6 indices
        useShader(vs, fs);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, elements);

        // Swap buffers
        window.display();
    }
    // cleanup
    return 0;
}

```

Why aren't any VAOs/VBOs needed. I've understood that VBOs are basically buffers that hold different kind of data that will be sent to the GPU. Basically, are vao/vbo usefull only for loading data into the shaders, since I'm gonna need constant data, wouldn't be better to premake the shaders and use them whenever I need them, or do I need to do it the VAO way.

Also when I'm looking to change the layout origin to upper left it logs me that it needs input data oO..

# Answer
> 0 votes
Aside from sourcing vertices via gl\_VertexId, in a more general sense VAOs/VBOs are not needed in this case because:

* The *shaders* may be declared as `#version 330 core`, but...
* ...the OpenGL C/C++ code is using the compatibility profile.

In the compatibility profile VAOs and VBOs are not needed because the compatibility profile provides *other ways* of drawing, including:

* Using VBOs but without VAOs,
* Using arrays sourced from client memory,
* Using the old glBegin/glEnd "immediate mode",
* Some combination of the above.

It's only in core profiles that the requirement to use VAOs/VBOs was introduced.

---

How can we be certain that this is compatibility profile OpenGL?

Because of this:

```
GLuint elements[6] = {  0, 1, 3,  1, 2, 3 };

```

And this:

```
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, elements);

```

If it were core profile it would be illegal for glDrawElements to source it's data from a client memory array, and drawing would fail. A buffer object would have to be created, and a VAO would be necessary to contain the ELEMENT\_ARRAY\_BUFFER binding.

---

To summarize:

**VAOs/VBOs are not mandatory in compatibility profile OpenGL**

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


# Question
Title: In Gamemaker Studio 2 how can I find out in code whether the platform is HTML5 or not?
I want to be able to run or not run code depending on which platform I am building for. Some code should only run for the HTML5 platform. How can I find out whether the platform being run is HTML5 inside my gamemaker events?

# Answer
You can check what browser the game is currently being run in with the `os_browser` constant. If the game is not being run in a browser the constant will be `browser_not_a_browser`. So to check if it is being run in a browser simply do:

```
if os_browser != browser_not_a_browser {
     // Being run in a browser
}

```
> 4 votes

---
Tags: game-maker
---


# Question
Title: App icon on phone looks squished in Unity
I am working on a 2D platformer. And I am alomost finished!! I am trying to work on adding the app icon. The icon that you would see on your phone. I imported the picture and added it to player settings. But when I put my game on my phone the icon looks squished. These are the settings that I imported it on

Texture Type (sprite 2D and UI)

sprite mode Single

Filter mode Blinear (not pixel art)

Here is a link to a screen shot on my phone of the icon

https://www.dropbox.com/s/jbgciscda7nykjd/app%20on%20phone.png?dl=0

Ok I am getting closer to an solution now. My first problem was that the image was not square as staed below. But now the image is smaller compared to the rest of the app icons. the resolution of teh image now is 2000X2000

Here is a screenshot of what it looks like now

https://www.dropbox.com/s/t45vylzpi3chnsf/App\_Icon\_2.png?dl=0

# Answer
> 1 votes
The icon needs to be square. Add some empty space on the top and bottom to pad it out to 2000x2000, or trim some empty space off the sides to make it 1537x1537 (or somewhere in between)

Actually it looks like there’s a fair bit of blank space in the icon already. You may want to crop all the white space out first, then add padding as necessary.

---
Tags: unity
---


# Question
Title: Rotation of a cylinder between to spheres in R3
I want to connect two spheres with the coordinates *\[ax, ay, az\] and \[bx, by, bz\]* with an cylinder which is placed in between the spheres an rotated. For the placement I calculate the center of the two spheres and place the cylinder there. The cylinder spawns parallel to the Z-Axis. Since I want to connect the spheres, I thought I first need to rotate either on the Y- or X-Axis and then on the Z-Axis.

I learned that combination of rotations is easiest with quaternions since you only have to multiply them, so I decided to use quaternions. So I get the angle of the first rotation(on Y- or X-Axis) and get the quaternion of this rotation, and then I get the angle of the second rotation on the Z-Axis and the quaternion of this rotation. Then I multiply them in order to get the combined rotation, and use the resulting quaternion on the cylinder.

This seems to work, but here is the problem: the more I get to the +-45° angle between the two spheres, the more I get something which looks like an offset to me. Furthermore, the greater the distance between the points is, the more offset I get. I checked the two quaternions which are multiplied, and both are indeed a +-45° rotation about the correct axis (in this example -45° in radians)

Since this is very hard to explain with words, here are some screenshots:

This is the 45° rotation:

This is with more distant points:

The red dot on the ground marks the x-axis, the blue dot marks the y-axis.The simulation was started without gravity.

So my question is, why is this happening? And if anyone knows why, how can I fix it? Since I am new to game development and orientation in R3, this could be something obvious to an experienced developer.

I am using c++ with the Open Dynamics Engine and the drawstuff library for my program.

**EDIT:** This is the resulting quaternion

**EDIT2:** I add the calculation of the angles. This whole thing is in an for-loop.

```
        /* lengths[i][j] is the distance between two points, taking the coordinates of point 1 minus the coordinates of point 0

        For example:
        lenghts[0][0] is the distance of the x-coordinates of the first two points which should be connected
        lengths[0][1] is the distance of the y-coordinates of the first two points which should be connected
        lengths[0][2] is the distance of the z-coordinates of the first two points which should be connected
        */
        angle = -pioff + atan(lengths[i][2] / lengths[i][1]); // pioff is M_PI_2 = pi/2 = 1.5708
        if(isnan(angle))
        {
            angle = 0.0;
        }
        dQFromAxisAndAngle(Q1, 1, 0, 0, angle); // get quaternion1 of angle
        cout << "   quat Q1: " << Q1[0] << " + i" << Q1[1] << " + j"  << Q1[2] << " + k"  << Q1[3] << endl;
        cout << "   angle Q1: " << angle << endl;
        cout << "   x axis: angle = -" << pioff << " + atan(" << lengths[i][2] << " / " << lengths[i][1] << ") = " << angle << endl;
        angle = -atan(lengths[i][0] / lengths[i][1]);
        if(isnan(angle))
        {
            angle = 0.0;
        }
        dQFromAxisAndAngle(Q2, 0, 0, 1, angle); // get quaternion2 of angle
        cout << "   quat Q2: " << Q2[0] << " + i" << Q2[1] << " + j"  << Q2[2] << " + k"  << Q2[3] << endl;
        cout << "   angle Q2: " << angle << endl;
        printf("   connect xyz1(%f/%f/%f) and xyz2(%f/%f/%f)\n", xyz1[i][0] + c[0], xyz1[i][1] + c[1], xyz1[i][2] + c[2], xyz2[i][0] + c[0], xyz2[i][1] + c[1], xyz2[i][2] + c[2]);
        cout << "   z axis: angle = - atan(" << lengths[i][1] << " / " << lengths[i][0] << ") = " << angle << endl;

```

This is the output I get. Lenght\[\]\[\] output are the elements of lengths\[i\]\[j\]

# Answer
For something like this, I'd be tempted to use a rotation matrix, if that's an option.

```
// Form a unit vector pointing along the line between the spheres.
zDirection = normalize(sphere2Center - sphere1Center)

// Expand this into an orthonormal basis
// (3 mutually perpendicular unit vectors)
if(abs(dot(zDirection, (0, 1, 0)) < 1)
    xDirection = normalize(cross((0, 1, 0), zDirection))
else
    xDirection = (1, 0, 0)

yDirection = cross(zDirection, xDirection)

// These vectors become the columns of your rotation matrix
// (or rows, if you multiply with the vector on the left)
rotationMatrix.columns[0] = xDirection
rotationMatrix.columns[1] = yDirection
rotationMatrix.columns[2] = zDirection

```

If you prefer to work with quaternions, you can convert these basis vectors into a quaternion format before proceeding, rather than using the rotation matrix directly.
> 0 votes

---
Tags: c++, 3d, rotation, quaternion, open-dynamics-engine
---


# Question
Title: How can I control the volume of the music and the sound effects seperately with two sliders?
In the Hierarchy i have one Main Camera with Audio Listener. In the Hierarchy I have AudioPanel and two child Sliders.

And the AudioManager script that attached to the AudioPanel:

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

[System.Serializable]

public class AudioManager : MonoBehaviour
{

    public Slider musicVolume;
    public Slider effectsVolume;

    private void SetMusicListenerVolume()
    {
        AudioListener.volume = musicVolume.value;
    }

    public void ApplyMusicSettings()
    {
        SetMusicListenerVolume();
    }

    private void SetEffectsListenerVolume()
    {
        AudioListener.volume = effectsVolume.value;
    }

    public void ApplyEffectsSettings()
    {
        SetEffectsListenerVolume();
    }
}

```

Now in the Hierarchy I have some Audio Sources components for the sound effects and I want to control them with the Slider (1).

And to control the music sound with the Slider. The music sound have his own Audio Source.

The problem is that the AudioListener in the script control all the Audio Sources. Music and Effects. Or maybe only the Music ? U'm not sure. But when i change both sliders when the game is running it's changing the music volume.

My question/s is how to control with Slider only the volume of the music and with Slider (1) the effects volume ?

And how can i get all the effects audio sources in the script and control the volume of them using the Slider (1) ?

The audio source component of the music is attached to GameObject name Sound. All the other audio sources components are effects and are in some places in the Hierarchy.

# Answer
> 7 votes
You will need to use an audio mixer.

An audio mixer lets audio sources specify which group they should output to, so you should create two groups, one for sounds effects, and one for music. You need to then expose the attenuation (volume) parameter of each group to code. Then, the music audio source can specify that it should play through the music group, and all the others play through the sound effects group.

Then, in code, you need to get a reference to the audio mixer (for example by adding a reference in a Monobehaviour and assigning it in the inspector) and set the volume of individual groups using the names of the parameters when they were exposed from the inspector.

Note that the range of attenuation is -80 (muted) to 0 (full volume). And it’s not linear, so the slider won’t control the volume smoothly if you just map the volume directly from the slider to attenuation value. You will need to do a conversion using `mixer.SetFloat(parameterName, Mathf.Log10(sliderValue) * 20);` to get it nice and smooth (assuming sliderValue ranges from 0 to 1). See here for more details.

Note: audio sources created in the editor should be assigned to groups in the inspector. To assign an audio source created at runtime to the correct group via code, use `AudioSource.outputAudioMixerGroup`

# Answer
> 0 votes
If all you want is to control the music and sfx volumes through separate sliders, then your AudioManager just needs a few simple changes. :)

```
public class AudioManager : MonoBehaviour
{

    public Slider musicVolume;
    public Slider effectsVolume;

    // Make sure to plug these in in the inspector.
    public AudioSource musicPlayer;
    public AudioSource effectsPlayer;

    private void Start()
    {
        /*
        All sliders have an onValueChanged event that executes every time the sliders' values are
        changed (meaning whenever their knobs are moved).

        By hooking them up to the appropriate volume-changing functions (which I added float
        parameters to, out of necessity), the volumes of the audiosources change with them.
        */

        musicVolume.onValueChanged.AddListener(SetMusicListenerVolume);
        effectsVolume.onValueChanged.AddListener(SetEffectsListenerVolume);

    }

    private void SetMusicListenerVolume(float volume)
    {
        musicPlayer.volume = volume;
    }

    private void SetEffectsListenerVolume(float volume)
    {
        effectsPlayer.volume = volume;
    }

    public void ApplyMusicSettings()
    {
        // The volume updates itself through the slider's events, so no need to update
        // the volume in this function.
        //SetMusicListenerVolume();
    }

    public void ApplyEffectsSettings()
    {
        // Or this one.
        //SetEffectsListenerVolume();
    }
}

```

The comments explain everything.

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


# Question
Title: Smoothly moving an orbiting object back into orbit
I have an object that orbits the player's sprite with code that looks like this:

```
x = player.x + sin(_float) * _radius;
y = player.y + cos(_float) * _radius;
_float += 0.01;

```

An event can trigger the object to fly away from the player to chase a target. After it hits the target, I would like the object to glide back toward the player and smoothly return to an orbiting path around the player.

Everything I've tried thus far just ends up making it snap to a position abruptly or completely fly away, never to return again.

EDIT: I ended up with a solution that sets the objects velocity to the sin/cos orbit instead of directly setting the x and y coordinates. Thanks for the ideas!

# Answer
Let's take a look at the problem from a distance. We have some requirements for this object:

* At any time the object can be in one of a number of distinct states.
* The current state can change at any time.
* For each state we can determine a target position at any time. This is where we would like the object to go ASAP when in this state.
* The object should move smoothly at all times. This may mean its speed is capped at some limit, or the magnitude of its acceleration is capped at some limit, or some other definition of smoothness.

Here are two basic strategies we could take:

### Continous Simulation

We write an function that takes the object's current position, the current target position, and the elapsed time since the simulation was last updated, and returns the object's new position. Some simple implementations:

* An infinite-impulse-response low-pass filter. The object moves a fixed fraction of the distance to the target every time it is updated. This only works well if the simulation timestep is fixed, of course, and you'll probably need to manually limit the object's top speed.
* Use a physics simulation. Apply a force in the direction of the target position and a damping force counter to the current velocity (i.e. friction) to prevent overshoot and oscillation. Calculate the resulting acceleration based on the net force and mass of the object, and integrate it to get the change in velocity. Then integrate the new velocity to get the new position. Use your physics engine if you have one. If the object is a missile or some other entity which maneuvers using thrust, this will probably give the most realistic result.

More complicated implementations might use the current/target velocity as well.

### Transition Smoothing

When the current state changes, we keep track of the previous state and the time when the state change occurred. We write a function that takes the current target positions for the current and previous states, and the elapsed time since the previous state transition, and returns the object's new position. We may also want to use other information, like the object's current position/velocity or what specific states anchor the transition (not just the calculated target position), and we may want to return more information, like whether or not the transition is complete. This strategy requires a few more assumptions about the problem:

* The target positions for each state of the object satisfy our requirements for smooth movement
* After changing to a new state, the object's state won't change again until the transition is complete.

The smoothing function would typically just interpolate between the previous and current target positions over a fixed timespan, using your favorite interpolation method, but you could come up with a more exotic implementation as well.
> 3 votes

---
Tags: 2d, mathematics, rotation, orbit
---


# Question
Title: Mixing threads and coroutines in Unity3D Mobile
I had a coroutine in Unity3D that downloaded a zip from a server, extracted it to the persistent data path, and loaded its contents into memory. The flow looked something like this:

```
IEnumerator LongCoroutine()
{
    yield return StartCoroutine(DownloadZip());
    ExtractZip();
    yield return StartCoroutine(LoadZipContent());
}

```

But the `ExtractZip()` method (which uses the DotNetZip library), is synchronous, takes too long, and leaves me no place to yield during the process.

This resulted in the application being killed (on mobile devices) whenever I tried to extract a large zip, which I assume is due to the main thread becoming unresponsive for too long.

**Is this something that mobile OS are known to do (kill the app if a frame takes too long)?**

So, I assumed that extracting the zip on a separate thread might solve the problem, and it seems to have worked. I created this class:

```
public class ThreadedAction
{
    public ThreadedAction(Action action)
    {
        var thread = new Thread(() => {
            if(action != null)
                action();
            _isDone = true;
        });
        thread.Start();
    }

    public IEnumerator WaitForComplete()
    {
        while (!_isDone)
            yield return null;
    }

    private bool _isDone = false;
}

```

And I use it like this:

```
IEnumerator LongCoroutine()
{
    yield return StartCoroutine(DownloadZip());
    var extractAction = new ThreadedAction(ExtractZip);
    yield return StartCoroutine(extractAction.WaitForComplete());
    yield return StartCoroutine(LoadZipContent());
}

```

But I'm still not sure if this is the best way to implement it, or if I need to lock `_isDone` (not too used to multithreading).

**Can something go wrong with this / am I missing something?**

# Answer
This is a really elegant solution for wrapping up multithreaded tasks in a coroutine, well done :)

Mixing coroutines and threads is perfectly safe, provided you correctly lock access to resources shared between your main thread (which the coroutine executes on) and the worker thread(s) you create. You shouldn't need to lock \_isDone in any way, since it's only ever written to by the worker thread and there's no intermediate state that could cause the main thread to misbehave.

Where you do need to look out for potential problems, is if any resources are written to by ExtractZip and are either

1. simultaneously written to by a function being called from your main thread or
2. being read by a function on the main thread and expected to be in a safe state before ExtractZip completes.

In this particular case, my worry would be that if you don't check that you're not trying to download the same file to the same location twice, you could have two threads simultaneously running ExtractZip that interfere with one another.
> 4 votes

# Answer
There is a free solution for this on the Asset Store:

Thread Ninja

With it you can switch between main thread & background thread easily, which likes:

```
void Awake() {
    this.StartCoroutineAsync(AsyncCouroutine());
}

IEnumerator AsyncCoroutine() {
    // won't block
    Thread.Sleep(10000);

    yield return Ninja.JumpToUnity;

    // we're now on Unity's main thread
    var time = Time.time;

    yield return Ninja.JumpBack;

    // now on background thread again
    // ...

```
> 2 votes

# Answer
Well, I'm not a major expert either, but I think in your 2nd example, the WaitForComplete() function will still block the calling thread until the ThreadedAction thread completes. What you can do is pass a callback function to your zip processing Thread, and have it call that function when it's done. That way your main thread starts the zip thread and then continues on doing his stuff (updating GUI, what have you), and then the call back function will set something in the main thread when it's done (like boolean zipDone=true), and at this point the main thread can react to that (display "Zip extracted" in the GUI etc).
> -1 votes

# Answer
You don't need to lock \_isDone, but it does need to be marked volatile.
> -2 votes

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


title: Table background not showing up

text:
# Question
Title: Table background not showing up
I am using Libgdx's Scene2D API to build my UI and everything has been working as expected until now. I created a `Skin` and a `TextureAtlas` and linked them as so:

```
Skin skin = new Skin();
TextureAtlas uiElements1 = new TextureAtlas("skins/uielements1.txt");
skin.addRegions(uiElements1);
skin.load(Gdx.files.internal("skins/uiskin.json"));

```

And then I tried to create a `Table`:

```
Table table = new Table(skin);
table.setWidth(stage.getWidth());
table.align(Align.center|Align.top);
table.setPosition(0, Gdx.graphics.getHeight());
table.padTop(30);
table.setBackground("grey_button02");

```

Finally, I added a `Label` to the `Table`:

```
Label gameTitle = new Label("Nameless Project", skin, "title");
table.add(gameTitle).padBottom(10).row();

```

Once I added the `Table` to my `Stage`, only the elements in it would show up and not the background image. I tried using `background(String s)`, `setBackground(String s)`, `background(Drawable d)`, and `setBackground(Drawable d)`. None of those seemed to work for me.

I also tried calling `pack()` and `setFillParent(true)` but both of those made my table disappear. I have gone through just about every Google result and I can't find anyone else with my issue.

Here is my `uiskin.json` file

```
{
  com.badlogic.gdx.graphics.g2d.BitmapFont: { default-font: { file: fonts/FutureThin.fnt } },
  com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: {
   default: { down: blue_button03, up: blue_button04, font: default-font },
  },
  com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle: {
    default:  {
      titleFont: default-font
     }
   },
   com.badlogic.gdx.scenes.scene2d.ui.Label$LabelStyle: {
    title: {
        font: default-font
     }
   }
}

```

And the entire class rendering the stage:

```
public class MainMenu implements Screen {

    GameClass myGame;

    Stage stage;
    Skin skin;

    Table table;
    TextButton singlePlayer;
    TextButton multiPlayer;
    Label gameTitle;

    public MainMenu(GameClass g) {
        myGame = g;

        // Create Skin, load texture Atlas, load skin
        skin = new Skin();
        TextureAtlas uiElements1 = new TextureAtlas("skins/uielements1.txt");
        skin.addRegions(uiElements1);
        skin.load(Gdx.files.internal("skins/uiskin.json"));

        // Create stage
        stage = new Stage(new ScreenViewport());

        // Create Table
        table = new Table(skin);
        table.setWidth(stage.getWidth());
        table.align(Align.center|Align.top);
        table.setPosition(0, Gdx.graphics.getHeight());
        table.padTop(30);
        table.setBackground("grey_button02");

        // Game Title
        gameTitle = new Label("Nameless Project", skin, "title");
        table.add(gameTitle).padBottom(30).row();

        // Single Player button
        singlePlayer = new TextButton("Single Player", skin, "default");
        singlePlayer.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent e, float x, float y) {
                myGame.setScreen(new WorldTesting(myGame));
            }
        });
        table.add(singlePlayer).width(300).padBottom(30).row();

        // Multiplayer Button
        multiPlayer = new TextButton("Multiplayer", skin, "default");
        multiPlayer.setWidth(350);
        multiPlayer.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent e, float x, float y) {
                // Change Scenes
            }
        });
        table.add(multiPlayer).width(300).padBottom(30).row();

        stage.addActor(table);
        Gdx.input.setInputProcessor(stage);
    }

    public void show() {

    }

    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    public void hide(){

    }
    public void resize(int x, int y) {

    }
    public void pause() {

    }
    public void resume() {

    }
    public void dispose() {

    }

}

```

# Answer
> 1 votes
I've had this exact problem before, so I'll try to remember how I solved it.

I recommend turning on the `stage.debugAll()` while you develop: It is a god send at helping you figure out when things aren't doing what they are supposed to be doing.

You say all of the elements inside the table show up fine. Are they properly aligned as well? If not then your table is not positioned correctly because it is not sized correctly.

Try and put a `stage.getViewport().update(x,y);` in the `resize(int width,int height);` method. Since you are using `screenviewport` your viewport size is not automatically set.

One more tip is instead of just using a drawable for a table background I would try and make use of a ninepatch. It will get rid of any weird stretching in your UI elements (especially tables which can be much bigger than most elements).

# Answer
> 0 votes
Edit because my previous answer was not the correct one:

First guess: the region is too small, or it can't process the image. I would debug the draw method and make sure the table actually has a background in the draw method. If no background is there, the method just draws nothing.

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


# Question
Title: Porting exiting engine to PBR (opengl/glsl)
I'm currently trying to port an existing engine to PBR. The engine was designed with some PBR features like IBL, energy conservation however it still uses the gloss map + specular map.

My goal is to port it to metalness + roughness to make artist's job easier, however I'm facing some issues.

* 1) The original engine dev left the project
* 2) While I have glsl/programming knowledge I'm more on the artistic side

> Before the engine compute the diffuse and specular coefficient with those function:
>
> **While the input var is named roughness, it's in fact the gloss map from the 3D model**
>
> ```
> // Blinn Phong with emulated fresnel factor
> vec3 SpecularBRDF(vec3 normal, vec3 eyedir, vec3 lightdir, vec3 color, float roughness)
> {
>     float exponentroughness = exp2(10. * roughness + 1.);
>     // Half Light View direction
>     vec3 H = normalize(eyedir + lightdir);
>     float NdotH = clamp(dot(normal, H), 0., 1.);
>     float normalisationFactor = (exponentroughness + 2.) / 8.;
>     vec3 FresnelSchlick = color + (1.0f - color) * pow(1.0f - clamp(dot(eyedir, H), 0., 1.), 5.);
>     return max(pow(NdotH, exponentroughness) * FresnelSchlick * normalisationFactor, vec3(0.));
> }
> // Lambert model
> vec3 DiffuseBRDF(vec3 normal, vec3 eyedir, vec3 lightdir, vec3 color, float roughness)
> {
>     return color;
> }
>
> ```
>
> And the main function
>
> ```
> void main() {
>     vec2 uv = gl_FragCoord.xy / u_screen;
>     float z = texture(dtex, uv).x;
>     vec4 xpos = getPosFromUVDepth(vec3(uv, z), u_inverse_projection_matrix);
>
>     vec3 norm = normalize(DecodeNormal(2. * texture(ntex, uv).xy - 1.));
>     float roughness =texture(ntex, uv).z;
>     vec3 eyedir = -normalize(xpos.xyz);
>
>     vec3 Lightdir = SunMRP(norm, eyedir);
>     float NdotL = clamp(dot(norm, Lightdir), 0., 1.);
>
>     vec3 Specular = SpecularBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);
>     vec3 Diffuse = DiffuseBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);
>
>     // Shadows
>     float factor;
>     if (xpos.z < split0)
>         factor = getShadowFactor(xpos.xyz, 0);
>     else if (xpos.z < split1)
>         factor = getShadowFactor(xpos.xyz, 1);
>     else if (xpos.z < split2)
>         factor = getShadowFactor(xpos.xyz, 2);
>     else if (xpos.z < splitmax)
>         factor = getShadowFactor(xpos.xyz, 3);
>     else
>         factor = 1.;
>
>     Diff = vec4(factor * NdotL * Diffuse * sun_color, 1.);
>     Spec = vec4(factor * NdotL * Specular * sun_color, 1.);
> }
>
> ```

I'm attempting to implement the function described here http://github.khronos.org/glTF-WebGL-PBR/ Currently I'm focused on implementing roughness. Metalness will come later

```
#define saturate(value) clamp(value, 0.0f, 1.0f);
#define PI 3.1415926f
#define EPSILON 10e-5f

// Attempt at better implementation ========================
// Surface Reflection Ratio (F)
float specularReflection_F(float metalness, float VdotH)
{
    return metalness + (1.0 - metalness) * pow(1.0 - VdotH, 5.0);
}

vec3 diffuse(vec3 diffuseColor)
{
    return diffuseColor / PI;
}

// Geometric Occlusion (G)
float geometricOcclusion_G(float NdotV, float NdotL, float alphaRoughness)
{
  float NdotL2 = NdotL * NdotL;
  float NdotV2 = NdotV * NdotV;
  float v = ( -1.0 + sqrt ( alphaRoughness * (1.0 - NdotL2 ) / NdotL2 + 1.)) * 0.5;
  float l = ( -1.0 + sqrt ( alphaRoughness * (1.0 - NdotV2 ) / NdotV2 + 1.)) * 0.5;
  return (1.0 / max((1.0 + v + l ), 0.000001));
}

// Microfaced Distribution (D)
float microfacetDistribution_D(float NdotH, float alphaRoughness)
{
    float roughnessSq = alphaRoughness * alphaRoughness;
    float f = (NdotH * roughnessSq - NdotH) * NdotH + 1.0;
    return roughnessSq / (PI * f * f);
}

float getShadowFactor(vec3 pos, int index)
{
    vec4 shadowcoord = (u_shadow_projection_view_matrices[index] * u_inverse_view_matrix * vec4(pos, 1.0));
    shadowcoord.xy /= shadowcoord.w;
    vec2 shadowtexcoord = shadowcoord.xy * 0.5 + 0.5;
    //float d = .5 * shadowcoord.z + .5;
    float d = .5 * shadowcoord.z + .5 - 1. / (shadow_res * 5.);

    float result = 0.;

    for (float i = -1.; i <= 1.; i += 1.)
    {
        for (float j = -1.; j <= 1.; j += 1.)
        {
            result += texture(shadowtex, vec4(shadowtexcoord + vec2(i,j) / shadow_res, float(index), d));
        }
    }

    return result / 9.;
}

void main() {
    vec2 uv = gl_FragCoord.xy / u_screen;
    float z = texture(dtex, uv).x;
    vec4 xpos = getPosFromUVDepth(vec3(uv, z), u_inverse_projection_matrix);

    vec3 norm = normalize(DecodeNormal(2. * texture(ntex, uv).xy - 1.));
    float roughness =texture(ntex, uv).z;
    vec3 eyedir = -normalize(xpos.xyz);

    vec3 Lightdir = SunMRP(norm, eyedir);
    float NdotL = clamp(dot(norm, Lightdir), 0., 1.);

    vec3 Specular = SpecularBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);
    vec3 Diffuse = DiffuseBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);

    // Custom computation for PBR engine ======================================
    vec4 BaseColor = vec4(sun_color.rgb, 1.0f);
    vec4 SpecularColor = vec4(sun_color.rgb, 1.0f);
    vec3 normal = norm;

    vec3 LightDirection = Lightdir;
    vec3 ViewDirection = eyedir;
    vec3 HalfVector = normalize(ViewDirection + LightDirection);
    float Roughness = 0.0;

    float RefractiveIndex = 0.24f; // RI for Gold materials. I got this from http://refractiveindex.info/
    float F0 = pow(((1.0f - RefractiveIndex) / (1.0f + RefractiveIndex)), 2);

    NdotL = saturate(dot(LightDirection, normal));
    float NdotV = abs(dot(ViewDirection, normal)) + EPSILON; // Avoid artifact - Ref: SIGGRAPH14 - Moving Frosbite to PBR
    float LdotH = saturate(dot(LightDirection, HalfVector));
    float NdotH = saturate(dot(normal, HalfVector));
    // Additional for testing the new implementation bellow
    float VdotH = saturate(dot(ViewDirection, HalfVector));

    // New implementation: ##################################
    float alphaRoughness = roughness;
    float F = specularReflection_F(0.0, VdotH);
    vec3 diffuseContrib = (1.0 - F) * diffuse(sun_color);
    float G = geometricOcclusion_G(NdotV, NdotL, alphaRoughness);
    float D = microfacetDistribution_D(alphaRoughness, NdotH);
    //float D = 1.0;
    G = clamp(G, 0.0, 2.0);
    D = clamp(D, 0.0, 2.0);

    vec3 specContrib = (vec3(F) * G * D) / (4.0 * NdotL * NdotV);

    // Shadows ================================================================
    float factor;
    if (xpos.z < split0)
        factor = getShadowFactor(xpos.xyz, 0);
    else if (xpos.z < split1)
        factor = getShadowFactor(xpos.xyz, 1);
    else if (xpos.z < split2)
        factor = getShadowFactor(xpos.xyz, 2);
    else if (xpos.z < splitmax)
        factor = getShadowFactor(xpos.xyz, 3);
    else
        factor = 1.;

    Diff = vec4(diffuseContrib, 1.0);
    //Diff =  DiffuseFactor;
    //Diff = vec4(factor * NdotL * DiffuseFactor * sun_color, 1.);

    Spec = vec4(specContrib, 1.0);
    //Spec = SpecularColor * SpecularFactor;
    //Spec = vec4(factor * NdotL * SpecularFactor * sun_color, 1.);

    //Diff = FinalColor;
}

```

However when launching the game, I have weird dark artifacts everywhere. I removed the shadows to ouput only the specular and diffuse factor

* 1) Are my input corrects (the VdotH, NdotV and LdotH)
* 2) Did I made any obvious mistake?

I didn't included other files to keep it short. However the full source code of the engine is open source and you can check it here https://github.com/Benau/stk-code/tree/combine/data/shaders

# Answer
Ok after a some research I finally found what was wrong.

Now I compute the final color as following:

```
float metallic = specMapValue;
    vec3 specularMatColor = mix(vec3(0.04), diffuseMatColor.xyz * 4, metallic);

    vec3 result = DiffuseComponent * mix(diffuseMatColor.xyz, vec3(0.0), metallic) + (specularMatColor * SpecularComponent);

```

I still have to fix the reflection of the metal part that is a bit too dark (currently I multiply the spec color by 4 but it feels like a hack

Anyway here is a comparison between Substance Painter and the shader result
> 0 votes

---
Tags: opengl, glsl
---


# Question
Title: How do I move a sprite by clicking other sprites in the stage?
I am new to the LibGDX environment; how do I move a sprite by clicking other sprites in the stage?

As you can see, I have an object I wish to move by clicking on arrow keys. Here are my current scripts:

```
public class MyGdxGame extends ApplicationAdapter {

    Stage stage;

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

        stage = new Stage(viewport);
        Gdx.input.setInputProcessor(stage);

        Myactor actor = new Myactor();
        stage.addActor(actor);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0.33f,0.66f,0.99f,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    @Override
    public void dispose () { }
}

public class Myactor extends Actor {

    Texture texture = new Texture(Gdx.files.internal("ball.png"));
    Sprite sprite = new Sprite(texture);

    Texture Tsol = new Texture(Gdx.files.internal("left.png"));
    Sprite Ssol = new Sprite(Tsol);

    Texture Tsag = new Texture(Gdx.files.internal("right.png"));
    Sprite Ssag = new Sprite(Tsag);

    @Override
    public void draw(Batch batch, float parentAlpha) {
        sprite.setPosition(Gdx.graphics.getWidth()
                - sprite.getWidth() - 50, Gdx.graphics.getHeight() / 2);
        sprite.draw(batch);

        Ssol.setPosition(Gdx.graphics.getWidth() - sprite.getWidth(), 0);
        Ssol.setRotation(90f);
        Ssol.draw(batch);

        Ssag.setPosition(Gdx.graphics.getWidth()
                - sprite.getWidth(), Gdx.graphics.getHeight()-sprite.getHeight());
        Ssag.setRotation(90f);
        Ssag.draw(batch);
    }
}

```

# Answer
> 1 votes
If it's possible, I would recommend using the Scene2d that's included with libgdx. For your left and right arrows, turn them into ImageButtons and add a Touch listener or InputListener, I forget what it's called.

If you want to stick with your sprites, you may be able to do the same thing. If you have a bounding box around the Sprite, you can check if your input is inside the box, and if so, do movement.

# Answer
> 0 votes
Just do a bounding box Check for the control sprites on TouchDown and move accordingly.

example:

```
if(Gdx.input.isTouched()){
    float x = Gdx.input.getX();
    float y = Gdx.input.getY();
    if(Ssag.getBoundingRectangle().contains(x,y)){
        //move sprite some amount
    }
    if(Ssol.getBoundingRectangle().contains(x,y)){
        //move sprite some other amount
    }
}

```

like Joey Mentioned though you can achieve the same thing with more functionality if you use the built in libgdx scene2d api. Good luck, Hope it helped !

---
Tags: libgdx, sprites
---


# Question
Title: What are "socialist core values" or "Chinese Government Approved" for games to run in China?
Noticed this recently on the Street of Rogue changelog Alpha 37 - Even More Downtown Work:

> **Internal**
>
> Did a bunch of work on a “Chinese Government Approved” Chinese version of the game

Now news outlets are reporting PUBG will change for China and align with ‘socialist core values’:

> But, in a statement from Tencent translated by Reuters, the gaming giant says that it will go a step further and alter Battlegrounds to better align with “socialist core values, Chinese traditional culture and moral rules.”

While also mentioning:

> It’s not entirely clear what that means.

and

> Reuters points out that Tencent’s competitor NetEase has accomplished something similar by adding actual government propaganda to the game, adding “red banners into its battleground ... with slogans such as ‘safeguard national security, safeguard world peace.’”

Steam user ytivarg asked Streets of Rogue developer Madguy

> ytivarg 3 Nov @ 4:38am
>
> So what did you have to do to make it "Chineese Government Approved"?

to which he replied:

> Madguy \[developer\] 3 Nov @ 5:16am
>
> @ytivarg I'm a little wary of getting into specifics, but it's basically some text and art that might be seen as objectionable. You can draw your own conclusions (or sift through the localization folder)

* So what exactly does it take to make a game "Chinese Government Approved" or sticking to "socialist core values"?

# Answer
> 5 votes
The short answer is, **the Chinese government disallows anything that it doesn't like**. This is because there are few hard-and-fast rules on what is allowed and not allowed.

Here's a list of forbidden items according to the Ministry of Culture:

* Gambling-related content or game features
* Anything that violates China’s constitution
* Anything that threatens China’s national unity, sovereignty, or territorial integrity.
* Anything that harms the nation’s reputation, security, or interests.
* Anything that instigates racial/ethnic hatred, or harms ethnic traditions and cultures.
* Anything that violates China’s policy on religion by promoting cults or superstitions.
* Anything that promotes or incites obscenity, drug use, violence, or gambling.
* Anything that harms public ethics or China’s culture and traditions.
* Anything that insults, slanders, or violates the rights of others.
* Other content that violates the law

An example of "threatens China's territorial integrity" would be Football Manager 2005 being banned for depicting Taiwan as a separate country.

For "harming the nation's reputation", games that depict the current Chinese government as evil and/or corrupt, e.g. Battlefield 4.

The Ministry's own views evolved over time; like many of China's other state organs, it takes a conservative (or suspicious) view of foreign influence, wary that letting in too much foreign cultural material will influence citizen's own political views and allegiance to the Communist party. This is why video game consoles were banned outright in 2000, but ultimately lifted in 2015. You might find that the same kind of content might be censored if it's very popular and published by a foreign company, but will fly under the radar if it's not popular, or published via partnering with a Chinese company.

But this list is very broad and up for interpretation; the more examples you find and study, the more you realise that the censorship is very inconsistent, and for borderline issues, it's hard to predict whether they will be censored. The best practical advice would be to steer well clear of sensitive topics, avoid depictions of politics especially w.r.t. China, and follow the government's line where appropriate.

Note that a lot of companies self-censor in an effort to avoid being censored by the Chinese government, and this often leads to content being changed or removed when they don't necessarily need to be. This has led to some misconceptions about what the Chinese government disallows, like skeletons or blood, when these are examples of foreign developers playing it safe.

---
Tags: game-design
---


# Question
Title: Directly accessing member variables vs inline accessor functions
I'm currently developing a game but am curious about a performance comparison. Should I be declaring my class member variables public and access them directly, or should they be left private and accessed with a simple inline function that returns that variable's value? At university (in Computer Science - not gamedev) we are always encouraged to use accessor and mutator like functions. However, I've seen some classes from game engines where they directly accessed the member variables. Is performance comparable here? Which way should I go about this?

Thank you.

# Answer
> 2 votes
Such a function will be inlined by the compiler anyway, with a high probability of getting exactly the same code.

There's no difference in performance, base your choice on other tradeoffs (encapsulation, invariants protection, ease of use...).

---
Tags: c++
---


# Question
Title: Rotation versus transform.forward in Unity
I want my player to "face" the direction they're moving, or if not moving, face the last movement direction. There are two solutions I see most often, using rotation (usually `Transform.LookAt`) or a "forward" vector, `transform.forward`.

Is there a reason to use one or the other? What do I gain/lose by using one over the other?

For the time being I'm updating `transform.forward` with a normalized vector of my character movement, unless it's 0,0. That doesn't work 100% so I have some logic left, but I want to understand why this isn't done using rotation.

# Answer
> 2 votes
# Use `Transform.LookAt()`

I didn't even realize that Transform.forward was even *assignable* until I peeked at the documentation just now, but even so I wouldn't do that; it feels improper.

`Transform.LookAt()` will be more reliable, as it should be able to handle a 0,0 vector more easily, just make sure to add the movement vector *to* the player position vector before passing it into `LookAt()` or your player will always look towards scene origin!

# Answer
> 0 votes
Perhaps you should use `Quaternion.LookRotation`, simply passing in your velocity vector as the “forward” argument, and then just assign that to `transform.rotation`. Slightly less maths involved overall, and at least for me it would be conceptually easier to parse. You don’t have to worry about offsetting to a point in space or anything.

---
Tags: unity
---


# Question
Title: Changing Box2D Body from Kinematic to Dynamic after contact
What is the correct way to change a Kinematic body into a dynamic body?

context - I have a dynamic body as a projectile which has to be fired at a kinematic body (it is kinematic because i am tweening it around the world in random movements). when the projectile makes contact with the kinematic body I would like it to become a dynamic body and be affected by gravity and I will apply a force to the contact point.

At the moment I am simply changing the type with in a menthod called by the contactListener

```
body.setType(BodyType.DynamicBody);

```

my biggest issue is that gravity is not acting on the body once it is changed to dynamic, so I'm pretty certain I'm going about this the wrong way.

# Answer
> 1 votes
Trying this myself this seems to be caused by the body still being in sleeping state after changing it to Dynamic. Bodies in sleeping state are not included in the physics calculation until they are awoken by colliding with another body. The solution to this is to manually awake the body:

```
bodyFound.setType(BodyType.DynamicBody);
bodyFound.setAwake(true); // awake the body to enable physics calculations

```

# Answer
> 0 votes
try it like this,

```
mPhysicsWorld.setContactListener(new ContactListener()
{
@Override
public void beginContact(Contact contact)
{
    final Body ballA = (Ball) pContact.getFixtureA().getBody();
    final Body ballB = (Ball) pContact.getFixtureB().getBody();

    Body bodyFound;//find body of interest from ballA.getUserData(); and ballB.getUserData();

    runOnUpdateThread(new Runnable()
    {
        @Override
        public void run()
        {
            //I hope you have used: "physicsWorld.registerPhysicsConnector(new PhysicsConnector(sprite,body,true,false));" while creating bodies
            bodyFound.setType(BodyType.DynamicBody);
            //now it will respond to gravity
        }
    }
}
};

```

if still it do not respond on gravity than update gravity on scene.onUpdate() method, physicsWorld.setGravity(Vector2 yourGravity);

---
Tags: libgdx, box2d
---


# Question
Title: Having trouble implementing libGDX pause
I tried to make pause button. When users click Pause button on a screen, a window came out then, game is frozen until users press continue button in the window . my code is able to pop up window, but not freezing a game...

Let me please know..

```
 public class Pause(){
   .....
   public Pause(){

.....
TextButton pauseButton = new TextButton("Pause",  new
Skin(Gdx.files.internal("x/myui.json")));
    pauseButton.addListener(new ClickListener() {

        @Override
        public void clicked(InputEvent event, float x, float y) {

           //>>here, I think I have to make it pause

            final Window pause = new Window("PAUSE", skin); // pop up window

            TextButton continueButton = new TextButton("continue", skin);
            continueButton.addListener(new ClickListener() {
                @Override
                public void clicked(InputEvent event, float x, float y) {

                    pause.setVisible(false);
                }
            });

            pause.add(continueButton).row();
            pause.add(new TextButton("exit", skin));
            pause.pack();
            //pause.setSize(stage.getWidth() / 1.5f, stage.getHeight() / 1.5f);
            //pause.setPosition(stage.getWidth() / 2 - pause.getWidth() / 2, stage.getHeight() / 2 - pause.getHeight() / 2);

            stage.addActor(pause);

        }
    });
    table.add(continueButton).top();
    stage.addActor(continueButton);

}

```

} }

# Answer
There's another more convenient way to pause your game: delta time manipulation. I prefer delta time manipulation because you do not have to individually place `if(!isPaused) ...` everywhere in your code - only at the very start of your game loop. Pausing your game using delta time manipulation is simply achieved by setting `deltaTime = 0` at the start of your loop.

```
void render(float delta) {
    if (isPaused)
        delta = 0;

    doLogic(delta);
    physicsWorld.step(delta, 6, 2);
    doRendering();

    // We don't want our UI to be paused so we use unscaled delta time
    // for UI calculations. Unscaled delta time can be accessed using
    // Gdx.graphics.deltaTime().
    stage.act(Gdx.graphics.deltaTime());
    stage.draw();
}

```
> 3 votes

# Answer
This is actually, not LibGDX related at all. You just need to set a flag on your code `boolean isPaused = false;` or something alike, and change its value upon pausing:

```
public void clicked(InputEvent event, float x, float y) {
    isPaused = !isPaused;
    //...
}

```

Change your main loop accordingly, and only call your logic and Box2D's `world.update()` if `isPaused` is false, that is:

```
void render() {
    //Calc dt, etc
    if(!isPaused) {
        doLogic(); //Your game logic
        physicsWorld.step(dt, 5, 5); //Box2D's World
    }
    stage.act(); //LibGDX Scene2D's UI Stage logic
    doRendering(); //Your game rendering
    stage.draw();
}

```

This should do.
> 3 votes

---
Tags: libgdx, box2d, pausing
---


# Question
Title: Where do the buffer values come from when rendering?
In the textbook I am reading, it talks about fragment tests that are performed when rendering.

All of these tests involve comparing the current fragment x value (x can be alpha, color, etc.) with a corresponding buffer value, and doing something in case the test passes. The test is usually a comparison between those two values (for example, \>=, \<=, etc.).

What I cannot understand is where do these buffer values come from in the first place?

Are these previous values? If so, what do the current values have to do with previously calculated values?

I don't even know what to search in google for this topic. Sorry if it is a total starter question. I am currently reading about rendering for the first time

# Answer
The "buffer" values are the ones previously written to the destination buffer. For example, for a depth test, this would be a value in the depth buffer.

That value was either put there when you cleared the depth buffer at the start of the frame, or by writing the result of a previous fragment that itself passed the depth test.

This is similar for blending tests (which operate on the color buffer) and stencil tests (which operate on the stencil buffer). You put initial default values there at the start of the frame (most of the time), and potentially modify what is in them after each fragment operation.
> 1 votes

---
Tags: rendering, depth-buffer
---


title: First Person Mouse Aiming

text:
# Question
Title: First Person Mouse Aiming
For one segment of my game, the player is in a fixed position (no movement) and has to aim and shoot at enemies in a first person 3D perspective using the Mouse. The player is holding a wand that shoots projectiles (which I have working) and I need it to rotate and aim towards the cursor as an aiming reticle. I also want to limit how much the player can rotate, so they can look around, but can't turn more than 180 degrees (sort of like this). However, I'm a designer and am having trouble programming this myself. I haven't been able to find a proper solution.

So far, I've been able to cobble the following code together, but the aiming is super wonky and doesn't properly point to the mouse position, making it impossible to actually aim at anything. I would really appreciate some help with figuring this out.

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

public class PlayerShoot : MonoBehaviour {

public float magnifier = 0.5f;
public Rigidbody shotPrefab;
public Transform barrelEnd;
public float shotSpeed = 500;
public Rigidbody sparkPrefab;

// Update is called once per frame
void Update () {

    Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    float midPoint = (transform.position - Camera.main.transform.position).magnitude * magnifier;

    transform.LookAt (mouseRay.origin + mouseRay.direction * midPoint*magnifier);

    if (Input.GetButtonDown("Fire1"))
    {
        Rigidbody shotInstance;
        shotInstance = Instantiate(shotPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
        shotInstance.AddForce(barrelEnd.forward * shotSpeed);
        sparkBlast();

    }
}
// Particle recoil effect
void sparkBlast () {
    Rigidbody shotSparks;
    shotSparks = Instantiate(sparkPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
    Destroy (shotSparks,0.5f);
}

}

```

# Answer
Okay, so I got a bit of help elsewhere and mostly solved the issue. I'll post my code here for people to see in case someone else has the same issue, but surprisingly it had a lot to do with changing transform.forward into transform.up.

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

public class PlayerShoot : MonoBehaviour {

public float magnifier = 0.5f;
public Rigidbody shotPrefab;
public Transform barrelEnd;
public float shotSpeed = 500;
public Rigidbody sparkPrefab;
public Rigidbody sparkBurst;

public Texture2D reticle;
public CursorMode cursorMode = CursorMode.Auto;
public Vector2 hotSpot = Vector2.zero;

public int RayLength = 100;

// Update is called once per frame
void Update ()
{
          // Aiming Mechanic
    var vMousePosition = Input.mousePosition;
    vMousePosition.z = Camera.main.nearClipPlane;

    var vPosition = Camera.main.ScreenToWorldPoint(vMousePosition);

    var vForward = (vPosition-Camera.main.transform.position).normalized;
    var ray = new Ray(Camera.main.transform.position, vForward);

    var targetPosition = ray.origin + (ray.direction * RayLength); // 100 is arbitary, but should be roughly equal to wand length

    transform.up = (targetPosition - transform.position).normalized;

    //Firing
            if (Input.GetButtonDown("Fire1"))
    {
        Rigidbody shotInstance;
        shotInstance = Instantiate(shotPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
        shotInstance.AddForce(barrelEnd.forward * shotSpeed);
        sparkBlast();

    }
}
// Particle recoil effect
void sparkBlast () {
    Rigidbody shotSparks;
    Rigidbody shotBurst;
    shotSparks = Instantiate(sparkPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
    shotBurst = Instantiate(sparkPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
    Destroy (shotSparks,0.5f);
}

}

```
> 0 votes

# Answer
Usually for an FPS style interface, we'd want to hide and lock the mouse cursor to the middle of the screen, so the player isn't distracted by the cursor zipping around disconnected from their aiming reticle, and doesn't accidentally click outside the window and interrupt the game.

We can do that something like this:

```
public class SimpleTurretCamera : MonoBehaviour {

    [Tooltip("Speed multiplier for horizontal & vertical rotation.")]
    public Vector2 turnSpeed = new Vector2(1, 1);

    [Tooltip("Maximum rotation from the initial orientation.")]
    public Vector2 degreeClamp = new Vector2(90, 80);

    [Tooltip("Check this box if you want forward input to look downward.")]
    public bool invertY;

    // Orientation state.
    Quaternion _initialOrientation;
    Vector2 _currentAngles;

    // Cached cursor state.
    CursorLockMode _previousLockState;
    bool _wasCursorVisible;

    void OnEnable () {
        // Cache our starting orientation as our center point.
        _initialOrientation = transform.localRotation;

        // Cache the previous cursor state so we can restore it later.
        _previousLockState = Cursor.lockState;
        _wasCursorVisible = Cursor.visible;

        // Hide & lock the cursor for that FPS experience
        // and to avoid distractions / accidental clicks
        // from the mouse cursor moving around.
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update () {
        // Collect relative motion of mouse since last frame.
        Vector2 motion = new Vector2(
                            Input.GetAxis("Mouse X"),
                            Input.GetAxis("Mouse Y"));

        // Scale it by the turn speed, add it to our current angle, and clamp.
        motion = Vector2.Scale(motion, turnSpeed);
        _currentAngles += motion;
        _currentAngles = Vector2.Min(_currentAngles, degreeClamp);
        _currentAngles = Vector2.Max(_currentAngles, -degreeClamp);

        // Rotate to look in this direction, relative to our initial orientation.
        Quaternion look = Quaternion.Euler(
                            -_currentAngles.y,                       // Yaw
                            (invertY ? -1f : 1f) * _currentAngles.x, // Pitch
                            0);                                      // Roll

        transform.localRotation = _initialOrientation * look;
    }

    void OnDisable () {
        // When switched off, put everything back the way we found it.
        Cursor.visible = _wasCursorVisible;
        Cursor.lockState = _previousLockState;
        transform.localRotation = _initialOrientation;
    }
}

```
> 2 votes

---
Tags: unity
---


# Question
Title: How can I implement persistent state for objects defined in a level?
I am developing a 2D Metroidvania which consists of a series of interconnected levels that can be revisited.

Each level is represented by a Tiled TMX file in which I have specified where various objects of different sprite classes spawn (for example, enemies, pickups, levers, etc.). When starting a new game, loading a saved game, or changing a level, my game loop runs through the appropriate TMX file and generates all the objects in that level.

I handle level changes in the following way: If the `Player` object intersects a `Portal` object, a `change_map()` method is called which loads a new map (the one associated with the intersected portal) and positions the player at the appropriate position on the new map.

Some of my objects have states which I would like to be *persistent* through level changes and saving and quitting the game. For example, if a player unlocks a door and the state attribute of the door is set to "open," I would like the door to be open when the player returns. I want something similar for levers, which can be set to left or right, and various other objects. Further, the player will sometimes have collected items which I do not want to respawn when the player revisits the area.

My question is thus **how can I handle this kind of persistence?**

I am working in Python, although I think you can abstract away from that.

# Answer
> 26 votes
I think not overthinking this issue will give the best results so I would just implement a simple key-value saving system into your game that you store along your other save data and then load on-demand when you need to access a previous state.

The flow could look something like this:

1. Load level from file
2. Before placing a tile / object check if it has a "persistent" property.
    1. If yes: Check the saved key-value pair for the key matching the property and fetch the approprtiate value.
    2. If no: Place the object as normal
3. When the player exits the level / saves the game loop through all objects with a "persistent" property and save them as a key-value pair.

---

Here's a pseudo-code example based on what I use for my simple 2D game:

```
def load_map(map):
    for y in range(0, height):
        for x in range(0, width):
            tile = map[x, y]

            for property in tile.properties:
                if is_persistent(property.name):
                    // Name prefixed with "persistent" means that it's persistent
                    // so we load the value from out persistent storage
                    property.value = persistent_values[property.name]

def save_map(map):
    ... everything in load_map ...
    if (property.name.matches("persistent_*")):
        // Name prefixed with "persistent" means that it's persistent
        // so we save the value to persistent storage
        persistent_values[property.name] = property.value

def is_persistent(name):
    return name.matches("persistent_*") and persistent_values.contains(name)

```

Then I can just check state using this property:

```
def draw():
    if properties["persistent_is_pressed"].value:
        draw_sprite(button_pressed)
    else:
        draw_sprite(button_unpressed)

def on_pressed():
    properties["persistent_is_pressed"].value = not properties["persistent_is_pressed"].value

```

If you're using a tiled map editor like Tiled adding properties like this is very easy:

Hopefully this will give you an idea on how to implement persistent state as simple as possible!

---
Tags: 2d, architecture, savegame, tiled
---


# Question
Title: How can I favour vertical travel before horizontal with my A* path-finding heuristic?
I'm writing an AI of a 'police car' that 'patrols' over a 2d grid. Right now, the patrol car randomly selects a destination, finds a path between it's current intersection and the destination intersection, follows the planned path then rinse and repeat. That's the intended behaviour and it works as expected.

Now the A\* algorithm I wrote based on Wikipedia's page about it will give me "step style" paths.

And I don't like it in this context. I want the police car to go straight in a direction first (vertical, or up and down, or along the y-axis), then straight in the other direction (i.e. horizontal, or left or right, or along the x-axis) before it reaches its destination.

I though about (and tried) hacking the heuristics method to "inflate" the values for x-axis paths, the idea being that it would find a path for the y-axis first, then for the x-axis, but there was no improvement to the police car behaviour.

In the same idea, I tried to tell the algorithm that x-axis distances were more expensive than the y-axis distances, but I got the same result: there was no improvement to the style of the paths the cars used.

How can I modify the heuristic evaluation method of the A\* algorithm so that the police car prefers going all the way through vertically, then horizontally?

Additional information:

* There is no obstacle on the grid.
* All the grids are separated evenly by a floating point value distance.

In my Graph.cpp, I have these two methods that basically find a path between `aStart` and `aEnd`. (Sorry for the bad name of "plot".)

```
// Find a path between aStart and aEnd.
std::vector<int>
Graph::plot( int aStart, int aEnd )
{
  std::set<int> closedSet;
  std::set<int> openSet = {aStart};

  std::map<int, int> cameFrom;

  std::map<int, float> gScore;
  for ( auto node : mNodes )
    gScore[node.first] = std::numeric_limits<float>::infinity();

  gScore[aStart] = 0.0f;
  std::map<int, float> fScore;
  for ( auto node : mNodes )
    fScore[node.first] = std::numeric_limits<float>::infinity();

  fScore[aStart] = getHeuristicBetween( aStart, aEnd );

  while (openSet.size() > 0)
  {
    int current = -1;
    float currentMinVal = std::numeric_limits<float>::infinity();
    for ( auto nodeIndex : openSet )
    {
      if ( fScore[nodeIndex] < currentMinVal )
      {
        current = nodeIndex;
        currentMinVal = fScore[nodeIndex];
      }
    }

    if ( current == aEnd )
      return reconstructPath(cameFrom, aEnd);

    openSet.erase( current );
    closedSet.insert( current );
    for ( auto outArc : mNodes[current]->getOutArcs() )
    {
      int neighbourIndex = outArc->getNodeTo()->getId();
      if ( closedSet.find(neighbourIndex) != closedSet.end() )
        continue;
      // The distance will be artificially higher if it's on an horizontal edge:
      float tentativeGscore = gScore[current] + outArc->getInfluencedDistance();
      if ( openSet.find(neighbourIndex) == openSet.end() )
        openSet.insert(neighbourIndex);
      else if ( tentativeGscore >= gScore[neighbourIndex] )
        continue;

      cameFrom[neighbourIndex] = current;
      gScore[neighbourIndex] = tentativeGscore;
      fScore[neighbourIndex] = gScore[neighbourIndex] + getHeuristicBetween( neighbourIndex, aEnd );
    }
  }
}

// Estimates the shortest path between aFromNode and aToNode.
float
Graph::getHeuristicBetween( int aFromNode, int aToNode ) const
{
  auto nodeStartIt = mNodes.find( aFromNode );
  auto nodeEndIt   = mNodes.find( aToNode );

  if ( nodeStartIt == mNodes.end() || nodeEndIt == mNodes.end() )
    return std::numeric_limits<float>::infinity();

  float dx = nodeEndIt->second->getX() - nodeStartIt->second->getX();
  float dy = nodeEndIt->second->getY() - nodeStartIt->second->getY();

  float length =
    (   glm::vec2( nodeStartIt->second->getX(), nodeStartIt->second->getY() )
      - glm::vec2( nodeEndIt->second->getX()  , nodeEndIt->second->getY() ) ).length();

  if ( dx > dy )
  {
    return length * 0.1; // Artificially inflate the cost of going left-right.
  }
  return length;
}

```

With or without the modification to the algorithm, I get this kind of behaviour:

# Answer
During a discussion a few years ago with some grad students studying pathfinding, I came up with a few solutions to the problem "How do I ensure the A\* solution is exactly the same as the solution obtained by BFS *(in particular, choosing certain edges over others when there is more than one best path)*"

It's been a few years since I've thought about it, so I will just copy+paste the final solution I came up with from the email chain.

---

I’ve come up with two ways of doing it, if any of you are still interested in this problem. Both have worse computational-complexity than BFS/Djikstra’s, but may still be faster in practice on large graphs or graphs with many obstacles. I’ll try implementing these if I can't find anything better, and see how they compare to BFS for my problem-space.

The first way is more widely applicable. The second is specifically for 4- or 8-connected graphs with all edge-weights 1 (or infinity).

The problem, again, is that there may be multiple best-paths, and we want to use A\* to find the same path obtained by BFS/Djikstra’s. To do this, we must alter A\* slightly – instead of stopping when we reach the end-node, we continue expanding all nodes with f-value \<= f(end-node). Since the A\* heuristic is admissible, this guarantees that all nodes that belong to a best-path will be expanded eventually: in particular, the nodes belonging to the BFS-best-path will be expanded.

In the first algorithm, when a successor B of a node A is seen for the first time, we set its distance-to-start g(B) = g(A) + c(A,B) and its previous-node property p(B) = A, like usual. If B is also a successor to node C, and later C is expanded, we compare B’s current distance-to-start g(B) with its potential new distance-to-start g’(B) = g(C) + c(C, B):

* If g’(B) \< g(B) (only possible if h is not consistent), we overwrite g(B) and p(B)
* If g’(B) \> g(B) we do nothing.
* If g’(B) == g(B), we have a problem. We need to figure out which path has higher lexicographical ordering - we need to find the first node that the path passing through A and the path passing through B deviate from one another. Once we know that, we can simply check which path takes the higher-priority direction from that node.

Finding the first node that the paths deviate is simple enough: we walk backwards along each path's previous-node property p(n) until we find the first node belonging to both paths. Since every node has only one previous-node property, every node before this one will be the same on both paths. Since this node will have the same g(x) value for both paths, we can find it by always stepping backwards on the path with the higher g(x) value.

If C is considered part of the current best-path at this point in our algorithm, and both B and C (or A and C) are part of the BFS-best-path, then B (or A) will be considered part of the current best-path at this point in our algorithm. And since all best-paths start at the same node, we can show inductively that this will give us the BFS-best-path.

The second algorithm is similar to the first, but we use the fact that, since there is (thus far) exactly one node where the paths containing A and B go from being the same to differing, instead of searching backwards from the end for the first place they're the same, we can search forwards from the start for the first place they're different. We can do this by storing the entire best-path found so far for each node in that node. In most cases, this would be unwieldy, but in 4- (or 8-)connected graphs with all edge-weights at 1, we can store the best path using 2 (or 3) bits-per-node, with higher-priority paths having higher values.

We can treat the paths as arbitrary-length integers, with the most-significant-2-bits representing the first direction moved. Then (assuming the two bit-strings have the same length) we can simply check which integer is larger to determine which path has higher priority. This allows us to compare 16 nodes of the path at a time with 32-bit registers; 32 nodes with 64-bit registers; and 64(!) nodes at a time with 128-bit registers (like the SSE registers in x86 and x64 processors), making this search very inexpensive even for paths with 100's of nodes.

---

As I was writing this, a user on Stackoverflow.com posted a third potential solution: run A\* as above to expand all nodes that belong to a best path; work backwards from the finish to find only those nodes that belong to a best path; work forward from the start again, finding the BFS-best-path by walking along the nodes that belong to a best-path, always moving upwards in g-value and breaking ties using our lexicographical-ordering.
> 2 votes

# Answer
The heuristic you are using is creating a bias in favor of "diagonal" paths. Using Euclidean distance in this scenario causes the distance between points along a diagonal to be underestimated. This isn't technically incorrect since the result will still be a shortest path, but since actual diagonal movement isn't possible in your case, using Manhattan distance is probably a better fit.

This won't guarantee that the found path will not have a staircase pattern, but you may be able to fix that by carefully selecting which node you select first if multiple nodes have equal f scores.
> 2 votes

# Answer
The naive approach to simply inflate the cost when going in a specific direction will never work in the heuristic evaluation function, because that function is unaware of the departure and final destinations. Also, it has to return the value of the most optimal path. To make it work from there, it would need to return the cost for the most optimal path, and the cost for the not-most-optimal-path. This does not make sense. The same applies when trying to hack the distance between two nodes (when asking the arc about it).

After thinking about it, I took a closer look into the algorithm, specifically the Wikipedia article:

> Typical implementations of A\* use a priority queue to perform the repeated selection of minimum (estimated) cost nodes to expand. This priority queue is known as the open set or fringe. At each step of the algorithm, the node with the lowest f(x) value is removed from the queue \[...\] (Wikipedia)

To make it work the way I wanted, I had to change how the node with the "lowest cost" was selected. I modified the algorithm like this:

1. Pick the candidate node if its score is lower than the current best score.
2. If the candidate node score is equal to the current selected node's score, pick the node where we have the shortest distance in y direction to go.

The code goes about like this:

```
  while (openSet.size() > 0)
  {
    int current = -1;
    float currentMinVal = std::numeric_limits<float>::infinity();

    for ( auto nodeIndex : openSet )
    {
      auto epsilonLessThan = []( float aLhs, float aRhs, float aEpsilon ) {
        if ( std::abs( aLhs - aRhs ) < std::abs( aEpsilon ) )
          return false;
        return aLhs < aRhs;
      };

      if ( epsilonLessThan( fScore[nodeIndex], currentMinVal, 0.00005f) )
      {
        current = nodeIndex;
        currentMinVal = fScore[nodeIndex];
      }
      else if ( glm::epsilonEqual( fScore[nodeIndex], currentMinVal, 0.00005f ) )
      {
        auto goalNode        = mNodes.find( aEnd );
        auto selectedNode    = mNodes.find( current );
        auto replacementNode = mNodes.find( nodeIndex );

        assert( goalNode != mNodes.end() && selectedNode != mNodes.end() && replacementNode != mNodes.end() );
        auto goalNodePosition        = glm::vec2( goalNode       ->second->getX(), goalNode       ->second->getY() );
        auto selectedNodePosition    = glm::vec2( selectedNode   ->second->getX(), selectedNode   ->second->getY() );
        auto replacementNodePosition = glm::vec2( replacementNode->second->getX(), replacementNode->second->getY() );

        auto deltaSelected = selectedNodePosition - goalNodePosition;
        auto deltaReplacement = replacementNodePosition - goalNodePosition;

        // We prefer going in y first
        if ( std::abs( deltaReplacement.y ) < std::abs( deltaSelected.y ) )
        {
          // we prefer that.
          current = nodeIndex;
          currentMinVal = fScore[nodeIndex];
        }
      }
    }

    if ( current == aEnd )
      // [...]

```

While the usage of `glm::epsilonEqual` is quite obvious, the `epsilonLessThan` was useful: tiny differences between `fScore[nodeIndex]` and `currentMinVal` would make the evaluation estimate them as being "less than" instead of "equal". (I could have checked the conditions in the other order and I guess I would have arrived at the same result.)

Here is the result:
> 1 votes

---
Tags: c++, path-finding
---


title: 2d tile map render rotation math?

text:
# Question
Title: 2d tile map render rotation math?
I am working on a personal project and am trying to make a 2d tile map render that needs to handle rotation.

I am using raylib to handle the drawing stuff onto the screen and am using this function to draw a tile:

```
void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, Vector2 origin, float rotation, Color tint);

```

How do I calculate the new coordinates of the tiles after the rotation and the individual rotation of each tile if I want to rotate the tile map?

I also need to figure how to do mouse click detection for tiles when they are rotated with their new coordinates and how to do ‘collision detection with cursor’ with rotated squares/tiles.

And due to the way the project is set up I cannot rotate the camera.

Extra info/diagram:

# Answer
You will need to transform the point by a rotation/transformation matrix.

Wikipedia has good information about using rotation matricies https://en.wikipedia.org/wiki/Rotation\_matrix

θ is your angle
X,Y are your coordinates of your object (represented as a column vector/1D matrix)
X',Y' are your new, rotated coordinates

```
[X'] = [cosθ -sinθ][X]
[Y'] = [sinθ  cosθ][Y]

```

This is a small amount of matrix math equating to

```
X' = [cosθ * X] + [-sinθ * Y]
Y' = [sinθ * X] + [ cosθ * Y]

```

You can use transformation matrices for lots of operations such as translations, scaling, rotation, skewing, etc. They are widely used in 3D graphics
> 1 votes

# Answer
get rotation flag from tile,parse it and swap coordinates from your vertexes

Here good engine and good example where you can find how to do it

https://github.com/oxygine/oxygine-framework/commit/3d02d81e0b3851bab705aaea72d5a0375c9ea432
> -1 votes

---
Tags: mathematics, rendering, tilemap, tiles, raylib
---


# Question
Title: UnsupportedOperationException: Unsupported format for this image
So.. I'm learning lwjgl currently and I stumbled on this weird error caused by slick-util which seems to be incorrectly displayed.

ERROR :

```
java.lang.UnsupportedOperationException: Unsupported format for this image
at org.newdawn.slick.opengl.PNGDecoder.decode(PNGDecoder.java:272)
at org.newdawn.slick.opengl.PNGImageData.loadImage(PNGImageData.java:97)
at org.newdawn.slick.opengl.CompositeImageData.loadImage (CompositeImageData.java:62)
at org.newdawn.slick.opengl.CompositeImageData.loadImage(CompositeImageData.java:43)
at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:292)
at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:254)
at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.
java:200)
at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:64)
at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:24)
at com.saumi.utils.Renderer.loadTexture(Renderer.java:91)
at com.saumi.assets.Assets.<init>(Assets.java:23)
at com.saumi.main.Main.init(Main.java:27)
at com.saumi.main.Main.<init>(Main.java:45)
at com.saumi.main.Main.main(Main.java:71)

```

The problem is that even though it says unable to read png data, the picture that the error points to is loaded properly and even displayed onto the screen!

I don't know what is is supposed to mean, please help.

EDIT :

My texture loader code :

```
public static Texture loadTexture(String path , String fileType){
    Texture tex = null;

    InputStream in = ResourceLoader.getResourceAsStream(path);
    try {
        tex = TextureLoader.getTexture(fileType,in);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return tex;
}

```

My Assets code which loads the textures :

```
public class Assets {

public static Texture playBtn , tutBtn , quitBtn;

public static Texture background;

public static Texture player , missile;

public Assets(){
    playBtn = Renderer.loadTexture("res/PlayBtn.png", "PNG");
    tutBtn = Renderer.loadTexture("res/TutBtn.png", "PNG");
    quitBtn = Renderer.loadTexture("res/QuitBtn.png", "PNG");

    player = Renderer.loadTexture("res/KillSkull.png", "PNG");
    missile = Renderer.loadTexture("res/Missile.png", "PNG");

    background = Renderer.loadTexture("res/Background.png", "PNG");
}

}

```

The Error points to the Background Image , and the order in which it is loaded does not matter, it always points to that image.

# Answer
There are a few solutions to this. Try them until you find one that works for you!

## Re-saving the image (Maybe Windows only)

1. Open the image in your image editing program / re-create the image from scratch.
2. Copy the entire image to your clipboard **from your image editing software** (don't save it).
3. Paste the image into MS Paint (**might** work with other programs. Tested only with MS Paint) and save the image as a **.png**.

## Change bit-depth to 32 bit (credit to Lemonzap)

1. Open your image in your image editing software.
2. Change the bit-depth to 32-bit.
    1. **Paint.net**: You chance it in the save dialog
    2. **Gimp**: Should automatically have 32-bit depth if your `Image > Mode` is RGB.
    3. **Photoshop:** In the menu `Image > Module` choose `32 Bits/Channel` or set it when you create the image (Image from Zidane)
3. Save like normal.

## Set interlacing to none (credit to Paulywog)

1. Open your image in your image editing software
2. Change interlacing to none.
    2. **Photoshop**: You change it in the save dialog.
    3. **Gimp:**
3. Save like normal.
> 1 votes

---
Tags: java, lwjgl, png
---


# Question
Title: Most efficient way of drawing a lot of cubes OpenGL ES
I have to draw a lot of cubes in my OpenGL programme for android. All the cubes have the same size but different colors. I know that calling glDrawArrays is expensive operation so I should call it less as possible. But as I know I have to call it 6 times (one per each side) and since I have more than 500 cubes it's not efficient at all. Does anyone have the idea what to do?

Btw, I am using OpenGL ES 1.0.

I saw that I can use one big VBO but I don't know how to do that.

# Answer
* Use OpenGL ES 2
* Set each vertex x,y,z and color information to one big VBO
* Set the color in the fragment shader
* Use ONE unique call to glDrawArrays
> 1 votes

---
Tags: opengl, opengl-es
---


title: Detect collision of a circle

text:
# Question
Title: Detect collision of a circle
I want to detect collision in every different color to this circle

# Answer
I would simply make use of Unity's built-in functionality of parenting and tagging to create one child for every section of the circle and then check the tag to see what part you hit.

Here's an image illustrating the setup (click for larger image):

Then you can have a script on the parent `Circle` object that makes use of the `OnCollisionEnter2D` method:

```
void OnCollisionEnter2D(Collision2D coll)
{
    if(coll.collider.tag == "Red")
    {
        // Hit red part of circle
     else if (coll.collider.tag == "Blue")
    {
        // Hit blue part of circle
    }
    // etc.
}

```

## Notes:

* Make sure to set the tag of the child objects using the `tag` dropdown.
* Make sure the parent `Circle` object has a `RigidBody2D`.
> 1 votes

---
Tags: unity
---


# Question
Title: Move Camera is an order so that the background doesn't move fast
I have created a game where I am moving my player on a platform. The car moves fine on the platform and the camera follows the car as well. My problem is that I wanted my background to move slowly. I am using a perspective camera and I am moving camera away to create a zoom out effect when my player jumps. Do you suggest I should move my background towards right so that it creates a simple slow effect? As currently it moves very fast.

here is my video demonstration : https://www.youtube.com/watch?v=xO\_mEXo6mNA

# Answer
Try tiling your background and adjusting the offset to create an effect of motion. this will allow you to "slow" and "speed up" the movement of the background

here's the tutorial from Unity: Link to Unity Tutorial starting at the right spot

Link to Full Tutorial with code
> 1 votes

# Answer
Move the background further away from the camera.

This causes the angular momentum of the background to be less, resulting in a less dramatic parallax effect.
> 1 votes

---
Tags: unity, camera, parallax-scrolling
---


# Question
Title: Why does unity obj import flip my x coordinate?
When I import my wavefront obj model into unity and then draw lines over it with the same coordinates in the obj file, the x coordinate is negated.

I don't see any option in the importer that might be doing that. And I'm using the same localToWorldMatrix and the same coordinate data in the .obj file. Hmmm

```
GL.PushMatrix();
GL.MultMatrix(transform.localToWorldMatrix);

CreateMaterial();
lineMaterial.SetPass(0);

GL.Color(new Color(0, 1, 0));
GL.Begin(GL.LINES);

GL.Vertex(p1);
GL.Vertex(p2);

GL.Vertex(p2);
GL.Vertex(p3);

//...

GL.End();
GL.PopMatrix();

```

# Answer
> 3 votes
I had quite a discussion about this with Unity customer support, which you can see here. The short of it is this:

1. The actual OBJ file format specification declares that, "A right-hand coordinate system is used to specify the coordinate locations."
2. Unity uses a left-hand coordinate system.
3. Conversion from right-handed to left-handed is accomplished by negating the coordinates on any axis (it doesn't matter which one).
4. Unity negates the X-coordinates to convert the right-handed OBJ data to left-handed data.

As far as I can tell, this is not documented by Unity. But, if you look at that bug report and the dialog I had with Unity's rep, it is the intended behavior.

Note that *none of this depends on any modeling app*. I did my tests with a file I created in Notepad. It all comes down to the OBJ file being *specified* as using a right-hand system, Unity using a left-hand system, and Unity negating the X-coordinate to convert from one to the other.

# Answer
> 1 votes
The difference between a r/h coordinate system & a l/h coordinate system is that the x axis is negated. I wonder if the object was created in a modeling app that uses one system while your development framework uses the other.

# Answer
> 0 votes
Look at the mesh instead of the game object in the inspector and see the orientation. Most of the times, exporters apply an overall transform.

# Answer
> 0 votes
I was seeing a similar issue. To investigate further I added an editor script like this, to log the vertices of the mesh I applied it to:

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

[ExecuteInEditMode]
public class TestScript : MonoBehaviour
{
    void OnEnable()
    {
        Mesh mesh = GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        foreach (var vertex in vertices)
            Debug.Log(String.Format("{0} {1} {2}", vertex.x, vertex.y, vertex.z));
    }
}

```

This logged coordinates like this:

```
-42.4 -6.608938 -1.6
-42   -6.579293 -1.6
-42.4 -6.652683 -1.2
-42.4 -6.608938 -1.6

```

Whereas my original .obj file had vertices like this:

```
v 42.4000015258785 -6.60893774032594 -1.60000002384146
v 42.4000015258785 -6.65268325805652 -1.20000004768452
v 42.0000000000008 -6.57929277420054 -1.60000002384146
v 42.0000000000004 -6.57929277420055 -1.60000002384106

```

So as Steve H suggested, it does look like Unity is negating the X values while importing. It must be assuming that the .obj file is right-handed, and so it converts to Unity's left-handed coordinate system by negating the X.

It looks like Unity also does some re-ordering / optimisation of the mesh, as the order and number of the vertices in Unity is not the same as the original .obj file either.

---
Tags: c#, 3d, unity, models, import
---


# Question
Title: Customising character appearance though textures
At the moment I am contemplating adding character customisation to my game, however I am unsure what approaches are available when it comes to using textures/decals to add facial features (like facial hair, hairstyle, scars/blemishes etc).

The character in question is stylised with a cel shader like effect.

So what are some approaches to take? Should I be using shaders to blend textures together by having the normal diffuse texture and then a mask texture to add facial hair or are there better more efficient results to achieve what I want?

Would another possibility be to use a shader and then bake the resultant blended texture to a new diffuse texture and use that?

To clarify, the customisation will be through textures only and not through adding/changing meshes

# Answer
For "efficiency" in broad strokes, you generally want to avoid state changes where possible and reduce your draw calls as much as possible.

For a feature-customization implementation that does not rely on any additional geometry and is handled entirely via textures, that probably means you want to avoid switching textures often (in other words, *probably* not baking a bunch of per-character textures).

Which means you'll likely want to group each character into two logical draws: the one drawing the part of the characters that cannot be customized, and the one drawing the parts that can be.

You'd likely want to pack as many different possible features into one texture as you can get away with given your desired quality bar. You might stuff all the beards into one column, for example, all the sideburns into another, and so on. Kind of like a sprite sheet.

That way you can represent the customization as texture coordinate offsets (directly in prepared vertex buffers, or via instance attributes, whichever works better for you) and still draw lots of it in one go.
> 3 votes

---
Tags: unity, shaders, textures
---


# Question
Title: Are there special APIs used to make PS4 games?
Game engines can build games for PS4, but how are those engines written to support it? Is there any special kind of support, API or something provided by the PS4? Does it have like a new programming language or new specification like OpenGL or DirectX?

# Answer
> 3 votes
Yes. All major consoles have proprietary APIs (which may include graphics APIs). Most of these APIs are non-public.

Engines that support those consoles will have abstraction layers that write against those APIs where required.

---
Tags: playstation4
---