# Question
Title: Are there any hex tile sizes where both width and height are integers?
I'm trying to figure out the optimal width and height (in pixels) to start building hex tiles for game development. My preference is for "flat topped" hex grids, but the math is similar for both.

I am looking for an "optimal" tile size that allows both the width and the height of the tile to be a rounded pixel number, based on the fact that `height = sqrt(3)/2 * width`.

My math skills being virtually nonexistent, I just ran a brute force script that ran through widths from 1 to 1024 and did not come up with a single value for `w` where `h` was an integer. Is this really the case? How does anyone create pixel-perfect hex tiles if there's no even width & height size that can accommodate a perfect hex aspect ratio?

# Answer
No. √3 is an irrational number, and by definition an irrational number can not be used as a ratio between two natural numbers (integers) such as pixel counts.

However, there is no rule that says you have to use ideal hexagons in your game tiles. If you approximate it closely and avoid any miscalculations that may result, which you should be able to do with integer math anyway, you can get a good-looking product while working with easy numbers behind the scenes (if you can call 100 and 173 easy to work with).
> 16 votes

# Answer
Just in case anyone is interested:

Lets assume sqrt(3) is rational:

1. Therefore, there must be two integral numbers `a` and `b` such that `a/b` = sqrt(3)
2. We assume these numbers are coprime, if they have a common factor, we divide by it producing a coprime pair, `a` and `b`
3. We know that `(a/b)^2 = 3` and therefore `a^2 = 3 * b^2`.
4. `3 * b^2` is devisible by 3 as `b^2` is integral and therefore `a^2` is also devisible by 3.
5. There are not integral numbers square is devisible by 3, but they are not. so it follows that `a` itself is devisible by 3. Lets define `k = a/3`.
6. `a^2 = (3k)^2 = 3 * b^2` =\> `9 * k^2 = 3 * b^2` = \> `3 * k^2 = b^2` which means that `b` is also devisible by 3.
7. This contradicts the base assumption that they are coprime integers.

Credits to wikipedie for refreshing my memory.
> 4 votes

# Answer
Lots of complex answers here. If you are looking for a 'Close enough' answer, try 7x8. Not a perfect hexagon, but close enough that most people will not notice the difference.
> 1 votes

---
Tags: hexagonal-grid
---


# Question
Title: My animation poses aren't showing up in my asset browser
I tried following this tutorial, where they eventually ask me to drag the `Aim_Center` from the asset browser onto the graph. The problem is, the only thing that shows up in my asset browser is the `Aim_Offset` that I created earlier.

Is there something I don't see? This is my first time using animations in the Unreal Engine. What am I doing wrong?

# Answer
As *Raildex* points out, you need to *create* the asset, first. This is actually stated quite clearly, in the tutorial you have linked.

---

It appears likely that you have mistakenly skipped a part of the tutorial. You mention being told to locate `Aim_Center`, which appears to be section three, but only finding `Aim_Offset`, which you would have made in section two.

`Aim_Offset` is being made in section one. I feel this is *very* clear, though it is referenced as **`Hero_AimOffset`**, *not `Aim_Offset`*. This should not cause any confusion, if you are following the tutorial. This is still consistent with the name used, later, when you are asked to find it.

---

It is important you follow the entire tutorial; *start* to *end*. In this case, the missed section makes up more than the `Hero_AimOffset` asset; it is likely that if you missed *one*, you probably missed *more*.
> 0 votes

---
Tags: animation, unreal-4, skeletal-animation
---


# Question
Title: How to make player stay on a moving object
I've made an obstacle course with various moving parts to test out movement of a player. In the obstacle course there is a section where there are multiple cubes moves from side to side, and you have to jump from one to the other. But regardless of their speed, I can't seem to get the player to stay on top of any of the moving cubes. I have no clue how to fix this my only guess would be to use materials, but I can't apply any to the character controller. I appreciate any suggestion that you can give. Also the movement is done as an animation that I created in unity in the animation window.

Thanks, Nova

# Answer
You don't have to apply any **Force** or **Velocity** to your player. Just set your *player* child of the current Obstacle, and it will stick to that Obstacle.

```
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "YOUR_OBSTACLE_TAG")
{
//This will make the player a child of the Obstacle
myPlayer.transform.parent = other.gameObject.transform; //Change "myPlayer" to your player
}
}

```

Note : Remember to remove the player from the Obstacle's child list when you jump or leave it

```
void OnTriggerExit(Collider other)
{
myPlayer.transform.parent = null;
}

```
> 2 votes

# Answer
Because you are using an animation to move your platforms the physics in unity has no idea that the object is actually moving. That is why your player stays in the same place and eventually falls off. Try applying a force to a rigidbody on the platform. I don't have time to test this right now so let me know how it goes. If you need any more help I'm happy to help.
> 0 votes

# Answer
I never used unity but if it's using a physics engine, maybe you could set the friction to the maximum. Or you could add the moving platform's velocity to the player's velocity.

Hope that helps.
> -1 votes

---
Tags: unity, movement, character, materials
---


title: Simple LWJGL program renders nothing

text:
# Question
Title: Simple LWJGL program renders nothing
When I run the following basic LWJGL program, all I get is a red screen due to `glClearColor(1, 0, 0, 1)`. Nothing renders in the screen except the red background. I'm using Ubuntu as my operating system.

How do I fix this? Here is the complete source code.

Main.java:

```
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.PixelFormat;

public class Main {
    public static void main(String[] args) {

        createDisplay(1280, 720);

        //Initializations...

        float[] vertex = {
            -1.5f, 1.5f, 0f,    //V0
            -1.5f, -1.5f, 0f,   //V1
            1.5f, -1.5f, 0f,    //V2
            1.5f, 1.5f, 0f      //V3
        };

        int[] index = {
                0, 1, 3,
                3, 1, 2
        };

        Render render = new Render(vertex, index);

        Shader shader = new Shader("vertexShader", "fragmentShader"); //initialize shader

        shader.bindAttribute(0, "positions");
        shader.link();

        GL11.glClearColor(1, 0, 0, 1);

        while(!Display.isCloseRequested()) {
            Display.sync(60);
            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
            render.draw(shader);
            Display.update();
        }

        render.cleanUp();
        shader.cleanUp();
        Display.destroy();
    }

    private static void createDisplay(int Width, int Height) {
        ContextAttribs attribs = new ContextAttribs(3, 2);
        attribs.withForwardCompatible(true).withProfileCore(true);

        try {
            Display.setDisplayMode(new DisplayMode(Width, Height));
            Display.create(new PixelFormat(), attribs);
        } catch (LWJGLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.err.println("Cannot Create Display");
        }

        GL11.glViewport(0, 0, Width, Height);
    }
}

```

Render.java:

```
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;

public class Render {

    int vaoID;
    int vertexCount;
    List<Integer> vbos = new ArrayList<Integer>();

    public Render(float[] vertex, int[] indices) {
        vaoID = createVAO();
        addIndices(indices);
        addVertex(vertex);
        unbindVAO();
        vertexCount = indices.length;
    }

    public void draw() {
        GL30.glBindVertexArray(vaoID);
        GL20.glEnableVertexAttribArray(0);
        GL11.glDrawElements(GL11.GL_TRIANGLES, vertexCount, GL11.GL_UNSIGNED_INT, 0);
        GL20.glDisableVertexAttribArray(0);
        GL30.glBindVertexArray(0);
    }

    public void draw(Shader shader) {
        shader.bind();
        GL30.glBindVertexArray(vaoID);
        GL20.glEnableVertexAttribArray(0);
        GL11.glDrawElements(GL11.GL_TRIANGLES, vertexCount, GL11.GL_UNSIGNED_INT, 0);
        GL20.glDisableVertexAttribArray(0);
        GL30.glBindVertexArray(0);
        shader.unbind();
    }

    public void cleanUp() {
        for(int vbo: vbos) {
            GL15.glDeleteBuffers(vbo);
        }
        GL30.glDeleteVertexArrays(vaoID);
    }

    public int getvaoID() {
        return vaoID;
    }

    private int createVAO() {
        int id = GL30.glGenVertexArrays();
        GL30.glBindVertexArray(id);
        return id;
    }

    private void addVertex(float[] vertex) {
        addToAttribList(0, vertex);
    }

    private void addToAttribList(int slot, float[] buffer) {
        int vboID = GL15.glGenBuffers();
        vbos.add(vboID);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
        FloatBuffer float_buffer = toFloatBuffer(buffer);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, float_buffer, GL15.GL_STATIC_DRAW);
        GL30.glVertexAttribIPointer(slot, 3, GL11.GL_FLOAT, 0, 0);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    }

    private void addIndices(int[] indices) {
        int vboID = GL15.glGenBuffers();
        GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);
        IntBuffer int_buffer = toIntBuffer(indices);
        GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, int_buffer, GL15.GL_STATIC_DRAW);
    }

    private FloatBuffer toFloatBuffer(float[] buffer) {
        FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(buffer.length);
        floatBuffer.put(buffer);
        floatBuffer.flip();
        return floatBuffer;

    }

    private IntBuffer toIntBuffer(int[] buffer) {
        IntBuffer intBuffer = BufferUtils.createIntBuffer(buffer.length);
        intBuffer.put(buffer);
        intBuffer.flip();
        return intBuffer;

    }

    private void unbindVAO() {
        GL30.glBindVertexArray(0);

    }

}

```

Shader.java:

```
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.lwjgl.opengl.GL20;

public class Shader {
    private final int programID;
    private int vertexID;
    private int fragmentID;

    public Shader(String keyVertex, String keyFragment) {
        programID = createProgram();
        vertexID = createVertexShader(keyVertex);
        fragmentID = createFragmentShader(keyFragment);
    }

    public int createProgram() {
        int id = createProgramShader();
        if(id==0) {
            System.err.println("Cannot create shader");
        }
        return id;
    }

    public int createVertexShader(String key) {
        int id = createShader("shaders/" + key + ".vs", GL20.GL_VERTEX_SHADER);
        if(id == 0) {
            System.err.println("Error creating Vertex Shader");
        }
        return id;
    }

    public int createFragmentShader(String key) {
        int id = createShader("shaders/" + key + ".fs", GL20.GL_FRAGMENT_SHADER);
        if(id == 0) {
            System.err.println("Error creating Fragment Shader");
        }
        return id;
    }

    public void link() {
        GL20.glLinkProgram(programID);
        GL20.glValidateProgram(programID);
    }

    public void bind() {
        GL20.glUseProgram(programID);
    }

    public void unbind() {
        GL20.glUseProgram(0);
    }

    public void cleanUp() {
        GL20.glDetachShader(programID, vertexID);
        GL20.glDetachShader(programID, fragmentID);
        GL20.glDeleteShader(vertexID);
        GL20.glDeleteShader(fragmentID);
        GL20.glDeleteProgram(programID);
    }

    public void bindAttribute(int attribute, String variableName) {
        GL20.glBindAttribLocation(programID, attribute, variableName);
    }

    private int createProgramShader() {
        return GL20.glCreateProgram();
    }

    private int createShader(String key, int type) {
        StringBuilder shaderSource = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(key));
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        String line;
        try {
            while((line = reader.readLine())!=null) {
                shaderSource.append(line).append("\n");
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            reader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        int id = GL20.glCreateShader(type);
        GL20.glShaderSource(id, shaderSource);
        GL20.glCompileShader(id);
        if(GL20.glGetShaderi(id, GL20.GL_COMPILE_STATUS) == 0) {
            System.err.println(key + ": Shader compilation error: " + GL20.glGetShaderInfoLog(id, 1080));

        }
        GL20.glAttachShader(id, programID);
        return id;
    }

}

```

And here are the shaders..

vertexShader.vs:

```
#version 400 core

in vec3 positions;

out vec3 pass_pos;

void main(void) {
    gl_Position = vec4(positions, 1.0);
    pass_pos = vec3(positions.x, 1.0, positions.z+0.05);
}

```

fragmentShader.fs:

```
#version 400 core

in vec3 pass_pos;

out vec4 out_Color;

void main(void) {
    out_Color = vec4(pass_pos, 1.0);
}

```

# Answer
Spotted error:

```
GL20.glAttachShader(id, programID);

```

Should be:

```
GL20.glAttachShader(programID, id);

```

And,

```
GL30.glVertexAttribIPointer(slot, 3, GL11.GL_FLOAT, 0, 0);

```

Should be:

```
GL20.glVertexAttribPointer(slot, 3, GL11.GL_FLOAT, 0, 0);

```
> 1 votes

---
Tags: opengl, java, shaders, lwjgl
---


title: Record voice and play in unity?

text:
# Question
Title: Record voice and play in unity?
i wanted to ask that does unity3d support audio record and playback option and if it does, how is it possible to just speak and the application will record the sound and play it back after a little interval say 2 seconds???

# Answer
You can do this with the class `Microphone`.

Here is a simple example copied verbatim from the documentation of `Microphone.Start`:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Start() {
        AudioSource aud = GetComponent<AudioSource>();
        aud.clip = Microphone.Start("Built-in Microphone", true, 10, 44100);
        aud.Play();
    }
}

```

Note that this example requires an Audio Source component on the game object you have that script on. The settings of that audio source are used for playing back the recording.

I am also not sure if `"Built-in Microphone"` is guaranteed to exist on every system. When it doesn't work for you, try replacing it with `Microphone.devices[0]` to use the first available recording device. For a real game you likely want to have a setting in your options menu where the user can choose which device from the `Microphone.devices` array they want to use.
> 1 votes

---
Tags: unity
---


title: C SDL render text?

text:
# Question
Title: C SDL render text?
I'm making a game in C using SDL library and I want to display a score. I have 9 photos with numbers from 0-9 and I want to know if I can use them somehow to display score, if my score is 2679 the game should use the photos 2 6 7 and 9 and display them realtime, can this be possible? Or how should I display the score?

# Answer
> 0 votes
There are a few ways to do this. What I would personally do is to use the SDL\_TTF library to load a font and use it to render your score. You also get full text rendering support at the same time, so instead of only rendering the score ("2679") you can add a title to it ("Score: 2679").

If you are set on using your own digit sprites, you need to load the images and split the score to individual digits. My C is a little rusty but something like the following should work for mapping the digits:

```
SDL_Texture* textures[10];

char filename[16];
for (int i = 0; i < 10; i++)
{
    sprintf(filename, "image_%d.png", i);
    textures[i] = SDL_CreateTextureFromSurface(IMG_Load(filename));
}

```

The code loads images from the root folder in the format of "image\_number.png".

Now all is left is to render the score number:

```
int score = 2679;

SDL_Rect dest;
dest.x = 500;
dest.y = 0;
dest.w = 16;
dest.h = 24;

while (score)
{
    int digit = score % 10;
    score /= 10;

    // Renders the digit.
    SDL_RenderCopy(renderer, textures[digit], NULL, &dest);

    // Moves so that the next digit will be at the correct position.
    dest.x -= dest.w;
}

```

The way of iterating over the digits in the number is from this SO answer. The code above iterates over the digits, and renders the corresponding texture to the correct spot, and then moves to the number left to the previous number. You can yourself add some padding there.

As you can perhaps see, the way of manually rendering the digits requires more work and currently only gives you support for some digits (with the idea I've shared). SDL\_TTF gives you all this, and more.

---
Tags: sdl, c
---


# Question
Title: Received email that iOS development Certificate was revoked, what is it mean?
I'm trying to make a .ipa in Xcode from the build of my project file exported in unity3d. There was two errors in Xcode which are 1."Signing for "Unity-iPhone" requires a development team. Select a development team in the project editor. 2. Code signing is required for product type 'Application' in SDK 'ios 10.1' that I'm resolving so I tried to search in google on how to resolved it. We have already an apple developers account so I set it as the "development team" (step from the tutorial I saw) then when I'm trying to test the solution I did from Product-\>Archive in Xcode, I received the email and I think it prevent me from making a .ipa file.

I'm not still sure why I received that email. Based from my research, some say that it means I can not longer able to submit updates to the App Store for my application. Can somebody please help me on the reasons why.

Thanks in advance!

# Answer
When trying to fix your signing issues, Xcode did ask you if you want Xcode to revoke the Certificate for you, which you accepted.

As a result, you have to download the new certificate and add it your KeyChain (by doubble clicking it). Also, all provisioning profiles created with the old certificate became invalid, so yo have to recreate all provisioning profiles and use them.
> 2 votes

---
Tags: unity, xcode, appstore, build-process
---


# Question
Title: Use an object's x position to seek within an animation
I have an animation clip I want to play, using the object's x position to control which frame of the animation is displayed. ie.

* When the object is at x = -2, the animation should show its initial frame.
* As the object moves rightward (increasing x) the animation should play forward.
* When the object is at x = 6, the animation should show its final frame.
* As the object moves leftward (decreasing x) between these values, the animation should play in reverse.

I thinks this is a form of clamping where I want to map x values into key frames of the animation.

Below just a simple code to run animation:

```
void Update () {
    if (isPositionChanging)
    {
        if(transform.position.x > xPos){
            if(incrementOrDecrement <=12) {
            incrementOrDecrement ++;
            AnimationPlayOnPositionValue(1, incrementOrDecrement);
            }
        }
        else {
            if (incrementOrDecrement >= 0)
            {
            incrementOrDecrement--;
            AnimationPlayOnPositionValue(1, incrementOrDecrement);
            }
        }

    }
}

void AnimationPlayOnPositionValue(float speed,float timeToUpdate) {
    animatedObject["MachineAnimationComplete"].speed = speed;
    animatedObject["MachineAnimationComplete"].time = timeToUpdate;
    animatedObject.Play();

}

```

# Answer
Here's a quick example using the AnimationClip.SampleAnimation method:

```
public class SampleByPosition : MonoBehaviour {

    public AnimationClip animationClip;

    // Direction in which a change in position should advance the animation.
    public Vector3 direction = Vector3.right;

    // Distances from the origin along this direction,
    // corresponding to the beginning & ending frames of the animation.
    public float start = -2;
    public float end = 6;

    // Cache previous frame time to avoid redundant work.
    float _previousT = float.NegativeInfinity;

    void Start () {
        // Normalizing the vector ensures our dot product below
        // returns distances in worldspace units, for ease of use.
        direction.Normalize();
    }

    // Animate in LateUpdate to include any motion in preceding Update.
    void LateUpdate () {

        // Calculate an animation time value from the object's position.
        float t = Vector3.Dot(transform.position, direction);
        t = animationClip.length * (t - start) / (end - start);

        // If this is the same time value we used last frame, bail out early.
        // (Sampling an animation has some performance cost, so if the frame
        //  we used recently is still valid, don't re-calculate it)
        if (Mathf.Approximately(t, _previousT))
            return;

        // Apply this moment of the animation to our host GameObject.
        animationClip.SampleAnimation(gameObject, t);

        // Cache the time value to compare against next frame.
        _previousT = t;
    }
}

```

Since we don't want to animate over time, but directly control the playhead in the clip, I skipped the Animation component entirely. If you want to blend multiple animations, the Animation.Sample method is better-suited - it's just a bit more verbose to set up if you only need a single clip.
> 1 votes

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


# Question
Title: Converting back and forth between spherical and cartesian coordinates in glsl
I have checked all the possible resources and I still don't know why my code is not working.

This code should convert uv (texture coordinates) or cartesian into spherical and back. But my code still can't convert the values back properly, even though it is the same as under that link: http://mathworld.wolfram.com/SphericalCoordinates.html

```
#ifdef GL_ES
precision mediump float;
#endif

#extension GL_OES_standard_derivatives : enable

uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;

const float PI = 3.14159265359;

vec2 toUV(vec3 n)
{
    vec2 uv;

    uv.x = atan(n.y, n.x);
    //uv.x = atan(n.y / n.x);   // Doesn't work either
    uv.y = acos(n.z);

    return uv;
}

// Uv range: [0, 1]
vec3 toSpherical(vec2 uv)
{
    float theta = 2.0 * PI * uv.x;
    float phi = PI * uv.y;

    vec3 n;
    n.x = cos(theta) * sin(phi);
    n.y = sin(theta) * sin(phi);
    n.z = cos(phi);

    // x, y, z range: [-1.0, 1.0]
    return n;
}

void main( void ) {
    // Range from 0 to 1
    vec2 p = gl_FragCoord.xy / resolution.xy;

    vec3 color = vec3(0.0);

    // The point of a sphere with radius 1.0
    vec3 n = toSpherical(p);

    // The cartesian coord
    vec2 uv = toUV(n);

    color = vec3(uv, 0.0);

    // uv should be p by now
    //color = vec3(p, 0.0);

    // Showing the color
    gl_FragColor = vec4( color, 1.0 );

}

```

To view this code, you can just paste everything into this site's editor http://www.glslsandbox.com/e

Any help would be appreciated.

# Answer
I hope this will be useful to anyone struggling with a similar problem.

The phrase one should look for is geographic or map projection.

Though I've found a different way to convert between these systems, I was playing around with the ranges and found a solution somehow. However, I wish someone could explain why this works.

'toPolar' converts a unit sized square to the surface of a unit sized sphere placed in origo. 'toUV' is the inverse function.

Full code here: (after many conversions the range is still kept) http://glslsandbox.com/e#37633.0

Important functions:

```
const float PI = 3.1415926535897932384626433832795028841971693993751058209749;

vec2 toUV(in vec3 n)
{
    vec2 uv;

    uv.x = atan(-n.x, n.y);
    uv.x = (uv.x + PI / 2.0) / (PI * 2.0) + PI * (28.670 / 360.0);

    uv.y = acos(n.z) / PI;

    return uv;
}

// Uv range: [0, 1]
vec3 toPolar(in vec2 uv)
{
    float theta = 2.0 * PI * uv.x + - PI / 2.0;
    float phi = PI * uv.y;

    vec3 n;
    n.x = cos(theta) * sin(phi);
    n.y = sin(theta) * sin(phi);
    n.z = cos(phi);

    //n = normalize(n);
    return n;
}

```
> 1 votes

---
Tags: mathematics, coordinates, uv-mapping, sphere
---


# Question
Title: What do I need to consider before making any class singleton?
I am sure most of my classes like for rendering text, sprite, shapes are not going to need more than one instance. Is it adequate to consider only this fact that its only going to need one instance? Should i also consider other things?

# Answer
> 13 votes
Do you think you don't *need* more than one or do you think there *must never be* more than one?

The singleton pattern is mostly useful in situations where the existence of more than one instance of a certain class isn't just unnecessary but would actually cause bugs, so you want to avoid at all cost that there ever is a second instance of it.

Also consider the alternative to a singleton: A purely `static` class, which in C++ can alternatively be implemented as a `namespace`. This is usually far easier to use and write and results in far more readable code. The main drawback is that you can't have a pointer or reference to a namespace. But I could hardly think of a situation where you would want that and where a singleton would still make sense.

# Answer
> 4 votes
The book Game Programming Patterns (which you can read free online) has a good overview of considerations for when to use / avoid singletons.

The cautionary advice boils down to:

* A singleton is a global variable, with all the trouble that comes with it: (this also applies to static classes)

+ Increasing the complexity of reasoning about your code, because now any two pieces of code that touch this singleton can indirectly affect each other, no matter how disparately they're separated in your code base.
    + Encouraging coupling between two systems. You probably want the SpriteRenderer.RenderSprite() method called only by your main render loop. But by putting it in a singleton, it's accessible anywhere, making it easy for a junior programmer to shortcut the intended flow of rendering and, say, try to render an impact sprite in a collision handler - now your physics and rendering are coupled, even if you had a neat messaging system that could have avoided the coupling. (We have a habit of reaching for whatever tool seems most direct, and singletons are very direct!)
    + Opening up to concurrency problems. Many modern games are multi-threaded, and a singleton is accessible to every thread, without knowledge of what the other threads are doing with it. This makes it easy to introduce bugs, or increase your code complexity with additional locks and checks.
* Singletons solve multiple problems (convenient access, enforced uniqueness, lazy instantiation), when maybe we only needed to solve one. The extra features we didn't need can trip us up later.

+ A common problem is to implement a singleton for convenient access early in a project when you only need one, so the uniqueness isn't a problem or a feature, just an inoffensive side-effect. If later you have a use case for multiple (eg. going from a single instance of Player to a multiplayer mode) then you have a lot of refactoring on your hands. (This is in line with Philipp & UnholySheep's advice: are you sure you *never* want more than one?)
    + Lazy instantiation means the heavy work of constructing an instance could happen at an inopportune time in your game (eg. if you spin up your stat reporting service the first time the player picks up a collectible, it could cause a hitch in gameplay). If you know you'll need exactly one of these at all times, it might as well be a static class (or namespace as Philipp points out) so you skip any added complexity of a singleton, and your code is explicit about what's happening.

Check the article for some alternatives that may get the functionality you need without the singleton baggage. Singletons aren't necessarily bad, but the case you describe doesn't sound like one that needs a singleton solution.

---
Tags: c++, software-engineering, design-patterns
---


# Question
Title: Handling mouse input depending on selected unit and clicked tile
I am making a turn-based tactical game (think something like X-Com) and I am currently trying to figure out how to handle mouse input in a clean way without a mess of if-statements.

I have a lot of variables that come into play and that changes what happens when you click a tile in the game.

For example: if the currently selected unit is a player controlled unit and the tile you click is within that units movement range, I want to queue up a move action. If the clicked tile contains another player character I want to select that one instead, but if it contains an enemy I want to select the enemy or attack it if the player is adjacent.

So basically what happens when you click depend on selectedUnit, clickedTile, clickedTile.getUnit().getType(), and if the selected units tile is a neighbour to the clicked tile.

Is there a cleaner way to handle this than a mess of if-statments? I am using Java and Libgdx if that matters, but I am guessing this is mostly a design question.

# Answer
> 0 votes
Since you are trying to avoid if statements, have you considered implementing the InputProcessor class?

```
@Override
public boolean keyDown(int keycode) {
    if (keycode == Input.Keys.BACK || keycode == Input.Keys.ESCAPE) {
        // Go back code
    } // other keys
    return false;
}
...

```

---
Tags: java, libgdx, input, selection
---


# Question
Title: Coordinates of the corners of a rectangle bridging two circles
I am implementing a game that involves slingshots and circular objects. I have gotten the basic "geometric" construction down for rendering the slingshot, but I am having trouble implementing this in my game (written in js, although any language explanations will be understood). Below is a diagram of the desired construction:

I know (cx, cy), which is the center of the circle I am "launching", the radius of that circle, and the position of the mouse at any given time (mx, my). The second circle around (mx, my) includes the same radius as the circle centered at (cx,cy). Lines ST and QP are parallel.

I must find the coordinates of points P, Q, S, and T. Any efficient approaches to this problem? (Would I use trigonometry, vector math, algebra?) Specific examples are appreciated. Thank you.

# Answer
> 2 votes
This is pretty straightforward:

```
travel = mousePosition - center

travelDirection = normalize(travel)
// ie. travel * 1 / sqrt(travel.x^2 + travel.y^2)

perpendicular = (travelDirection.y, -travelDirection.x) * radius

P = center + perpendicular
Q = center - perpendicular
S = mousePosition - perpendicular
T = mousePosition + perpendicular

```

(+ and - might need to be exchanged depending on the handedness of your coordinate system)

---
Tags: mathematics, vector, geometry, trigonometry
---


title: Help with Transform Path

text:
# Question
Title: Help with Transform Path
I have a 2D square. It has an initial position translation T0. It rotates about the Z axis, about an arbitrary point, say 45 degrees, then moves (translates) along the +X axis some distance.

I'm trying to put together the 4x4 homogeneous transform (this example is only 2D but the problem is really in 3D) to move the square but I seem to be missing something, and I get odd results.

T0 := initial translation to some point T1 := center of rotation point Rz := rotation Matrix about Z and about point located at T1 T2 := additional translation TF := final transform p := a vertex of the square to rotate If I use the following sequence -

TF = T2 * T1 * Rz * T1^-1 * T0

I can rotate about T1 as long as T2 is (0,0).

If I use only T0 - by combining T0 and T2 - it rotates correctly but it moves along the rotated X axis rather than the original X axis.

So, it seems I can

Transform first and get the rotation correct but not the translation OR Transform last and get the translation correct but not the rotation.

example:

move to 10,10 rotate about 9.5, 9.5 move -5,0

It seems there should be a way to get my desired result, but I seem to be missing something.

Thanks

Rick

# Answer
is this the transform you require for
move to 10,10 rotate about 9.5, 9.5 move -5,0:

```
rot = 45 degrees
trans1 = vec(10.0,10.0,0.0)
trans2 = vec(-5.0,0.0,0.0)
rot_point = vec(9.5,9.5,0.0)

translate(trans2) *
translate(rot_point) *
rotatez(rot) *
translate(trans1 - rot_point)

```
> 1 votes

---
Tags: animation, rotation, transformation
---


title: Why is my enemy kill code not working?

text:
# Question
Title: Why is my enemy kill code not working?
I'm trying to make an enemy for my game, and everything works, except for the bit of code where the enemy is supposed to die.

My player attacks but nothing happens.

I filled in the prefabs, I have the right tags, I tried remaking it and I can't find anything that is wrong.

---

What am I doing wrong?

```
#pragma strict
var EnemyItself : GameObject;
var EnemyCorpse : GameObject;

function OnTriggerEnter(other : Collider) {
    if (other.gameObject.tag == "Hero Punch") {
        EnemyItself.SetActive(false);
        EnemyCorpse.SetActive(true);
    }
}

```

# Answer
> 1 votes
As previously pointed out, through comments, there is nothing wrong with your code. Assuming you have referenced the game objects and are using tags correctly, the only thing left appears to be your rigidbody.

This also seems to be the confirmed issue, in the comments.

---

Collision events require *at least* one of the game objects to contain a `RigidBody` component. Ideally, these would be on the *moving objects*, and we would not have a situation where *two non-moving objects* enter a collision event.

It is also worth mentioning that you need to use `RigidBody` for 3D collion events, where 2D collision events will require a `RigidBody2D`.

---
Tags: unity, unityscript
---


# Question
Title: How do I set a scene up for two players?
I´m finishing a game in Unity, but I have a new requirement: make it multiplayer. I will do this by splitting the screen and running two instances.

Is there a way to instance a scene twice at the same time, and render them two a different part of the screen? Alternativley, what is the best approach to achieve this?

# Answer
If you want to make a local multiplayer with a split screen, the way to go is to have two cameras and change the rect viewport of them :

https://docs.unity3d.com/ScriptReference/Camera-rect.html

For vertical split screen : (x, y, width, height)

* 1st camera : (0, 0, 0.5, 1) ► left
* 2nd camera : (0.5, 0, 0.5, 1) ► right

For horizontal split screen : (x, y, width, height)

* 1st camera : (0, 0.5, 1, 0.5) ► top
* 2nd camera : (0, 0, 1, 0.5) ► bottom

---

No need to have two worlds. However, if you want the players to have their own GUI, you will have to take a look at culling masks

https://docs.unity3d.com/ScriptReference/Camera-cullingMask.html

Place all the objects of the player 1 in a new layer ("Player1Layer"), all the objects of player 2 in another ("Player2Layer"), and make sure the camera of the player 1 does not have "Player2Layer" checked in its culling mask while the camera of the player 2 does not have "Player1Layer" checked in its culling mask.

# IMPORTANT NOTE

It seems that additional configuration is required so as to show GUI to a specific player. I don't really know why.

Each player must have their own :

1. Main camera with :

* Correct viewport rect
    * A `Depth` value set to 0
    * A culling mask to `Everything`, except `Player1Layer` and `Player2Layer`
2. A second camera with :

* Correct viewport rect
    * A `Depth` value set to 1
    * A culling mask to `Player1Layer` (or `Player2Layer` for 2nd player)
3. A dedicated canvas with :

* Render Mode set to Screen Space - Camera
    * The correct camera configured in #2

For the sake of simplicity, attach the two cameras of a given player to a unique parent, and move the parent so that the two cameras will follow. Maybe, you can keep the cameras #2 at (0, 0, 0). I haven't tested.
> 11 votes

---
Tags: unity
---


# Question
Title: What are the advantages of using SAT(seperating-axis theorem ) in collision detection?
Lets say i need to check if two AABBs are colliding with each other. I would simply compare their corners. When am i gonna need SAT(heavy vector calculations) to do the same thing?

# Answer
SAT is for convex polygons, AABB is for axis aligned bounding boxes (obviously). If you only have the latter ones, then you don't need to use SAT, but if you need something that's more precise, then SAT is the way to go (polygons can enclose objects more precisely, though it requires you to make them manually or use some sort of algorithm to generate them)

Usually AABB is used for the broad phase, and SAT is for the narrow phase.
> 3 votes

---
Tags: collision-detection, game-mechanics, vector, bounding-boxes
---


# Question
Title: How to sync animations of 2 different characters in Unity 3D?
I am working on an endless running 3d game. I have 2 characters. One of them is a small kid and another one is a security guard. Both characters and animations are exported as separate FBXs.

The scene is something similar to the situation in Subway Surfer, where the cop picks up the character. See first few seconds - https://www.youtube.com/watch?v=FdxgHMh0QEc

For this we animated both the characters in a single file in 3DS Max. In this file one character has to pick other character by his leg.

Now how should I proceed so that both the animations play in sync when shown in the game. What would be the best approach to sync different characters in Unity when using different files ? Or should I export a single file containing both the characters and animations and use it just for this scene?

Any help would be really appreciated. Thanks in advance.

# Answer
> 1 votes
This is a bit old, but still relevant.

The best way of managing animation in Unity is to always consider each "actors" as their own. In this case, consider the cop as a separate entity than the kid or whatever that get grabbed by the feet.

The best way of doing this is by doing it when using 3dsMax is through the following steps.

Step One, make sure you're using 2 animation layers when animating. It's something that can be done with both CAT and Biped, but slightly different in terms of how it's done. The Layer 1 act as the "Movement" on the X and Z axis. (If Y is upward) The Layer 2 act as the Rotation/Limb layer.

Step two, on layer 1, you place the character at their relative position as to what it would be in the game. On layer 2, you manage the body's movements (Like the cop crouching a big to grab the kid's leg or something). Ideally, make sure that one of the 2 characters is in the center/origine of the world (like the cop) and take note of the position of the kid before he get taken up by the leg. Once the animation is done, save a copy (in case you need to access it again). delete the layer 1. This is will bring both the cop and kid at the X & Z origin.(They will both be in the center of the 3dsMax scene.)

Step three, you export both the Cops and the Kid (and their relative bones/armature) in separate FBX file. Each should be separate entities in Unity.

Step four, in Unity, create each their own animator with the relevant states.

Step five, when the cop has to grab the kid's leg, adjust the positions (and movement) in Unity so that the same distance and orientation (as used in the layer 1 in 3dsMax which I suggested to take note of). This requires that you program the animation in synch with the in-game movement. (In other words, movement of the legs are based on the movement in the world that translate into the animator parameter.) then, when the cop tries to grab the kid and if it's successful, a call is sent to the kid's animator to start the "get grabbed" animation. This part has to be one in multiple animations part : Cop has the part where it tries to grab. Then it has the 2 possibilities of successfully grab or failing to grab. Then it has the lift up or the recover animation (based on the results) and then whatever you want. The kid might have an evade (if close to get grabbed) and a "being grabbed" (that start at the same time as when you start the cop's "Successful Grab" animation) and a "Grabbed" for when the cop is holding the kid's leg.

the easiest way of managing this is to always consider that there's 1 master script and 1 subordinate scripts depending on who got the upper hand. It also important to understand how to make both script communicate together efficiently so that calls and parameters can easily be transmitted from one to the other.

---
Tags: unity, animation, 3dsmax, skeletal-animation, synchronization
---


# Question
Title: SDL_RenderDrawLines isn't drawing complete geometry
So I am trying to draw hexagons with \[`SDL_RenderDrawLines`\]\[\]. It looks to be working fairly well, however, it fails to draw some of the lines.

So each of the hexagons in the screenshot is a hex object. They each have a center x/y , and an array of SDL\_Points for the six corners of the hex.

Here is the hex object draw call:

```
SDL_RenderDrawLines(
    TheGame::Instance()->getRenderer(),
    corners,
    HEX_NUMBER_OF_CORNERS);

```

There is some reoccurring condition that causes a vertical line to not be rendered, and I can't seem to figure out why.

The two obvious things that stand out don't explain why there is no line:

1. The draw order of the objects shouldn't matter since all of the borders for each hex are being drawn.
2. The horizontal distance between adjacent hexes' centers can be +-1 because of rounding would lead to a double thick border and not a missing border.

If anyone has any insight, I welcome the input.

**EDIT:**

I have been over suggestions you have mentioned prior to this question, increasing the array of points to 7 is correct, I tested it on a triangle before I tried with hexagons. When you don't close of the shape, you typically get drawn lines that shoot off the edge of the screen.

The part on three lines is also something else I discovered while messing around. I included some of my code to show the two ways that I preformed the very thing you mentioned:

```
// render the hexagon to on screen
void Hex::draw()
{/*
 draw order of points
 rotate ccw 90 degrees for actual postion
  [2] ____ [3]
     /    \
[1] /      \
    \      / [4]
     \____/
  [0]    [5]
 */

    // draw the hex with a fill color
    // 0XAABBGGRR is the bit order for the color param
    filledPolygonColor(
        TheGame::Instance()->getRenderer(),
        vx, vy,
        HEX_NUMBER_OF_CORNERS, r_order(CLEAR));

    // set outline color to black
    SDL_SetRenderDrawColor(
        TheGame::Instance()->getRenderer(),
        0, 0, 0, 255);

    // draw the hex outline

    //SDL_RenderDrawLines(
    //  TheGame::Instance()->getRenderer(),
    //  corners + 2,
    //  HEX_NUMBER_OF_CORNERS - 2);

    // or
    SDL_RenderDrawLine(
        TheGame::Instance()->getRenderer(),
        corners[2].x, corners[2].y,
        corners[3].x, corners[3].y);
    SDL_RenderDrawLine(
        TheGame::Instance()->getRenderer(),
        corners[3].x, corners[3].y,
        corners[4].x, corners[4].y);
    SDL_RenderDrawLine(
        TheGame::Instance()->getRenderer(),
        corners[4].x, corners[4].y,
        corners[5].x, corners[5].y);
}

```

Just for clarity, it still occurs in spots where there should be a drawn line. This is a shot with the above code:

# Answer
The reason why I was able to do this in the stand alone project but not have similar results is because I am using `SDL_RenderSetLogicalSize`. I am not using some crazy size though, which I find kinda odd that it is having issues.

```
SDL_RenderSetLogicalSize(renderer, 1920, 1080);

```

As soon as I change the resolution to something smaller than this it works fine.

> 1536 x 864 was the highest 16:9 resolution that worked
> 1 votes

# Answer
According to the documentation for SDL\_RenderDrawLines:

> **Function parameters**
>
> **count** the number of points, drawing count-1 lines

`SDL_RenderDrawLines()` doesn't presume that you have a closed shape; it's just drawing lines between the points you've provided. So with 6 points (as per your `HEX_NUMBER_OF_CORNERS` constant), you get just five lines, drawn between the set of points you've specified in order

If you wish to draw all six lines around each hexagon, then you'll need to provide an array of seven points, duplicating the first corner also as the last point in the array, and then pass a count of `7` to `SDL_RenderDrawLines()`.
> 1 votes

---
Tags: sdl, sdl2, hexagonal-grid
---


# Question
Title: How do you do tile-based movement in Phaser?
I'm looking to make 2D game that is very similar in movement to Pokemon Red or Blue (player must move a full tile in any direction, the ground moves smoothly beneath the player as they walk). I've got my hands on Tiled in order to make my maps, and I've got a player sprite that I can display over the map, but I can't seem to find a way to restrict the player to moving the way I want.

I feel like there should be some parameter for Arcade physics to make the movement the way I want, but I'm not finding it. Abandoning Arcade physics and manually changing the X/Y of the player with a loop kinda works, but can be very slow and laggy, making me think I'd need to look into the Time and Tween parts of Phaser to actually implement it correctly.

So did I miss something with Arcade Physics to do this? Or do I need a really good tutorial on Tween to manually code this myself?

# Answer
The player should have a position, that can be any number, and a target position. When the current position is equal to the target position, check the input, and set the new target position accordingly.

When the target position doesn't equal the current position (e.g. the player just started moving) move the current position closer to it.

Make sure the interpolation between the tiles is quick or else the player will get really frustrated with the controls.
> 3 votes

---
Tags: movement, phaser, tiles
---


# Question
Title: What are some common FOV for third person games?
I am trying to decide on a field of view (FOV) for a third person game and I really don't know where to start. It would be very helpful to have some points of reference from recent TPS games and the FOV they use by default. The trouble is many third person games (or at least those I have tried) do not have any settings or information about what their default FOV is. I have had a look at Uncharted 4, Hitman (2016), The Division and GTA 5 but cannot find information about their FOV anywhere.

I understand that each game is different and the type of gameplay will determine the FOV choice here, but it would be very useful for me to have some existing examples as a starting point. Is there any good place to find this out?

# Answer
I seem to use 75, 80, 115 and 125 degrees horizontally, for 1, 2, 3 and 4 (lined up) monitors respectively; rendering large outdoor scene. It's user-configurable (.ini file) and requires a re-start if changing. This solution/selection is only one of many possible.

It depends on your scene. Make it look good!

A too wide FOV causes restless movement and erratic sizes at left & right outer edges and stretches the center area inwards the screen in an innatural way. Otoh, if a racing game, that gives an good impression of fast movement.

A too narrow FOV gives a binocular effect, where a small mouse movement/camera direction change causes the scene to be restless and hard to control.

You can solve from this:

```
tan(fovY / 2) = tan(fovX / 2) / aspectratio

```
> 1 votes

# Answer
Found it! It takes a bit of digging, but this website shows the default FOV settings for many games, including third person ones: http://pcgamingwiki.com/wiki/Category:Games

This is what I was looking for as a point of reference.
> 0 votes

---
Tags: camera, third-person-view
---


# Question
Title: XNA draw a rectangle 3D perpendicular to camera
I need some ideas how to implement the `Draw` method.

Need to draw a rectangle (actually a million of them, all same texture) that is in 3D, starts at point `p` and ends at point `q` and is always perpendicular to the camera. So, it is impossible for me to go around it and see how flat it really is. The points `p` and `q` are marked on the texture.

# Answer
> 2 votes
This can be done many ways, here I'll give you non language or engine specific answers.

The first way to do it is useful, if you don't want to or can't use shaders, you need to get the angles of the vector that goes from the object to the camera and set the angles of the rectangle to the results. If you have a `lookAt` function by any chance, then just use that to make the object look at the camera.

The second solution works if you create shaders, and is way more effective, because the CPU is not the most well suited for these kinds of operations.

When you move the vertex in the vertex shader, you usually multiply it with a modelview matrix (if you have a separate model and view matrix, just multiply them together in the view -\> model order). If you look at how the rotations are coded in this matrix:

you can see that the rotations utilize the top-left 3x3 area of the 4x4 matrix. To remove rotations, you need to set these to

```
1 0 0
0 1 0
0 0 1

```

Then you can use the resulted matrix.

---
Tags: xna, .net, rendertexture
---


# Question
Title: Is there a term for lore about a game world's population (cultures, economic state, etc.)?
The lore of a game, the ethnicity of its population, cultures, economic state or anything which illustrates the population of a game.

Are all these things part of the lore? Or are they called the story of the game?

# Answer
"Lore" is a very broad phase. For example, let's take the Elder Scrolls games. They have a lore which describes almost everything. The gods, the history, the people and races, the population and the regions are also part of it.

If something is used to describe the way and reason how the world functions, then it's part of the lore.
> 2 votes

---
Tags: terminology, npc, world-design
---


title: SDL TTF render variable

text:
# Question
Title: SDL TTF render variable
This is the way I render the score in my main game , and I made this new project to understand how to use it... It works , the score is updated and it display on the screen but the problem is memory... it increase forever , from 20mb when I start untill it runs out of memory..it nevers stop. And in the main game it's working at 2fps... I hate TTF I just can't understand how it works and how should I do it... every tutorial is in c++ and I have to make the game in pure C for college...Help.

```
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_image.h>

int main(int argc, char ** argv)
{
    bool quit = false;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    SDL_Window * window = SDL_CreateWindow("Example",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
    SDL_Surface * surface;
    SDL_Texture * texture;

    int score = 0;
    char buffer[50];
    int texW = 0;
    int texH = 0;
    TTF_Font * font = TTF_OpenFont("font3.ttf", 25);
    SDL_Color color = { 255, 255, 255 };

    while (!quit)

    {
        SDL_RenderClear(renderer);

        SDL_WaitEvent(&event);
        switch (event.type)
        {
        case SDL_QUIT:
            quit = true;
            break;
        }

        score += 100;
        sprintf(buffer, "SCORE: %d", score);

        surface = TTF_RenderText_Solid(font, buffer, color);
        texture = SDL_CreateTextureFromSurface(renderer, surface);
        SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);

        SDL_FreeSurface(surface);
        SDL_Rect dstrect = { 0, 0, texW,texH };
        SDL_RenderCopy(renderer, texture, NULL, &dstrect);

        SDL_RenderPresent(renderer);
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_DestroyTexture(texture);
    TTF_CloseFont(font);

    TTF_Quit();
    SDL_Quit();

    return 0;
}

```

# Answer
> 0 votes
It's been a while since I've done any SDL but I think your problem is here: `texture = SDL_CreateTextureFromSurface(renderer, surface);` You're creating a texture and then never freeing it.

If you dig into the SDL2 source code you'll find that in SDL\_render.c an SDL\_Texture gets allocated on the heap every time you call SDL\_CreateTexture\* (`texture = (SDL_Texture *) SDL_calloc(1, sizeof(*texture));`)

What will probably solve your leak, and save some frames, would be to only update the texture when the score updates and to free the existing texture before you allocate a new one.

```
if (prevScore != currentScore)
{
  SDL_DestroyTexture(scoreTexture);
  //Create new score texture
}

//Regardless of score change, render the score

```

---
Tags: sdl, sdl2, ttf
---


# Question
Title: How to catch basic system events (such as input) in Linux/C++
As old and as standard as Linux/C++ is now, I would imagine there's an efficient method, even a library or three, for something as elementary as catching system events.

The types of events I need are things like:

* **GUI**: Window resizing, moving, ...
* **IRQ**: Inputs (Keyboard/Mouse), USB, ...
* **FS**: Node operations, r/w, ...
* Anything similar, Shutdown, log out, ...

I know:

* /dev/input/\* can be polled
* Udev ...
* Xorg can be polled
* IRQ Handlers ...

Most of these are either inefficient and/or require certain environments, (Xorg, Udev, etc.) IRQ Handlers are efficient, but are good for only one type of event.

**Game engines have to be especially efficient with these, in particular inputs, for the sake of FPS loops.** If anyone can provide implementation details for inputs, that would suffice and be appreciated.

What is the efficient method I'm looking for? What is commonplace? If I have to build it myself, where do you suggest I start? What tools would I need?

> So, to clarify, applications have always had to do this one way or another right? Web browsers, game engines, desktop environments, etc, have all had to gather input and other events efficiently. "How is that?" I'm asking. Is it unreasonable to expect an established OS/PL for practical API(s)? Of course not!

# Answer
> Game engines have to be especially efficient with these, in particular inputs, for the sake of FPS loops. If anyone can provide implementation details for inputs, that would suffice and be appreciated.

In fact, receipt of the events you're talking about is generally *nowhere near* the bottleneck for a game. So we generally do not need to do anything particular clever or special or low-level to handle them. Generally, in fact, we just use whatever mechanism is provided for us on whatever platforms we're building for. This is fairly straightforward on Windows and macOS, which have standard GUI APIs that provide ways to listen for nearly all of the event types you listed.

For Linux, which does not have a hard standard GUI library, it's somewhat more complicated, but only by virtue of having potentially many APIs to choose from. One could directly write against Xlib, if one chose, although I'd venture to guess that most people would rather write against the APIs provided by Qt or GTK these days instead. The ease-of-use provided by the higher-level abstractions offered by the likes of Qt vastly overpower the insignificant "perf cost" of using such an abstraction, because (again) handling events is not a bottleneck for most games.

Certainly these days very games bother directly concerning themselves with IRQs or any other driver-level interrupt event. It's not worth the price of admission.

> What is the efficient method I'm looking for? What is commonplace? If I have to build it myself, where do you suggest I start? What tools would I need?

Fundamentally you need to simply need to choose which GUI system you're going to use to build your game. SDL? Qt? GTK? There are many choices available and providing guidance as to which *you* should choose is out-of-scope for this site. They can all fulfill the basic task of giving you a window onto which you can paint your game graphics (with OpenGL or the like) and hook up the receipt of any sort of input event you might want.

Pick one that seems to work with your engineering style and go for it; this will cover most of your listed types of events (window-related ones and input-related ones). It's not necessarily true that a GUI API will also provide filesystem access APIs, but many do. If not you can simply pick an appropriate API according to your needs. For example if all you need is basic file IO, the C++ standard library will suffice. If you want something that leverages the OS's asynchronous file IO capability, you will need to use the OS's API or some wrapper around it. Similarly if you need filesystem-watch events (which isn't super common), you may need to use something like the `inotify` API.
> 1 votes

---
Tags: c++, input, events, linux
---


# Question
Title: Calculate Relative Mouse Movements Regardless of position
**Context**

I'm working on making a variant of the atari game Breakaway IV and I'm trying to improve my mouse input handling.

I use the input of a mouse's motion left and right to move the bumper.

```
public void mouseLocationChanged(Point mouseLocation) {
    if (lastMouseLocation == null) {
        lastMouseLocation = mouseLocation;
        return;
    }
    bumperStep = (int) ((mouseLocation.x - lastMouseLocation.x) * SENSITIVITY_MULTIPLIER);
    lastMouseLocation = mouseLocation;
}

```

Then in the update method of my game I check if there is a bumper movement queued up.

```
 public void update() {
    if (inputHandler.isBumperMove()) {
        submitBumperMove(inputHandler.getBumperMove());
    }
    ...
}

```

If there is, I move the bumper with the below code.

```
public void submitBumperMove(int move) {
    if (move < -1 * BUMPER_SPEED_LIMIT) {
        move = -1 * BUMPER_SPEED_LIMIT;
    } else if (move > BUMPER_SPEED_LIMIT) {
        move = BUMPER_SPEED_LIMIT;
    }

    testPoint.x = bumper.x + move;
    testPoint.y = bumper.y;

    while (testPoint.x != bumper.x) {
        if (!willCollideWithWall(bumper, testPoint)) {
            bumper.x = bumper.x + move;
            if (bumper.hasBall){
                ball.x = ball.x + move;
            }
        } else {
            move = shrinkStep(move);
            testPoint.x = bumper.x + move;
        }
    }
}

```

**Observed bugs**

1. I don't reset `bumperStep` with the call to `getBumperMove()` so the cursor drifts if there isn't a different input to set `bumperStep` to 0. This mainly happens when the mouse exits the window.
2. When resetting `bumperStep` to 0 with `getBumperMove()` (making it `consumeBumperMove()`) the mouse can run out of the window before the bumper reaches the edge of the game and the bumper can't be moved to the edge.

**Proposed Solution**

I was considering resetting the mouse cursor in the center of my window (with the cursor invisible) while the game is in "play" mode with each game update. This would prevent the problem of the mouse leaving the screen and not working while still allowing me to consume the movements which will stop the drifting bumper I'm observing.

**Questions**(finally ;-) )

1. Is there a better approach to getting mouse left and right movements from any position in java, or should I stick with just keeping the cursor where I want it?
2. If locking the cursor is the way to go, how can I pragmatically set the mouse position in Java? I've heard about a `Robot` class that is supposed to help, but it looked like an application needs special signing/permission to use that.

# Answer
> 2 votes
1. If you want to find out the mouse position, even if the mouse is outside of the window, you can use the MouseInfo class of AWT:

```
int mouse_x = MouseInfo.getPointerInfo().getLocation().x
int mouse_y = MouseInfo.getPointerInfo().getLocation().y

```

But I would recommend you to fix the position of the mouse inside your window. Otherwise, you will run into another problem, like the mouse will reach the screen border.

Fixing the mouse inside the game window is a common concept to prevent the mouse leaving the screen. A lot of games place it in the middle of the game window, hide it and add an image of a new mouse which shows the in game mouse position while the desktop mouse is kept in the middle. You can see this effect when you tab out of a game and your desktop mouse is visible again. It is mostly placed in the middle of the window instead of the game mouse location.

2. If you want to force the mouse to a position without any additional native libraries, you can use, as you mention it, the Robot class:

```
if(myJFrame.isFocused()){
  int mouse_x = myJFrame.getLocation().x + myJFrame.getWidth() / 2;
  int mouse_y = myJFrame.getLocation().y + myJFrame.getHeight() / 2;
  robot.mouseMove(mouse_x, mouse_y);
}

```

This will place the mouse in the middle of the window and also gives the user the mouse control back if the window gets unfocused. But as you mention also, the Robot class needs on some system special permissions to change the mouse position.

I highly recommend you to use a game library such as LibGDX or at least a native adaptation like LWJGL (which is used by LibGDX) if you want to create a game in Java. Problems like this are easy solved with these libraries.

In LibGDX you can use the setCursorCatched function. It will hide your mouse and fix it in the middle of your window. X and Y coordinates of your mouse are still reported as if the mouse was not caught:

```
Gdx.input.setCursorCatched(true);

```

If you want to catch your mouse in the LWJGL library, you can use the following method:

```
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

```

---
Tags: java, mouse
---


title: OpenGL application, not working on AMD.

text:
# Question
Title: OpenGL application, not working on AMD.
Recently,

I moved an app I am building from a computer with Intel & Nvidia to a computer with AMD CPU & GPU.

The problem is, that glDrawElements gives me bad access location and I can't figure out why.

The render function is the following:

```
template<class PositionData> void drawTexturedMesh(const PositionData &pd, const IndexedFaceMesh &mesh, const unsigned int offset, const float * const color, GLuint text)
{
  // draw mesh
  const unsigned int *faces = mesh.getFaces().data();
  const unsigned int nFaces = mesh.numFaces();
  const Vector3r *vertexNormals = mesh.getVertexNormals().data();
  const Vector2r *uvs = mesh.getUVs().data();

  // Update our buffer data passed to GPU
  glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
  glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(double) * 3 * pd.size(), &pd.getPosition(0)[0]);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
  glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(double) * 2 * mesh.getUVs().size(), &uvs[0][0]);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
  glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(double) * 3 * mesh.getVertexNormals().size(), &vertexNormals[0][0]);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // Binding element array and drawing. numFaces * 3 triangles per face.
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(unsigned int) * mesh.getFaces().size(), mesh.getFaces().data());

  glDrawElements(GL_TRIANGLES, 3 * nFaces, GL_UNSIGNED_INT, BUFFER_OFFSET(0));

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

```

Math, vectors and matrices are from Eigen. Any ideas or any other code part you would like to see? Bare in mind that this exact code works fine with nVidia.

Thanks.

# Answer
> 4 votes
**This is caused by your use of double-precision**.

In short, GPUs just don't like double-precision; the hardware support for it is just not there to the same degree as for CPUs.

A good (if slightly dated) overview may be read at http://arrayfire.com/explaining-fp64-performance-on-gpus/; I'll quote the opening paragraph because it explains things perfectly, but you can read it all if you're interested in further details.

> GPUs are really good at doing math. The Achilles heel is when it comes to 64-bit double precision math. GPUs, at least consumer grade, are not built for high performance FP64. This is because they are targeted towards gamers and game developers, who do not really care about high precision compute. So vendors like NVIDIA and AMD do not cram FP64 compute cores in their GPUs.

So when you provide double-precision numbers to a GPU, one of the following may happen, depending on how old the GPU is, how good the drivers are, whether it's a consumer-grade or workstation GPU, and perhaps other factors:

1. It will work in hardware but it will be slower.
2. It will drop you back to software emulation (and be *much* slower).
3. It won't work.

In the ideal world only (1) or (2) would happen, but driver quality being what it is, (3) is possible.

That's not to say that potentially bad AMD drivers are the actual cause in your case. If we review the documentation for glVertexAttribPointer, we'll see that there are actually two variants available:

* glVertexAttrib**I**Pointer: use with integer data types.
* glVertexAttrib**L**Pointer: use with double-precision.

It may very well be the case that simply switching to glVertexAttrib**L**Pointer is sufficient to resolve things for you (in which case NVIDIA and Intel are doing a format conversion that AMD is failing to do).

**Where to go from here**.

Review your use of doubles, because - despite what you might think - you almost certainly don't need them.

* You are very unlikely to need doubles for your UVs, which will typically be in a 0..1 range. Single-precision will work.
* You definitely don't need doubles for your normals, which are in the -1..1 range, unless you're doing something like passing unnormalized normals with crazy-high values.

That leaves positions, and unless you're drawing absolutely huge scenes, you don't need doubles for your positions either. In fact you'll probably run out of depth buffer precision before this becomes a factor (there are no 64-bit depth buffer formats on current hardware or APIs). A good overview is at http://www.gamasutra.com/view/feature/131393/a\_realtime\_procedural\_universe\_.php?print=1 and I'll quote:

> ...if the smallest unit you care about keeping track of is a millimeter, you start to lose accuracy around 1,000 km with floats and around 1 trillion km with doubles.

So single-precision is sufficient to represent scales of 1:1,000,000,000.

**Conclusion**

* Review your use of doubles because you most probably don't need them. Typically using doubles is a good indicator that you've actually got a problem that may be better solved by switching to alternative algorithms.
* If you absolutely must use doubles then ensure that you're using the correct API: glVertexAttrib**L**Pointer rather than glVertexAttribPointer.
* Having the end result run unacceptably slow or just not work at all is something that you may just have to accept.

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


# Question
Title: Is A* suitable for this particular case?
I have a 2D map of nodes a train could travel. They are not in a grid. The node positions are placed by a designer and exported to a JSON file which the game loads to display the node positions on the map texture/sprite.

I'm tying to implement pathfinding for the train. The user can select a node and set a waypoint to that node. The game should find the shortest path and take that (avoiding locked nodes).

The way the nodes are set up right now is that each node has other neighbour nodes. There's the condept of a 'link' which connects two nodes. Nodes do not store any neighbour information in them, instead they're stored in the links which are stored separately (a list of links, each link contain two integers representing the linked nodes' ids)

The train has no restriction on its movement it could move from A-\>B or B-\>A, only restriction is that it doesn't move to the previous node it came from. So going from A-\>B, when asking B of its neighbours, we exclude A and look at the other neighbours.

I hope that's enough context to answer my question: Is A\* applicable to me? If so, I'm not really sure how to write a function to generate weights/costs on nodes. I just can't seem to answer the question of: What's the total distance between A-\>B in order to assign costs/distances? Because there could be more than one path to go from A-\>B, which requires path-finding in itself (see the infinite loop in my logic?). If A\* is not the best here, what is?

**\[EDIT\]** Replying to Matt's answer. I thought of using distances to calculate the weights/costs but take this example for instance:

Where's at 'P' trying to go to 'T'. Edge/link 'A' is shorter than 'E' but if we take the 'A' route it would be longer in the long run. I would have to travel both the paths to determine which distance is shorter, otherwise how do I know? am I missing/misunderstanding something here?

Another question is, how do I track paths/links/nodes that I shouldn't visit anymore? I can't just mark a node as 'visited' once I visit it the first time because there could be a branch in there and I have to visit it twice to know which one is shorter, correct?

**\[EDIT\]** I guess in the first case^, it would be benefecial to also do the pathfinding backwards from 'T' to 'P' then pick which ever is the shortest between going P-\>T and T-\>A?

# Answer
A\* can be used to solve this problem. The search starts from your start node, and then scores all adjacent nodes. The cost of each adjacent node is the actual cost of getting to that node (the link distance) plus an estimate of how far you have left to go. This estimate must not overestimate the true cost - for this problem, you can use the straight-line distance between points.

Now you have a cost for all nodes adjacent to the start node. Pick the lowest-cost node, and repeat, scoring all nodes adjacent to that one (score = the running total of the link distance + distance remaining estimate). If you want to speed up the search, disallow backtracking. Keep doing this, and you will find the optimal path from A to B.

For your example in the bottom half of the question, keep in mind that A\* has no way of knowing the optimal path a priori, so it will likely explore routes that are later discarded. In fact, you may wind up exploring every possible path and finding the optimal one last. All A\* guarantees is that you WILL find the optimal path, not that you will find it quickly. The search relies on heuristics, which usually speeds things up, but it isn't guaranteed.

From a programming point of view, one way to implement A\* is using two lists of nodes, called the open list and the closed list. The open list is your "frontier" of visited nodes that you haven't expanded yet - that is, you haven't looked at where you can get to from there. The closed list is nodes you have visited and expanded. The open list starts with the start node, and the closed list starts empty. Take the lowest-scoring node on the open list, expand it, and add all adjacent neighbors to the open list. If a node is on the closed list, don't re-open it, and if it's already on the open list, keep the new one if you have found a better (lower-scoring) path. Then move the current node to the closed list. Repeat until you expand the destination node and move it to the closed list. You only have to expand each node once, since you only keep the shortest path to any particular node.
> 1 votes

---
Tags: path-finding
---


title: Tile set showing grid with lighting

text:
# Question
Title: Tile set showing grid with lighting
Hi so I have this tile set generated procedurally at the start of the scene. When I activate the point light in the middle of the screen I keep getting this grid in the game view, i tried changing the size of the tiles but no luck if I change them before pressing play in the game view. But if I do it at run time from the inspector the bug goes away , hiding the square of the tile that I have moved...for that tile in particular even just moving it a bit solves it. This happens in edit and game mode ,and the grid is made of loads of sprites put together. The import settings of these sprites is dont generate mip maps, no compression. And each of the tiles have the default shader sprite diffuse. I deactivated gizmos but no luck either

Any idea what can this be ? anything related with baking the light or something? thank you for your help!

# Answer
> 1 votes
The tiles are generated too close, and they cover the edges of each other resulting in brighter areas at those intersections. Try generating the tiles a bit further apart.

---
Tags: unity, lighting
---


title: SDL Detect change score

text:
# Question
Title: SDL Detect change score
I have this in my loop , it works but I get verry low fps and game is working in slow motion :

```
while (!done)
    {
        //Check for events
        done = processEvents(window, &player);
        updateLogic(&player);

        sprintf(buffer, "SCORE: %d", player.currentScore);

        textSurface = TTF_RenderText_Solid(font, buffer, color);
        text = SDL_CreateTextureFromSurface(renderer, textSurface);

        SDL_QueryTexture(text, NULL, NULL, &textW, &textH);
        SDL_FreeSurface(textSurface);

        doRender(renderer, &player);
        SDL_DestroyTexture(text);
    }

```

I think I need to update those 2 only when score is changing , not every frame..and I don't know how to do it.

```
textSurface = TTF_RenderText_Solid(font, buffer, color);
text = SDL_CreateTextureFromSurface(renderer, textSurface);

```

# Answer
> 2 votes
So the way I would approach this is by adding an additional member `bool ScoreChanged` to your player instance, and set it when you change the score. An alternative approach would be to save the score at the end of your main loop and compare it against the current value before rendering.

Anyways, once you have that setup, all you need to do is to render the texture. This means that you want to move the initial texture creation and declaration outside of your mainloop. Once you detect a score change, render the surface and translate it to the texture. Remember to destroy to previous texture. Also don't forget to reset the `ScoreChanged` value, if you went with that approach.

For a larger project you might want to consider caching your prerendered textures of text to a global stash, but something like the above should work just fine here.

---
Tags: sdl, c, sdl2
---


# Question
Title: Are environments built in external applications or in Unity?
Totally new to game development here– I know models are never built in Unity, but what about environments? Is it common to say, build an office building environment with hallways and doors (sans furniture and props) in Blender and import that into Unity and assemble the scene there?

# Answer
> 2 votes
For general questions I hope general answers are okay, I do like to rant and I assume GameDev is probably more relaxed than the other stack exchanges.

Generally all "hard surface" 3D models in a game today environmental or otherwise are created in a 3D modeling application such as 3DSMax, Maya, Blender, or Zbrush.

The common exception to this is terrain generation. Game engines like Unity tend to include a tool for creating and deforming very large ground plane meshes that are tailored to perform well and include features like texture blending. Once you learn about UV unwrapping, you'll understand that a special shader is usually required for terrain, since the textures are usually several different textures tiling and alpha-blended together, often based on a height map.

The other less common exception is any case where meshes are being generated programatically.

In the past engines did rely on built in tools to make a lot of geometry out of adding and subtracting primitives. I am no expert, but my gut feeling is that doing things that way helped integrate an engine's binary space partitioning calculations. Source and Unreal 3 are both engines that did this. These are your "brushes" in Hammer. https://developer.valvesoftware.com/wiki/Brush

Today almost everything is a static mesh, enabled due to vast performance improvements across the board. Killing Floor 2 for example, despite being built in Unreal 3, is constructed entirely of modular stage segments/slices. Tripwire has built in their own custom functionality to merge those meshes to make that system practical.

If you're interested in gamedev, want to make 3D games alone, and don't have money to spend, I can tell you Blender is a very powerful tool. However, learning any 3D modelling application is a serious undertaking and you should look for a structured resource to learn from, either a paid online video course or a book. While you can learn a lot from Google, these applications are highly contextual and easy to get lost (and even lose progress in) unless you understand the big picture of what's going on in all their little windows.

---
Tags: unity, blender
---


# Question
Title: How do you retrieve assets that have been stored by UUID?
I'm designing my assets, and thinking about using a UUID or a name for accessing them. I decided to use UUIDs for identifying them and for storing/accessing the cache, but what if I want to get/use an asset in my script? Do I have to know the UUID of the asset? Having a name identifier will help, but this should also be unique, so I don't know if it's a good idea having both identifiers in the asset.

This seems unintuitive; I have always accessed them by name, like this:

```
// before:
TextureCache *tc = ...
auto texture = tc->get("Mario");  // (more intuitive)

// now:
TextureCache *tc = ...
auto texture = tc->get(234242423424234);  // (not intuitive)

```

How do you retrieve assets that have been stored by UUID?

# Answer
> 3 votes
One way of doing this is to just have a `const unsigned int TEXTURE_MARIO` which stores the UUID, this can be generated either at load or at compile time.

That way you still have the advantage of not doing a comparison with a string constantly, combined with the readability of not having random numbers in your code. If you do generate the variables list at compile time a decent compiler will generate the same code as if you had the numbers inline.

# Answer
> 2 votes
My recommendation is to not reference specific assets so directly in your scripts.

There's a lot of reasons. One is that this breaks the ability for your tools or diagnostic helpers to see which assets are in use; they have to execute game code to see what assets get loaded, and since your scripts can generate a literally infinite number of strings/names, there's no way to be exhaustive.

A stronger approach is to use *resource tables*. These are basically just resources that list other resources, potentially with some other metadata. For example, a drop loot table might be a list of item ids and weights used in the random selection. The drop loot table resource would then be referenced by the monster resource that drops that loot. The script code would do something like `drop_random(dead_monster.loot_table)` rather than having a unique loot code or list of strings/resources of its own.

This approach can drive almost every single part of your game: spawns are resources referenced by the map, character classes are resources referenced by the player creation resource table, and so on.

The only resource that ever needs to be hard-coded is the main "boot" resource. That is the resource that contains the references to your splash screens, your main scripts, etc. Because there's just one of those it's a lot easier to special case in all your tools. In fact, loading it might even just be a single function that's compiled into all the tools from the same source code.

For your example, you'll probably want a `StartupResource` of some kind, maybe defined like:

```
struct StartupResource {
  TextureHandle mario;
  LevelHandle first_level;
};

```

Then your startup function would look more like this:

```
StartupResource* startup = load_startup_resource(); // only place you ever hardcode a resource name

TextureCache *tc = ...
auto texture = tc->get(startup->mario); // intuitive, data-driven, toolable

```

---
Tags: c++, architecture, assets
---


# Question
Title: LibGDX: Google Play Game Service (Dec 2016) - Cannot call Games class
I'm trying to include Google Play Game Services in my Android game and I tried adding BaseGameUtils library. But it is not really working.

I can call the `GameHelper` class from `AndroidLauncher` but not the `Games` class for getting leaderboards.

I also have this warning in my console: **(which does not interfere with the actual problem - see the answer)**

```
project ':android': Unable to resolve additional project configuration.
Details: groovy.lang.MissingPropertyException: Could not find property 'main' on SourceSet container.

```

Can somebody give any insight to this problem?

This is my android gradle: http://pastebin.com/ya85gGs4

And this my BaseGameUtils gradle: http://pastebin.com/0iyz2j12

Also the root gradle: http://pastebin.com/in2MmYMM

When I check Project Structure -\> Problems, I have these messages:

**EDIT:** I have tried changing android support library, appcompat and google play services to different versions including the latest ones but this error keeps pissing me off.

---

**PS:** Please feel free to edit the title. I put the date because I wanted to imply that this is a recent issue.

# Answer
> 0 votes
I spent the last 2 weeks trying to find a solution to this and it turns out I was using a 32-bit version of IntelliJ. All I had to do was to use the 64-bit program which is available in the same directory. ~~But I don't know how this solved the problem.~~ It's possibly because of the JRE used by the 32bit IDE. The 64bit IDE uses the java we installed while the 32bit one uses the java that's shipped with IDEA as mentioned here.

I got the solution from another entirely different error debugging. They should have provided me with a better warning/error message. I stumbled on this problem while I was changing the JDK version in Maven settings of IntelliJ.

**EDIT:** I may have to mention that even now, the warning

```
project ':android': Unable to resolve additional project configuration.
Details: groovy.lang.MissingPropertyException: Could not find property 'main' on SourceSet container.

```

is still present. It is indeed caused by the inclusion of `BaseGameUtils` library but it does not interrupt getting the necessary library files.

---

## tl;dr

Use `idea64.exe` in `C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.3.2\bin` instead of `idea.exe`

---
Tags: android, libgdx, google-play-services
---


title: Creating puzzle on libGDX

text:
# Question
Title: Creating puzzle on libGDX
Good afternoon. Help me please to add the code for the game. This game is puzzle. Everything works good, but I would like to have not just ordinary puzzles with numbers, but also the puzzle with a picture. Could you tell me how I can insert a picture ant divide it into parts? Thanks in advance for any help.

```
package com.frastan.puzzletestgame3.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.frastan.puzzletestgame3.Application;
import com.frastan.puzzletestgame3.actors.SlideButton;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;

public class PlayScreen implements Screen {
private final Application app;
private Stage stage;
private Skin skin;
private int boardSize = 4;
private int holeX, holeY;
private SlideButton[][] buttonGrid;
private TextButton buttonBack;
private Label labelInfo;
public PlayScreen(final Application app){
    this.app = app;
    this.stage = new Stage(new StretchViewport(Application.V_WIDTH,Application.V_HEIGHT,app.camera));
}

@Override
public void show() {
    System.out.println("PLAY");
    Gdx.input.setInputProcessor(stage);
    stage.clear();
    this.skin = new Skin();
    this.skin.addRegions(app.assets.get("ui/uiskin.atlas", TextureAtlas.class));
    this.skin.add("default-font", app.font24);
    this.skin.load(Gdx.files.internal("ui/uiskin.json"));
    initNavigationButtons();
    initInfoLabel();
    initGrid();

}
private void update(float delta){
    stage.act(delta);
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1f,1f,1f,1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    update(delta);
    stage.draw();
}

@Override
public void resize(int width, int height) {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

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

private void initNavigationButtons(){
    buttonBack = new TextButton("Back", skin, "default");
    buttonBack.setPosition(20, app.camera.viewportHeight - 70);
    buttonBack.setSize(100, 50);
    buttonBack.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y){
            app.setScreen(app.mainMenuScreen);
        }
    });
    stage.addActor(buttonBack);
}
private void initInfoLabel(){
    labelInfo = new Label("Welcome! Click any number tile to begin!", skin, "default");
    labelInfo.setPosition(20, 350);
    labelInfo.setAlignment(Align.center);
    labelInfo.addAction(sequence(alpha(0f), delay(.5f), fadeIn(.5f)));
    stage.addActor(labelInfo);
}
private void initGrid(){
    Array<Integer> nums = new Array<Integer>();
    for(int i = 1; i < boardSize * boardSize; i++){
        nums.add(i);
    }
    nums.shuffle();
    holeX = MathUtils.random(0, boardSize - 1);
    holeY = MathUtils.random(0, boardSize - 1);
    buttonGrid = new SlideButton[boardSize][boardSize];
    for(int i = 0; i <boardSize; i++){
        for(int j = 0; j <boardSize; j++){
            if(i != holeY || j != holeX) {
                int id = nums.removeIndex(0);
                buttonGrid[i][j] = new SlideButton(id + "", skin, "default", id);
                buttonGrid[i][j].setPosition((app.camera.viewportWidth / 7) * 2 + 51 * j,
                        (app.camera.viewportHeight / 5) * 3 - 51 * i);
                buttonGrid[i][j].setSize(50, 50);
                buttonGrid[i][j].addAction(sequence(alpha(0), delay((j + 1 + (i * boardSize)) / 15f),
                        parallel(fadeIn(.5f), moveBy(0, -10, .25f, Interpolation.pow5Out))));
                buttonGrid[i][j].addListener(new ClickListener(){
                    @Override
                    public void clicked(InputEvent event, float x, float y){
                        int buttonX = 0, buttonY = 0;
                        boolean buttonFound = false;
                        SlideButton selectedButton = (SlideButton) event.getListenerActor();
                        for(int i = 0; i < boardSize && !buttonFound; i++){
                            for(int j = 0; j < boardSize && !buttonFound; j++){
                                if(buttonGrid[i][j] != null && selectedButton == buttonGrid[i][j]){
                                    buttonX = j;
                                    buttonY = i;
                                    buttonFound = true;
                                }
                            }
                        }
                        if(holeX == buttonX || holeY == buttonY){
                            moveButtons(buttonX, buttonY);
                            if(solutionFound()){
                                labelInfo.clearActions();
                                labelInfo.setText("Solution Found!");
                                labelInfo.addAction(sequence(alpha(1f), delay(3f), fadeOut(2f, Interpolation.pow5Out)));
                            }
                        } else {
                            labelInfo.clearActions();
                            labelInfo.setText("Invalid Move!");
                            labelInfo.addAction(sequence(alpha(1f), delay(1f), fadeOut(1f, Interpolation.pow5Out)));
                        }
                    }
                });
                stage.addActor(buttonGrid[i][j]);
            }
        }
    }
}
private void moveButtons(int x, int y){
    SlideButton button;
    if(x < holeX){
        for(; holeX > x; holeX--){
            button = buttonGrid[holeY][holeX - 1];
            button.addAction(moveBy(51, 0, .5f, Interpolation.pow5Out));
            buttonGrid[holeY][holeX] = button;
            buttonGrid[holeY][holeX - 1] = null;
        }
    } else {
        for(; holeX < x; holeX++){
            button = buttonGrid[holeY][holeX + 1];
            button.addAction(moveBy(-51, 0, .5f, Interpolation.pow5Out));
            buttonGrid[holeY][holeX] = button;
            buttonGrid[holeY][holeX + 1] = null;
        }
    }
    if(y < holeY){
        for(; holeY > y; holeY--){
            button = buttonGrid[holeY - 1][holeX];
            button.addAction(moveBy(0, -51, .5f, Interpolation.pow5Out));
            buttonGrid[holeY][holeX] = button;
            buttonGrid[holeY - 1][holeX] = null;
        }
    } else {
        for(; holeY < y; holeY++){
            button = buttonGrid[holeY + 1][holeX];
            button.addAction(moveBy(0, 51, .5f, Interpolation.pow5Out));
            buttonGrid[holeY][holeX] = button;
            buttonGrid[holeY + 1][holeX] = null;
        }
    }
}
private boolean solutionFound(){
    int idCheck = 1;
    for(int i = 0; i < boardSize; i++){
        for(int j = 0; j < boardSize; j++){
            if(buttonGrid[i][j] != null){
                if(buttonGrid[i][j].getId() == idCheck++){
                    if(idCheck == 16){
                        return true;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    }
    return false;
}
}

```

# Answer
> 1 votes
Libgdx provides `Texture` and `TextureRegion` classes that should do what you need.

A `Texture` is a handle to the entire image. One way to load it is

```
Texture dogTexture = new Texture(Gdx.files.internal("path/to/dog.png"));

```

and a `Texture` is drawn using a `Batch`

```
//x,y,width and height are where and how big the texture is drawn in your world
batch.draw(dogTexture,x,y,width,height);

```

A `TextureRegion` is just what it sounds, it is just a smaller part of a texture. It is created like this

```
//x,y,width, and height are coordinates on the texture where you want to cut-out the texture region
TextureRegion dogRegion = new TextureRegion(dogTexture,x,y,width,height);

```

and a `TextureRegion` can be drawn the same way as a whole texture

```
batch.draw(dogRegion,x,y,width,height);

```

So, you will want to create a `TextureRegion` for each `SlideButton` which corresponds to the part of the texture that the button should be displaying.

Then, you should draw the whole texture for the hint picture near the top of the game.

# Answer
> 0 votes
For you if statement, the button manipulation code is a bit redundant, what I would recommend is to make another void class:

```
public void ModifyHole(SlideButton button, int yMod, int xMod){
    button = buttonGrid[holeY+yMod][holeX + xMod];
    button.addAction(moveBy(51*xMod*(-1), 51*yMod*(-1), .5f, Interpolation.pow5Out));
    buttonGrid[holeY][holeX] = button;
    buttonGrid[holeY + yMod][holeX + xMod] = null;
}

private void moveButtons(int x, int y){
    SlideButton button;
    if(x < holeX){
        for(; holeX > x; holeX--){
            ModifyHole(button, 0,-1);
        }
    } else {
        for(; holeX < x; holeX++){
            ModifyHole(button, 0,1);
        }
    }
    if(y < holeY){
        for(; holeY > y; holeY--){
            ModifyHole(button, -1,0);
        }
    } else {
        for(; holeY < y; holeY++){
            ModifyHole(button, 1,0);
        }
    }
}

```

This helps so that if you need to change the code for the manipulation, it'll affect all the if-statements.

Also you have a lot of magic numbers.

I'm not 100% sure what the 15 represents, though I think it is how far each block needs to move so something like:

```
private final int MOVE_DISTANCE = 15;

```

Same thing for when you check if the game is solved.

```
private final int SOLVED_TILES = 16;

```

Other places would be when you are initializing the board such as width, height, etc. Replace the magic numbers with final variables.

Another thing in the initialization is that you should move the button creation into a separate method so that it is easier to modify for a later date. Breaking code into chunks of code that all work together makes life easier and helps when going back to edit it.

---
Tags: java, libgdx, puzzle
---


# Question
Title: Why is my enemy object shaking in my AI code?
My script here is attached to an 'enemy' object. My enemy walks to certain "points" if the player is far away from him. If the player gets close to him, the enemy follows the player. The problem is that after chasing the player, when he escapes, the enemy should walk back to the "points".

Now I see the enemy object shaking and walking far away from the expected direction?!

```
public class enemyscript: MonoBehaviour {

    public Transform target;
    public Transform[] waypoint; // points
    NavMeshAgent ePath;
    private int farPoint = 0;
    public float elife = 100f,distance,look_range = 20.0f;

    // Use this for initialization
    void Start () {
        ePath = GetComponent<NavMeshAgent>();
        ePath.speed = 2;
    }

    // Update is called once per frame
    void Update () {
        distance = Vector3.Distance(gameObject.transform.position, target.transform.position);

        if (ePath.remainingDistance < 0.5f)
        {
            nextpoint();
        }

        if (distance < look_range)
        {
            attack();
        }
    }

    void attack() {
        ePath.SetDestination(target.position);
        ePath.speed = 6;
    }

    void nextpoint() {
        if (waypoint.Length == 0)
            return;
        ePath.destination = waypoint[farPoint].position;
        farPoint = Random.Range(0, waypoint.Length);
        ePath.speed = 2;
    }
}

```

# Answer
> 1 votes
Even though the description of your problem is pretty unclear (what do you mean exactly by *shaking and walk far from his direction* ?), I can see how your code fails.

In order for the enemies to do these routines, you should add a `state` variable. This state should take 2 values (or more if needed) `PATROL` and `ATTACK`. You can use an enum for this.

Then in your code it becomes easy to deal with the enemy's behaviour

```
if in PATROL mode, check if you need to switch to ATTACK mode, else follow target or find new one.

if in ATTACK mode, check if you need to go back to PATROL mode and then find new target

```

In your code you have implicit states as you change the speed and the target according to the distance from the player, but it seems once you went into "attack" mode, you **never go back to patroling**. If you were using states explicitely it would be pretty easy to track what is happening.

This other topic might prove useful Finite State Machines for Enemies (AI vs. Entity States)

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