# Question
Title: MonoGame "couldn't find a default importer" for .txt file?
I'm trying a solution in MonoGame to create levels from a .txt file, but the pipeline tool fails when trying to build the Content.mgcb correctly:

> ❌ Skipping HighResolutionContent\Backgrounds\Layer1\_0.png
>
> C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Backgrounds/Layer1\_0.png
>
> Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/2.txt'!
>
> Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/0.txt'!
>
> Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/1.txt'!

Visual Studio shows me this:

> ❌ The command `""C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools\MGCB.exe" /@:"C:\Users\foo\documents\visual studio 2017\Projects\Platformer\Platformer\Content\Content.mgcb" /platform:Windows /outputdir:"C:\Users\foo\documents\visual studio 2017\Projects\Platformer\Platformer\Content\bin\Windows" /intermediateDir:"C:\Users\foo\documents\visual studio 2017\Projects\Platformer\Platformer\Content\obj\Windows" /quiet"` exited with code 3.
>
> ❌ Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/0.txt'!
>
> ❌ Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/1.txt'!
>
> ❌ Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/2.txt'!

# Answer
You're getting this message because **the pipeline doesn't contain a content importer for a .txt file**. Plain-text files generally don't require any special processing, and don't need to be converted to a binary format (which is what the content pipeline is for).

There's an option in the MonoGame Pipeline Tool to set the Build Action to "Copy" instead of "Build", which is probably what you're looking for. The file will then be copied as it is. It won't be converted into a .xnb file, and you'll have to read the file manually (not using `ContentManager`).

The content pipeline converts source files into binary .xnb files. It has predefined content importers for most standard audio and image formats that will import the file, process it into an object, and then write the object into a binary .xnb file.

At runtime, when you use a `ContentManager` to load your content, the binary .xnb file gets read and converted into your output type (such as `Texture2D` or `SoundEffect`).

All that's known about a .txt file from it's extension is that it contains text, and all of this importing/processing/writing/reading is unnecessary when something like `File.ReadAllText` exists.

If your .txt file is supposed to represent something that can be converted into an object, such as a game level, you could consider writing your own content importer if you want your .txt file to be converted to an .xnb. The downside of this is that your level files would need to be rebuilt whenever they're modified, but you gain some protection against players that may try to modify `DifficultLevel.txt` to make it easier.

MSDN has a good tutorial on writing your own custom importer, and it's all still relevant in MonoGame, aside from actually getting the MonoGame Content Builder to use your custom importer. I found a reply to a question on MonoGame's forum that helped me figure it out.
> 3 votes

---
Tags: c#, monogame, text, file
---


# Question
Title: How to properly setup unit testing for my c++ game project?
I'm currently creating a 2d game in C++ using visual studio and utilizing gtest/gmock for my testing framework. The problem I'm having is I'm not sure what my best option is for testing. I'm using SDL and opengl and if I try and test normally my test project crashes when it hits any opengl calls. I'm using glew to access opengl so in my game I setup glew and call glew.init() within my window class:

```
void Window::Initialize()
    {
        if (SDL_Init(SDL_INIT_VIDEO) != 0)
        {
            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SDL Error", "SDL did not initialize", nullptr);
            SDL_Quit();
        }

        /** All attributes need to be set before window creation **/

        p_window = SDL_CreateWindow("Shadow Gods", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, SDL_WINDOW_OPENGL);
        if (!p_window)
        {
            LOG("ERROR: SDL window failed to initialize! SDL error: %s\n", SDL_GetError());
            SDL_Quit();
        }

        glContext = SDL_GL_CreateContext(p_window);

        glewExperimental = GL_TRUE;
        if (glewInit() != GLEW_OK)
        {
            LOG("ERROR: GLEW failed to initialize!");

            SDL_GL_DeleteContext(glContext);
            SDL_DestroyWindow(p_window);
            SDL_Quit();
        }

        //Sets the values that the depth and color buffers will be set to when glClear is called
        glClearDepth(1.0);
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    }

```

Now in order to test any of my classes that utilize openGL calls I need to make sure to create a window object first and initialize before calling any other code:

```
#include <gtest\gtest.h>
#include "GameEngine\Window.h"
#include "GameEngine\Sprite.h"

TEST(SpriteClassTest, SpriteInitialize_True)
{
    Blz::Window win;
    win.Initialize();
    Sprite sprite;
    ASSERT_TRUE(sprite.Init(23, 32, 100, 100, "../Game/CharImage.png"));
}

```

I don't want to have to do this for every class that utilizes opengl since 1.) It's redundant and 2.) My tests might be failing because there is something wrong with the window initialize() function instead of what tests were designed for. So is there a better way? If not, how could I get around having to include my "window.h" header in every file and having to initialize the window in every test? Can I do this globally with gtest?

# Answer
> 1 votes
This is mostly a comment, but unfortunately too long to post it as such.

Related: How can I unit test a GUI?

If your test requires you to create a Window, it's not a Unit Test. It might be a useful test, but it's not a Unit Test.

You test your classes by designing them such that if they logically don't require a `Window`, they don't rely on a `Window`. You also design classes such that very few of them logically require a `Window`.

To address your specific example, the example also seems to involve disk access, which is something some (but not all) people put in the same category as creating a Window. The condition of the test is also too little to be of actual use, and the naming of the test isn't at all descriptive, so I'll assume you're somewhat new to Unit Tests. I'll recommend to borrow some books on the topic from a local library, because web articles are too short to properly cover the topic, in my opinion.

---
Tags: opengl, c++, sdl, unit-testing
---


# Question
Title: Make virtual joystick preserve aspect ratio Android in Unity
When I start my game on Android my virtual joysticks stops being round.

Here you can see it:

Here is the project on PC at the same time:

Here are my UI settings for the Joystick:

Please, help me to find a way to preserve the roundness on the Android phone. It feels to me that the solution to the problem is straightforward, but my lack of knowledge prevent me from getting it. What I tried to do is to tweak settings in Editor, in particular I checked preserve ratio on all elements images as you can see on screenshots, but it did not help. I think it did not due to the fact that there is a code executed every time which is this:

```
Screen.orientation = ScreenOrientation.LandscapeLeft;

```

And I think that it changes ratio even though I preserved it in Editor. So, help me out of the problem, please.

# Answer
If you want to specify game orientation, go to `File -> Build Settings -> Player Settings` and there open a tab `Resolution and Presentation`.

Set your desired orientation there:

And delete that line: `ScreenOrientation.something` from your code. I'm 99% sure that it causes all the stretching.
> 1 votes

---
Tags: unity, android, gui, scale, aspect-ratio
---


# Question
Title: SceneManager.LoadScene doesn't seem to be working in Unity IDE
I'm in the start screen scene of my game and I'm trying to load the actual game. I use the following code:

```
public void LoadGame(){
        SceneManager.LoadScene ("Main", LoadSceneMode.Single);
    }

```

I set this method to be called when a button in the UI is clicked. When testing in the game in the unity IDE, clicking the button doesn't do anything. Is my code wrong, is the IDE screwing up, or will clicking the button never do anything in the ide?

# Answer
> 1 votes
Turns out the code works. Here "Main" is the name of the scene and LoadSceneMode.Single is one element of an enumeration. Remember to add all scenes to the build settings.

---
Tags: unity, gui, levels, scene
---


title: How to detect if a key is held?

text:
# Question
Title: How to detect if a key is held?
I am trying to make a dodging game, where objects fall from the top of the window that the player must dodge or collect, depending on whether it is a triangle or a circle. Right now I am doing the layout, and making the moveable icon, which is a smiley face emoji. I am using a `keyListener` to move the icon(using WASD controls). Right now when you want to move the image with the `keyPressed` method you have to press and release the keys, rather than holding them. How can I make the icon move just by holding the keys, instead of pressing and releasing the keys rapidly?

Info: The background is a `JLabel` which the player chooses at the beginning through a `JOptionPane`. All of the background images are in the source folder, and are all 500\*300 pixel jpg's. My application is run on a Mac OS X, if that helps at all.

Thanks, and here's my Program:

```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Dodge extends JFrame {
    private static final long serialVersionUID = 1l;
    String[] backDrops = {"space", "sky", "snow", "rain", "beach", "grass"};
    ImageIcon backDrop;
    String[] options = {"Easy", "Medium", "Difficult"};
    String result;
    String bd;
    int x;
    int y;
    int difficulty;
    int wait = difficulty * 500;
    Graphics g;

    public Dodge() {
        getPreferences();
        layoutGame();
        setTitle("Dodge The Objects!");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void getPreferences() {
        JOptionPane.showMessageDialog(this, "Welcome to Dodge. The rules are simple:"
                + "\n\t\t\t\t1. Choose a level"
                + "\n\t\t\t\t2. Choose a back drop"
                + "\n\t\t\t\t3. Use the arrow keys to move"
                + "\n\t\t\t\t4. Avoid triangles and collect the circles");

          JOptionPane difficultyChoice = new JOptionPane("\t\t\t\t\t\t\t\t\t\t\tChoose your difficulty:",
                JOptionPane.PLAIN_MESSAGE, JOptionPane.YES_NO_OPTION,
                null, options, options[1]);
          JDialog difficultyWindow = difficultyChoice.createDialog(null, "1. Difficulty");
          difficultyWindow.setVisible(true);
          result = (String) difficultyChoice.getValue();
          if(difficultyChoice.equals("Easy")) {
              difficulty = 3;
          } else if(difficultyChoice.equals("Medium")) {
              difficulty = 2;
          } else if(difficultyChoice.equals("Difficult")) {
              difficulty = 1;
          }

          JOptionPane backDropOption = new JOptionPane("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tChoose your back drop:",
                    JOptionPane.PLAIN_MESSAGE, JOptionPane.YES_NO_OPTION,
                    null, backDrops, backDrops[0]);
          JDialog backDropWindow = backDropOption.createDialog(null, "2. Back Drop");
          backDropWindow.setVisible(true);
          bd = (String) backDropOption.getValue();
          backDrop = new ImageIcon(this.getClass().getClassLoader().getResource(bd + ".png"));
    }

    private void layoutGame() {
        JLabel title = new JLabel("Dodge The Enemies!");
        Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
        title.setFont(titleFont);
        title.setHorizontalAlignment(JLabel.CENTER);
        title.setBackground(Color.BLACK);
        title.setForeground(Color.WHITE);
        title.setOpaque(true);
        add(title, BorderLayout.NORTH);

        JLabel background = new JLabel();
        background.setIcon(backDrop);
        add(background, BorderLayout.CENTER);

        x=230;
        y=120;
        JLabel you = new JLabel();
        you.setBounds(x, y, 50, 50);
        you.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("happy.png")));
        background.add(you, JLabel.CENTER);

        JTextPane direction = new JTextPane();
        direction.setText("Direction");
        add(direction, BorderLayout.SOUTH);

        direction.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyChar() == 'w') {
                    y-=2;
                } else if (e.getKeyChar() == 's') {
                    y+=2;
                } else if (e.getKeyChar() == 'a') {
                    x-=2;
                } else if (e.getKeyChar() == 'd') {
                    x+=2;
                }
                you.setBounds(x, y, 50, 50);
                direction.setText("   \t   \t   \t   ");
            }
        });
    }

    public static void main(String[] args){
        try {
            String className = UIManager.getCrossPlatformLookAndFeelClassName();
            UIManager.setLookAndFeel(className);
        }
        catch (Exception e) {}

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Dodge();
            }
        });
    }
}

```

# Answer
> 1 votes
Especially with falling objects, you are going to need to look into something called a "game loop".

What a "game loop" allows you to do, basically, is have actions that are repeated over and over; but unlike a normal loop, it's properly timed to achieve what we mostly know as "FPS" or "Frames per Second" which basically measures how quickly your game loops every second.

Here's a very good resource on game loops: http://www.java-gaming.org/index.php?topic=24220.0

In theory, when you have your game loop, what you will do is set a boolean to true when you press a button like 'w', 'a', 's', or 'd' and in your loop have an if-statement that checks whether one of those booleans are true and then moves your `JLabel` like before.

ex.

```
/* ... */

    direction.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyChar() == 'w') {
                wIsPressed = true;
            }
            // a, s, d
            // ...
        });

/* ... */

    // In game loop
    if (wIsPressed) {
        y -= 2;
    }
    // a, s, d
    // ...

    you.setBounds(x, y, 50, 50);

/* ... */

```

You will also need to have a listener for when a key is released, not just pressed to set those boolean to false.

The KeyAdapter class has a `keyReleased` method to override alongside the `keyPressed`.

https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyAdapter.html

---
Tags: java, swing
---


title: C++ vector Approaches to Octree's

text:
# Question
Title: C++ vector Approaches to Octree's
there, I am making a strategy 3d game somewhat like Global Superpower, its much simpler mechanic wise but im now attempting to make performance improvements, now I am wondering what sort of approach would be good for my game, specifically in the way of moving entities addresses into vectors - that would relate to my Octree's well, stricly speaking its not a true octree, but it is the world divided into 8 Cubes, to reduce collision and unit combat stress instead of searching through the whole vector.

Diagram - of my current approach

There is a problem with this approach, I am struggling to manage pushing and popping the entities onto the vectors as they require a new instance of an entity, not a current entity, I have tried creating something like `vector<entity*>*myaddresses` -but its not worked.

Any idea how I can do it for just addresses or is there a better approach ?

# Answer
Hard to say without more context, but here's my gut feeling as to what your issue is.

You can certainly store a vector of pointers, but

```
vector<entity*>* someVariableName

```

isn't a vector of pointers, it's a pointer to a vector of pointers, notice the second \*. It should be

```
vector<entity*> someVariableName

```

As an aside, if performance is your focus here, I'd recommend storing a vector of small structs which contain your entity pointer, and a copy of some of the most relevant information you're likely to use when searching the octree. For example

```
struct EntityInfo
{
    Entity* myEntity;     // Entity pointer
    BoundingSphere myBounds;
    UnitType myUnitType;  // Type of unit
    PlayerId myOwningPlayerId; // Owner
};

vector<EntityInfo> myContainedEntities;

```

Why? Because ideally if you're writing fast code, you want to avoid repeatedly accessing objects that are scattered around in memory (which is often the case when you're dealing with pointers). If you store a contiguous array of structs containing the most common info that's typically searched for, then you can potentially reject entities without ever dereferencing the entity pointer (and likely incurring the cost of a cache miss).

Obviously you can't optimise every single octree access, but it's something to bear in mind.
> 1 votes

---
Tags: vector
---


title: Unity / Passing an array in a shader

text:
# Question
Title: Unity / Passing an array in a shader
I want to pass my array (which is inside my c# code) to my shader.

```
Shader "custom/shader4"
{
    Properties
    {
        _myArray("Array", Float[256]) = []
    }

    SubShader
    {
        Pass
        {
            CGPROGRAM
            public float _myArray[256];

//code...

```

^this is obviously not working. Is anyone here who knows how to solve this?

(also in c#:)

```
myMaterial.MyArray = anotherArray;

```

It has to be something like this- right? Or do I need a workaround?

# Answer
Since this has too many views, here is the obvious answer:

First you need to assign this in your C# Script:

```
public Material myMaterial;

void Update()
{
//or somewhere else
MyMaterial.SetFloatArray("_FloatArrayNameInsideShader", MyFloatArray);

}

```

Then in your Shader:

```
Shader "Custom/Array" {
     Properties {
...
     }
     SubShader {
         Tags { "RenderType"="Opaque" }
         LOD 200

         CGPROGRAM
         #pragma target 3.0
...

         float _FloatArrayNameInsideShader[3];
 ....

```
> 0 votes

# Answer
As far as I know, you need to use 5.4 Beta in order to do this at the moment.

Take a look at:

http://docs.unity3d.com/540/Documentation/ScriptReference/Material.SetFloatArray.html

Or the other SetArray methods of the Material class, starting from 5.4.

http://docs.unity3d.com/540/Documentation/ScriptReference/Material.html
> 0 votes

---
Tags: unity, shaders
---


title: Why is the movement space increasing?

text:
# Question
Title: Why is the movement space increasing?
This is a follow-up question to my previous question. I got my key holding to move, using `boolean` variables and making another method with a `javax.swing.Timer` for delays(Thank you to KingDolphin), but strangely when I move my Icon it seems to increase how many pixels it moves each time by 1. It moves one pixel the first `keyPressed`, then two for the next, then three, etc. This may not seem like much, but when you are moving by 30+ pixels, it gets out of control. I really have no Idea how to fix it. I have tried changing some things, and I have "done my homework"(Googled and searched StackExchange sites including this one and StackOverflow), but have found nothing even related to it. Here's my `layoutGame` and `move` methods(The problem is in there), and thank you for helping me out:

```
    private void layoutGame() {
        JLabel title = new JLabel("Dodge The Enemies!");
        Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
        title.setFont(titleFont);
        title.setHorizontalAlignment(JLabel.CENTER);
        title.setBackground(Color.BLACK);
        title.setForeground(Color.WHITE);
        title.setOpaque(true);
        add(title, BorderLayout.NORTH);

        JLabel background = new JLabel();
        background.setIcon(backDrop);
        add(background, BorderLayout.CENTER);

        JLabel you = new JLabel();
        you.setBounds(x, y, 50, 50);
        you.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("happy.png")));
        background.add(you, JLabel.CENTER);

        JTextPane direction = new JTextPane();
        direction.setText("Direction");
        add(direction, BorderLayout.SOUTH);

        direction.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyChar() == 'w') {
                    wPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 'a') {
                    aPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 's') {
                    sPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 'd') {
                    dPressed = true;
                    move(you);
                }
                direction.setText(null);
            }
            public void keyReleased(KeyEvent e) {
                wPressed = false;
                aPressed = false;
                sPressed = false;
                dPressed = false;
            }
        });
    }

    private void move(JLabel icon) {
        int delay = 100; //milliseconds
        ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (wPressed) {
                    y = y - 1;
                } else if(aPressed) {
                    x = x - 1;
                } else if(sPressed) {
                    y = y + 1;
                } else if(dPressed) {
                    x = x + 1;
                }
                icon.setBounds(x, y, 50, 50);
                icon.repaint();
            }
        };
        new Timer(delay, taskPerformer).start();
    }

```

# Answer
> 2 votes
The reason for this lies in the way you've implemented the `move` method: in there, you create a new `javax.swing.Timer` object that is responsible for increasing or decreasing the icon's x or y position.

However, note the following:

1. `Timer`s execute their `actionPerformed` method not just once, but indefinitely until they're canceled.
2. You create a new `Timer` object every time a key is pressed.
3. Your timers are never canceled, i.e., they keep running forever.

This means before long, you've created a whole bunch of `Timer`s that all run concurrently and that all increase/decrease your icons position. That's why you see an additive effect. You can see this quite easily if you add the following debug line to the `actionPerformed` method inside `move`:

```
public void actionPerformed(ActionEvent evt) {
    System.out.println("timer " + hashCode() + " running");

```

Now, watch the terminal output while you play the game.

I don't think you actually need a timer at all, you can just move the code that's currently inside `actionPerformed` directly into `move` and the effect will disappear.

(However, an even better tip would be to read up on "game loops".)

---
Tags: java, movement, coordinates, swing
---


title: Avoiding overlapping UI Images

text:
# Question
Title: Avoiding overlapping UI Images
When an enemy dies in my game, it drops an item on the ground. Enemies may drop multiple items. Currently, the item will always drop a set distance directly below the origin of the enemy when it dies. Therefore, if multiple items are dropped, I only see the most recently dropped item on the ground. Moreover, each item has a UI label clamped to some offset distance above the item. As such, I only see the UI label of the "most recently" dropped item. Because every item dropped by an enemy drops at the same physical location, and because I haven't added code to deal with this kind of thing, the physical game objects overlap with each other and the UI labels of those items overlap with each other.

My question is pretty general. What are the best ways to modify my code such that

1) If multiple items are dropped, there will appear to be multiple game objects on the ground (Close enough to the origin)?

2) The UI labels attached to each item will appear as close as possible to that item without overlapping with the other items' UI labels?

I would appreciate direct assistance or references that deal with this kind of thing. Thanks.

# Answer
I would suggest you to keep track of the items that are going to fall when the enemy dies. And if there are more than one, set a little offset between the falling objects and moreover, I would choose an area which is right below the enemy's dead body, and randomly distribute the falling positions of the items in that little area to give it a more realistic look. **Note**: For this solution you need to check that randomly generated positions are not very close ones, in order to make the solution work.
> 1 votes

---
Tags: unity
---


# Question
Title: Flip x when direction of the movement changed in Unity
What is the easiest and the most efficient way to flip x of the `SpriteRenderer` when direction of the movement changed in Unity?

I use `Input.GetAxis()` in order to get user input. When it returns 0 I would like to do nothing, when it returns positive number I would like to have x flipped in SpriteRenderer in one side and when number returned is negative another side.

So far I come up with a solution of using a variable which will be keeping the info about to which side the player is turned and flip x if necessary. But I am sure that this is not an efficient way to do it and even not a convenient one since my code will tend to become a lot bigger and messier.

# Answer
I suggest do not bind the flipping procedure to the `Input` since it is directly relevant to the moving direction of the body (Input may not change the body's moving duration in some specific occasions). Do it by simply checking the **velocity** vector of the **rigidBody2D**.

It can be simply done by 2 ways:

-Either you can check in the moving object's `Update()` loop by simply writing:

```
if(rigidbody2D.velocity.x >= 0){
   spriteRenderer.flipX = false;
}
else {
   spriteRenderer.flipX = true;
}

```

\- Or you can do the same check whatever the function changes the velocity of the body that you are moving.

You can also simplify the code into one line, if you want less lines like the following:

```
spriteRenderer.flipX = rigidBody2D.velocity.x < 0 ? true : false;

```
> 1 votes

---
Tags: unity, input, efficiency, direction
---


# Question
Title: How can I use StringTokenizer instead of array?
I'm currently redeveloping an OBJ & MTL importer for my game engine. At the moment, I'm focusing on increasing how quickly I can parse large OBJ files.

For now, I can parse about 1.2M vertices, uvs and normals in around 4-6 seconds. Which is awesome, considering the file that I'm parsing, couldn't be parsed originally.

Anyways, on with my question; I want to be able to make the following method use a StringTokenizer instead of String array. The reason is because using String.split is slow and I want to parse the file relatively fast.

```
private OBJIndex parseIndex(String token)
{
    String[] tokens = token.split("/");

    OBJIndex result = new OBJIndex();
    result.setVertexIndex(Integer.parseInt(tokens[0]) - 1);

    if(tokens.length > 1)
    {
        if(!tokens[1].isEmpty())
        {
            hasUVs = true;
            result.setUvIndex(Integer.parseInt(tokens[1]) - 1);
        }

        if(tokens.length > 2)
        {
            hasNormals = true;
            result.setNormalIndex(Integer.parseInt(tokens[2]) - 1);
        }
    }

    return result;
}

```

How would I go about doing this?

# Answer
> 1 votes
If you want fast loading times in your game, what engines do is: not using text based data-files (obj, xml ..) on big data like meshes in the first place.

Instead, prepare the data in an offline process, specifically for your engines needs and optimize this instead. In your engines data-exporter tool, read in the obj files and write the optimized data binary. Then there is no parser needed anymore when the game actually starts and runs, it just reads in the binary data directly into its data structures.

Unreal calls this process cooking, other engines have other terms for the same thing. The point is: optimize your engines data formats for fast loading, this excludes text based data formats for big data.

---
Tags: java
---


# Question
Title: set which display on which monitor in unity
I'm working on a project that has multi screen to show environment. the question is options not working when there is multi screen. for example in single screen you can set which screen shows the game but it seems there is not such option.

how can I set which display or which camera get displayed on which monitor in script? for example: camera display 1 to screen 2 and....?

thank you for helping

# Answer
You can set the target display of any camera with the `TargetDisplay` propriety of the `Camera` component.

Via Inspector:

Via Script:

```
Camera camera;

void Awake() {
    camera = GetComponent<Camera>();
}

void CameraTargetDisplay (int target) {
    camera.targetDisplay = target;
}

```

`target` is equal to the display index in the `Display.displays` array.
> 1 votes

---
Tags: unity
---


# Question
Title: How to know if these profiler values are good or bad?
I'm making a 2D game for Android Mobile using LibGDX and Java in Android Studio. My game mostly runs alright with 60FPS, but for some time to time it lowers to 50FPS. I'm trying to find out what causes it. I came across this profiler and implemented it and here are the values in a very "messy" frame with lots of objects going around and messing around:

```
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Calls: 498
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Draw Calls: 37
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Shader Switches: 8
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Bindings: 36
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Vertex Count: 31.945946

```

My question is how am I supposed to know if these are considered to be high values or low? I read the LibGDX documentation but it doesn't give any direction or indication about the values effect. Yes, it might be an opinion-based question, but at least someone can give relevant direction using these values?

Thanks in advance

# Answer
> 2 votes
There are no definitive "bad" or "good" value, but in general fewer calls are better since you spend less time doing what you're doing (e.g. drawing to the screen). The only way to know if your numbers are good or bad is to experiment. Those numbers are not there to give you definitive answers to what's going wrong they're there to help you and to point you in the right direction.

I'll give an example from one of my own prototypes: I profiled my **draw calls** and the **number of objects on screen**. I did this during normal gameplay and when my frames dropped below a certain value. The resulting numbers looked something like this:

```
Low Load
--------
Number of Draw Calls (avg) | Number of Objects (avg) | Type of Object
100                        | 1200                    | Mostly enemies

```

This didn't tell me very much all by itself. But look at the numbers when I experienced lag:

```
High Load
--------
Number of Draw Calls (avg) | Number of Objects (avg) | Type of Object
500                        | 2100                    | Mostly particles

```

Whoa! I didn't even double my amount of objects on the screen but the number of draw calls increased five-fold! This is an indicator that something is wrong. In this case it turned out that my particle batching didn't work as expected which led to necessary flushing of the batch, increasing the amount of draw calls.

This is basically what you have to do. Trial and error, just testing and trying to figure out what could be the cause of the increase. My biggest tip is to profile more than just the raw numbers - profile amount of objects and what type of objects you're dealing with. This might help you notice that when a certain object enters play you experience these drops.

---
Tags: opengl, java, libgdx, debugging, android-studio
---


# Question
Title: How to save and update modifications done by the player in my procedurally generated JavaScript game?
I am making a game and I need the world to be generated and saved. I used Perlin noise to generate the terrain (and other stuff like trees), but cannot figure out the best way to save and recall actions done by the player, e.i. if a tree is cut down or a mineshaft is used I want that entity to either be updated or deleted.

How could I accomplish this?

More info: I am making this in JavaScript and eventually want to implement Node.js to implement multiplayer features in the future. The player also has a very limited view and this is a 2D top down kind of game. I am also making this basically from scratch.

Any and all help is appreciated!

# Answer
> 0 votes
## What technology to use for saving

When your game is single-player, you can save to the browser's localstorage. But keep in mind that the specification guarantees only 5 MB of storage per website (some browsers will give you more, but you can't rely on that). It also allows web browsers to delete old localstorage data without a warning at their discretion.

An alternative is to use the JavaScript file API to create or read savegame files which the user stores on their filesystem. This appears to the user like a web download / web upload (even though the data never leaves their device). This is less convenient for the player than localstorage, because both saving and loading require additional user interaction. That means no autosave and no one-button quicksave. But it makes it easier for players to transfer savegames between devices and frees you from the space restrictions of localstorage.

When you switch to an online game with a Node.js backend, you should consider saving to a database. If you don't want to use a database for some reason (you **do** want one, trust me), server-sided files are an alternative option.

## What data to save

Dirty solution: Just serialize and store the whole chunk, including the procedurally generated data. This is what Minecraft does, for example. One advantage is that it is easy to do. Another is that it is good for backward compatibility. If you change your world generation algorithms, those chunks generated by the old version are unchanged. The problem is that this can amount to quite a lot of data, especially when your world is very large and/or complex.

Elegant solution: Only store the following:

1. the seed which was used to generate the Perlin-noise for the chunk (note that the JavaScript standard RNG doesn't allow seed values, so you need to implement an own RNG. Don't be afraid, there are many well-documented PRNG algorithms around which aren't hard to implement)
2. any changes the player made.

In order to do the latter, you need to keep a list of changes to each chunk. If the player planted a tree at 317:56, push an object `{ x:317, y:56, object: "Tree" }` to the `changes`-array. When they chopped down a tree at coordinates 456:194, push an object `{ x:456, y:194, object: null }`. If they chopped the tree at 317:56 down again (restoring the original state), remove the object with `x:317, y:56`.

The advantage of this method is that you minimize the amount of data you need to store when the player usually doesn't make that many changes to the game world. But keep in mind that if your player has a lot of influence on the game-world, this method can amount to even more data than just storing the whole chunk.

## How to serialize data

`JSON.stringify` and `JSON.parse` are your friends here. They can turn a JavaScript object (or array) into a string and back. But keep in mind that it can not serialize functions! Any fields which contain functions will be omitted.

If the JSON code turns out to be too large for your use-case, consider running a stock compression algorithm like ZIP on it.

---
Tags: javascript, architecture
---


# Question
Title: Why do I get these "Invalid command android" errors trying to build for Android in Unity?
Trying to move a unity project over to android using gradle as the build system. I get the following 3 errors:

```
Error:Invalid command android

CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/bin/java -Xmx2048M -Dcom.android.sdkmanager.toolsdir="/Users/joeljohnson/Library/Android/sdk/tools" -Dfile.encoding=UTF8 -jar "/Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()

```

and

```
Error building Player: CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/bin/java -Xmx2048M -Dcom.android.sdkmanager.toolsdir="/Users/joeljohnson/Library/Android/sdk/tools" -Dfile.encoding=UTF8 -jar "/Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]

```

It turns out a lot of people have been having this problem and the most common solution is to move to an earlier version of the apk. When I tried that, I still received the same three errors. I moved down to api level 23 from the most current. I am one a mac. exit code: 64

# Answer
> 0 votes
This is a known bug. It's been fixed in the latest version of Unity:

**5.4**.5p2 and higher
**5.5**.3p3 and higher
**5.6**.0p3 and higher
and 2017.1 beta 5 and higher

> Android: Fixed android application building with the latest android sdk.

With the latest version of Unity, you won't need to downgrade your SDK version.

---
Tags: unity, android, gradle
---


# Question
Title: Applying "zoom to the exact point" transformations to screen positions
I´ve implemented zooming of orthographic camera (just scaling it with its speed value):

```
viewMatrix = glm::scale(viewMatrix, glm::vec3(_cameraScale, _cameraScale, 1.0f));

```

And then applied these transformations (also translation by camera position) to the destination point (actually a cursor position vector) so I got its world positions:

```
void Camera::applyTransformationsToPoint(glm::vec3& pos) {

    pos += _cameraPosition;

    pos /= _cameraScale;
}

```

It worked fine, i was getting the right world position with diferent scales. However, this was done with normal scaling - to the origin of the matrix so basically when i scaled the matrix the whole camera moved to its origin and it looked a little bit weird. SO i have decided to imlement zoom to the middle of the screen feature. So basically what I do is (in pseudocode):

```
translate(screenWidth/2,screenHeight/2);
scaleTranslatedMatrix();
translate(-screenWidth/2,-screenHeight/2);

```

It works fine but the code above for transformation of screen coordinations to the world is now not working properly(im not getting the right world positions), any suggestions how to correct it? Thanks.

Edit1: This is how I apply the scaling (if anyone wondered):

```
void Camera::zoomOut(float dt) {

    _cameraScale -= _scaleSpeed * dt;

    if (_cameraScale < 0.4f) {

        _cameraScale = 0.4f;
    }
}

```

**According to the first answer edit:** As I have 4x4 matrix and using a vec3 for my point representation, i have to use temporary vec4 to perform the multiplication, however, it is not working correctly (even without scaling and just translating the view matrix) - for inverse matrix im using GLM library.

```
glm::vec3 Camera::applyTransformationsToPoint(glm::vec3 pos) {

    glm::vec4 tmpVec(pos.x, pos.y, pos.z, 1.0f);
    tmpVec = tmpVec * glm::inverse(viewMatrix);

    return glm::vec3(tmpVec.x,tmpVec.y,tmpVec.z);
}

```

# Answer
> 1 votes
For any matrix transformation, the inverse matrix is what you can consider to be the transformation in "reverse".

Currently, the logic in your `:applyTransformationsToPoint` is basically calculating the inverse transformation directly for a standard matrix that has only ever been scaled and translated about the origin.

Instead, and as a more general solution, the INVERSE of the matrix you compute for the screen transform should be used to apply transformations to point instead.

So where you would have

```
m = new Matrix()
m.translate(screenWidth/2,screenHeight/2);
m.scale(scaleX, scaleY)
m.translate(-screenWidth/2,-screenHeight/2);

```

You would then also create

```
inv = m.invert()

```

And then your point transformation method would become

```
applyTransformationsToPoint(pt){
   return inv*pt   // where * is a matrix multiply
}

```

Hope that helps!

# Answer
> 1 votes
\[EDIT 2\]

You can change the scale of an orthographic projection matrix by modifying the left right bottom top values.

Here is the OpenGL call: `glOrtho( -width/2*zoom, width/2*zoom, -height/2*zoom, height/2*zoom, -1, 1 );`

Alternatively:

```
left = -width / 2 * zoom
right = width / 2 * zoom
bottom = -height / 2 * zoom
top = height / 2 * zoom

```

---
Tags: matrix, transformation
---


# Question
Title: How to implement combining 2 ingredients to create a product?
In my game, you can combine a variety of ingredients to make a product. For example, you could combine water and dirt to make mud.

What I am currently doing to achieve this is by listing each combination possibility that a particular ingredient has. The one thing I managed to do to make it a little more efficient is that I managed to remove duplicates (So for example, if I have coded ingredientA + IngredientB = Cheese, there isn't another entry for IngredientB + Ingredient A = Cheese).

The problem I have with my method is that it is very annoying adding new ingredients. If I do so, I have to go back to every previous ingredient I have coded, and add it's interaction with the ingredient(s) I want to add.

The amount of ingredients I have means this is becoming increasingly time consuming.

Is there a better way to do this?

# Answer
> 3 votes
Each product that exists in your world could be listed in an array or table in a database.

Each product can then have a collection of Recipes.

Instead of each Recipe actually containing a Product, the can simply reference the Products necessary to produce another Product.

For example, let's say Cheese is made from Milk and Chemicals. :) All these things will exist on the same level wherever you decide to store them. Cheese will have a Recipe. This Recipe will reference Milk and Chemicals. Assuming Cheese has another Recipe (say, Milk and Fart), this other Recipe will also reference the necessary products.

I believe this way, there's no need to worry about backward compatibility.

# Answer
> 0 votes
Following what Didia said, what you want sounds like a Composite pattern (https://en.wikipedia.org/wiki/Composite\_pattern).

A resulting product is the same thing as it's parts. In your case, a cheese would be a product just as much as milk and rennet. Each product could have an array of "product required" to create it, but in the end they're all the same conceptually. So when you add a new product, you just need to specify it's required products to create it:

```
                          milk
                 cheese <
               /          rennet
mac n' cheese <
               \         flour
                 pasta <
                         egg

```

In this case, you'd have

```
List<Product> list_products = new List<Product>();

list_products.add(new Product("milk",null));
list_products.add(new Product("rennet",null));
list_products.add(new Product("flour",null));
list_products.add(new Product("egg",null));
list_products.add(new Product("cheese",new Tuple<string,string>("milk","rennet")));
list_products.add(new Product("pasta",new Tuple<string,string>("flour","egg")));

```

To add mac n' cheese, simply push a new value in the list

```
list_products.add(new Product("mac n' cheese",new Tuple<string,string>("cheese","pasta")));

```

I used Tuple wince you said that 2 product create another, but Lists or even arrays could do the job here.

Of course the code is probably not working (or working awfully with string comparison, problems with localization, etc.), so see it as pseudocode, but you should get the gist of it. The cool thing is that you could (and should IMO) put your products in a nice JSON or XML format that is easily parsable and scalable with this kind of data. Also, a hashtable of ("ID",Product) would probably be easier to manage.

---
Tags: unity, c#, software-engineering, game-mechanics, efficiency
---


# Question
Title: SerializeField UntiyEvent not properly saving modifications in EditorWindow
I'm making a node editor in Unity using an EditorWindow, I'm currently trying to make it so designers can add their own methods to a node using serialized UnityEvents; but I haven't been able to get it to function properly.

```
SerializedObject serializedObject = new SerializedObject(selectedNode.NodeState);

SerializedProperty property = serializedObject.GetIterator();
property.Next(true);

while (property.NextVisible(false))
{
    EditorGUILayout.PropertyField(property);

}
serializedObject.ApplyModifiedProperties();

serializedObject.Update();

```

The above code runs through all necessary fields of the class so the user can modify them.

Everything functions perfectly with the exception of UnityEvents. They almost do as I intend them to do, except they don't preserve the variable inputs of inserted object's method. If I keep working within the editor window they stay, but if I close the window and re-open the inputted variable resets.

I thought this may be caused by an issue somewhere else in my code, but all other fields work fine.

# Answer
I think the problem is that all actions in the custom Editor or EditorWindow you should do **between** two calls:

```
serializedObject.Update()

// Here is some of your code

serializedObject.ApplyModifiedProperties()

```

But in your code these lines goes below the main code. Moreover, the sequence is wrong.

I think the right way will be:

```
serializedObject.Update()

while (property.NextVisible(false)) {
    EditorGUILayout.PropertyField(property);
}

serializedObject.ApplyModifiedProperties()

```
> 1 votes

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


# Question
Title: In Hammer, how can I make a sound come from a physics object?
In hammer, I want to make a functioning radio, as in the sound comes from the radio itself and when you pick it up and move it around the sound's origin moves with the object.

# Answer
I fixed it. Basically, you want to go into the ambient generic, and set the source entity to whatever you want the sound to come from. make sure to name the entity.
> 1 votes

---
Tags: hammer
---


# Question
Title: Unity 2d text not rendered properly in scene mode
I am a beginner in Unity and trying to add a text box to my scene. I have done this before and was able to do it properly.

**Problem**

But recently I created a new project, added a text element to it, but text is not rendered properly in that text box. Anything I type in it is shown as boxes.

Here is the screenshot for it.

While text is shown properly in play mode. I also tried adding custom fonts in it but it didn't made any effect.

What can be the cause for this.

# Answer
> 2 votes
Change to 'shaded' inside this dropdown. It's right next to the scene view tab.

---
Tags: unity, text
---


# Question
Title: Make Dropdown adhere size of its contents
When `Dropdown` is placed inside a panel with `ContentSizeFitter/LayoutGroup` with preferred size set, it appears to take just 10x10 units, no matter what the contents are. How can I make Dropdown's preferred size adhere size of its contents, i.e. size of its biggest option?

# Answer
> 1 votes
The option child control sizes inside the panel paired with the content size fitter seems to be a bit buggy, because it's not wrapping the contents of the dropdown recursively.

I tested a couple times, and i think you should either Disable the option from the panel object:

**OR**

use a script and set the DROPDOWN OBJECT Width+Height yourself, using a layout Element componnent;

**OR** (workaround without using scripts)

* Turn off 'Child control Size'
* Remove/Readd dropdown
* Add layout Element component to Dropdown
* Click Preferred Width , Preferred Height
* Re-enable 'Childcontrol Size' if its nescessary for your needs;

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


# Question
Title: How to make changes to array of prefabs in editor to be visible in game window
I attached the following script to an empty game object (`EnemiesGO`) in the editor.

```
public class EnemiesScript {

[System.Serializable]
public struct EnemyWithType {
    public EnemyScript enemy;
    public EnemyScript.Type enemyType;
}

public EnemyWithType[] enemyPrefabs;
public EnemyScript[] enemies;

void Start ()
{
    enemies = new EnemyScript[enemyPrefabs.Length];

    for (int i = 0; i < enemyPrefabs.Length; i++)
    {
        enemies[i] = Instantiate<EnemyScript>(enemyPrefabs[i].enemy);
        enemies[i].enemyCategory = enemyPrefabs[i].enemyType;
    }
}

```

}

When I was populating `enemyPrefabs` (through the editor) I didn't see the prefabs in the popup selection window so I dragged them directly from the Assets window `Assets/Resources/Prefabs/EnemyPrefabs`. My question is two fold.

1. If it is possible, how can I get the populated `enemyPrefabs` array to be displayed in the game window/ scene window before I run the game? In general, I would like to see changes effected from the editor in the game window before I run the game.
2. How can I access the EnemyPrefabs folder from the popup selection window?

# Answer
* 1st question You should add \[ExecuteInEditMode\] to your class , check this example. Also, read the description, it explains the differences in the callbacks of playmode/editmode;
* 2nd question, you should use a GameObject as the type of your prefabs, so you can access them in the inspector via the little circle.

`[System.Serializable]
 public struct EnemyWithType {
 public GameObject enemy;
 public EnemyScript.Type enemyType;
 }`

\[...\]

```
for (int i = 0; i < enemyPrefabs.Length; i++)
    {
        enemies[i] = Instantiate(enemyPrefabs[i].enemy).GetComponent<EnemyScript>();
    }

```
> 1 votes

---
Tags: unity
---


title: What is Fresnel?

text:
# Question
Title: What is Fresnel?
I am new to graphics rendering and there are a lot of terminology. Can someone please explain what fresnel is?

I see fresnel in unreal engine when people deal with translucent objects such as glasses. What is it in the fresnel that everybody uses it for translucent object. When I googled the term I only find technical documentations that only some people can understand.

Could you guys can explain as you would explain to little child? So other new people, too, can understand?

# Answer
The fresnel **effect** is the way light works when gets in contact with a translucent object.

You can actually try this, take a bowl fill it with water and look at it from above. You'll see the bottom of the bowl clearly. Now start looking at it from different angles. The closer you are to the plane of the water's surface (aka. The smaller the angle is between your head and the ground) the less you'll be able to see through the water and the more it will reflect the stuff behind it.
> 10 votes

# Answer
To complete Bálint's answer:

In Mathematical terms, the Fresnel node is a Dot Product between the Camera Vector and the Surface Normal, where both vectors are normalized!
The resulting value determines the angle you are looking onto the surface. 0 means you are looking straight onto the surface and 1 means you are looking on the same plane as the surface.

Fresnel is often used in PBR, because it simulates the reflectivity in real life pretty well. Every surface is perfectly reflective when you are looking onto it on the same plane. This can be seen when you are driving with the car or looking onto a long road. You can see the reflection of cars on the streets when the road becomes convex, but the reflection disappears when it becomes concave again. This "reflection threshold" can be simulated by calculating the fresnel with an exponent \> 1
> 4 votes

---
Tags: graphics, terminology
---


# Question
Title: Storing quests for an online RPG in a MySQL database
I'm creating an online RPG game and I've been looking around for a way to save players' progressions in quests in MySQL. I've been looking at Pim Jager's answer answer for a while and I've come to the conclusion that this could work, but then my question would be:

Where/how do I store if a player currently has a quest accepted? How do I keep track of at which step of the quest the player currently is? This has to be saved somehow but I can't seem to figure out how I would do that. Let me know if you can help me out.

Thanks!

# Answer
> 1 votes
Create a table `CharacterQuestSteps` with three columns:

```
CharacterId  UNSIGNED INT NOT NULL
QuestId      UNSIGNED INT NOT NULL
Step         INT
PRIMARY KEY (CharacterId, QuestId)

```

When a player-character hasn't accepted a quest yet, then there should be no entry in that table.

When the player is on a quest, the field `Step` says on which step of the quest they are. Which value means what will usually be quest-specific, because different kinds of quests will have different steps. The quest being finished can be a magic value (like `9999`) or a value of `NULL`. If using magic numbers or meaningful `NULL`s is too dirty in your opinion, you could also add a fourth boolean field `Completed`.

When you have a lot of the stereotypical "Kill X mobs" or "Collect X Items" quests, you could also add another column `Counter` which holds the count-value for the current quest step. This architecture limits you to one counter per quest-step, though. If you want to allow quests with multiple counters in one step ("Kill 10 goblin warriors, 10 goblin archers and 1 goblin leader"), you will need a second table `CharacterQuestCounters` which looks like this:

```
CharacterId  UNSIGNED INT NOT NULL
QuestId      UNSIGNED INT NOT NULL
CounterName  VARCHAR      NOT NULL
CounterValue INT          NOT NULL
PRIMARY KEY(CharacterId, QuestId, CounterName)

```

When you change the step of a quest, you can delete the corresponding entries from this table, because they will likely be not applicable to the new step.

# Answer
> 0 votes
Pim's answer includes a `Quest` and `QuestStep` table. Depending on what you want, you may choose:

* A table that maps players to quests (eg. a table with a `PlayerId` and `QuestId`). You insert a row whenever a player accepts a quest; or you can have a "status" column (accepted, completed, etc.)
* A table that maps players to quest steps. This way, you can track per-step which player accepted (or is at what state) for each quest.

---
Tags: multiplayer, rpg, databases, mysql, quests
---


title: Convert a terrain to plane?

text:
# Question
Title: Convert a terrain to plane?
I have a terrain on which I painted on and used many textures on it. Now when I start the game on my phone it lags alot. Is there any way I can convert the terrain to maybe a plane or anything simpler but still keep the textures and paintings on top?

# Answer
> 2 votes
***There are 3 methods for mobile optimized terrain or platform.***

1) Predesigned Terrian from 3D modeling tool.

2) Optimized the Terrian in Unity.

3) Export Unity Terrian from Unity to any 3D modeling tool and then Reimport it into Unity.

**1)** Use any modeling tool and make a platform.You have a good knowledge of 3D Modeling tool.

**2)** Set these setting on Unity Terrian and you can optimized it.

Set those setting and use texture size of 512x512 and for each terrain use 2-3 texture.

**3)Exports a Unity terrain object as a .obj file that can be loaded into various 3D apps.**

***This approach is used to convert high poly terrain into low poly by exporting it from Unity into a .obj file and then optimize it into any 3D tool.***

You must place the script in a folder named **Editor** in your project's Assets folder for it to work properly. Also, it must be called "**ExportTerrain**" or it won't run.

**Usage** To export, first, select a terrain object in your scene. If none is selected, it will use the active terrain (if any). Select Export To Obj... from the Terrain menu, and in the resulting window, select whether you want the object to use triangles or quads when exported, and also select the resolution to use for the exported mesh (full, half, quarter, eighth or sixteenth). Then click Export, choose a file name and location, and the file will be exported. Note that high-res terrains exported at full resolution will result in very large .obj files and may take a while to process.

Find this link also: http://wiki.unity3d.com/index.php?title=TerrainObjExporter

```
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.IO;
using System.Text;

enum SaveFormat { Triangles, Quads }
enum SaveResolution { Full=0, Half, Quarter, Eighth, Sixteenth }

class ExportTerrain : EditorWindow
{
   SaveFormat saveFormat = SaveFormat.Triangles;
   SaveResolution saveResolution = SaveResolution.Half;

   static TerrainData terrain;
   static Vector3 terrainPos;

   int tCount;
   int counter;
   int totalCount;
   int progressUpdateInterval = 10000;

   [MenuItem("Terrain/Export To Obj...")]
   static void Init()
   {
      terrain = null;
      Terrain terrainObject = Selection.activeObject as Terrain;
      if (!terrainObject)
      {
         terrainObject = Terrain.activeTerrain;
      }
      if (terrainObject)
      {
         terrain = terrainObject.terrainData;
         terrainPos = terrainObject.transform.position;
      }

      EditorWindow.GetWindow<ExportTerrain>().Show();
   }

   void OnGUI()
   {
      if (!terrain)
      {
         GUILayout.Label("No terrain found");
         if (GUILayout.Button("Cancel"))
         {
            EditorWindow.GetWindow<ExportTerrain>().Close();
         }
         return;
      }
      saveFormat = (SaveFormat) EditorGUILayout.EnumPopup("Export Format", saveFormat);

      saveResolution = (SaveResolution) EditorGUILayout.EnumPopup("Resolution", saveResolution);

      if (GUILayout.Button("Export"))
      {
         Export();
      }
   }

   void Export()
   {
      string fileName = EditorUtility.SaveFilePanel("Export .obj file", "", "Terrain", "obj");
      int w = terrain.heightmapWidth;
      int h = terrain.heightmapHeight;
      Vector3 meshScale = terrain.size;
      int tRes = (int)Mathf.Pow(2, (int)saveResolution );
      meshScale = new Vector3(meshScale.x / (w - 1) * tRes, meshScale.y, meshScale.z / (h - 1) * tRes);
      Vector2 uvScale = new Vector2(1.0f / (w - 1), 1.0f / (h - 1));
      float[,] tData = terrain.GetHeights(0, 0, w, h);

      w = (w - 1) / tRes + 1;
      h = (h - 1) / tRes + 1;
      Vector3[] tVertices = new Vector3[w * h];
      Vector2[] tUV = new Vector2[w * h];

      int[] tPolys;

      if (saveFormat == SaveFormat.Triangles)
      {
         tPolys = new int[(w - 1) * (h - 1) * 6];
      }
      else
      {
         tPolys = new int[(w - 1) * (h - 1) * 4];
      }

      // Build vertices and UVs
      for (int y = 0; y < h; y++)
      {
         for (int x = 0; x < w; x++)
         {
            tVertices[y * w + x] = Vector3.Scale(meshScale, new Vector3(-y, tData[x * tRes, y * tRes], x)) + terrainPos;
            tUV[y * w + x] = Vector2.Scale( new Vector2(x * tRes, y * tRes), uvScale);
         }
      }

      int  index = 0;
      if (saveFormat == SaveFormat.Triangles)
      {
         // Build triangle indices: 3 indices into vertex array for each triangle
         for (int y = 0; y < h - 1; y++)
         {
            for (int x = 0; x < w - 1; x++)
            {
               // For each grid cell output two triangles
               tPolys[index++] = (y * w) + x;
               tPolys[index++] = ((y + 1) * w) + x;
               tPolys[index++] = (y * w) + x + 1;

               tPolys[index++] = ((y + 1) * w) + x;
               tPolys[index++] = ((y + 1) * w) + x + 1;
               tPolys[index++] = (y * w) + x + 1;
            }
         }
      }
      else
      {
         // Build quad indices: 4 indices into vertex array for each quad
         for (int y = 0; y < h - 1; y++)
         {
            for (int x = 0; x < w - 1; x++)
            {
               // For each grid cell output one quad
               tPolys[index++] = (y * w) + x;
               tPolys[index++] = ((y + 1) * w) + x;
               tPolys[index++] = ((y + 1) * w) + x + 1;
               tPolys[index++] = (y * w) + x + 1;
            }
         }
      }

      // Export to .obj
      StreamWriter sw = new StreamWriter(fileName);
      try
      {

         sw.WriteLine("# Unity terrain OBJ File");

         // Write vertices
         System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
         counter = tCount = 0;
         totalCount = (tVertices.Length * 2 + (saveFormat == SaveFormat.Triangles ? tPolys.Length / 3 : tPolys.Length / 4)) / progressUpdateInterval;
         for (int i = 0; i < tVertices.Length; i++)
         {
            UpdateProgress();
            StringBuilder sb = new StringBuilder("v ", 20);
            // StringBuilder stuff is done this way because it's faster than using the "{0} {1} {2}"etc. format
            // Which is important when you're exporting huge terrains.
            sb.Append(tVertices[i].x.ToString()).Append(" ").
               Append(tVertices[i].y.ToString()).Append(" ").
               Append(tVertices[i].z.ToString());
            sw.WriteLine(sb);
         }
         // Write UVs
         for (int i = 0; i < tUV.Length; i++)
         {
            UpdateProgress();
            StringBuilder sb = new StringBuilder("vt ", 22);
            sb.Append(tUV[i].x.ToString()).Append(" ").
               Append(tUV[i].y.ToString());
            sw.WriteLine(sb);
         }
         if (saveFormat == SaveFormat.Triangles)
         {
            // Write triangles
            for (int i = 0; i < tPolys.Length; i += 3)
            {
               UpdateProgress();
               StringBuilder sb = new StringBuilder("f ", 43);
               sb.Append(tPolys[i] + 1).Append("/").Append(tPolys[i] + 1).Append(" ").
                  Append(tPolys[i + 1] + 1).Append("/").Append(tPolys[i + 1] + 1).Append(" ").
                  Append(tPolys[i + 2] + 1).Append("/").Append(tPolys[i + 2] + 1);
               sw.WriteLine(sb);
            }
         }
         else
         {
            // Write quads
            for (int i = 0; i < tPolys.Length; i += 4)
            {
               UpdateProgress();
               StringBuilder sb = new StringBuilder("f ", 57);
               sb.Append(tPolys[i] + 1).Append("/").Append(tPolys[i] + 1).Append(" ").
                  Append(tPolys[i + 1] + 1).Append("/").Append(tPolys[i + 1] + 1).Append(" ").
                  Append(tPolys[i + 2] + 1).Append("/").Append(tPolys[i + 2] + 1).Append(" ").
                  Append(tPolys[i + 3] + 1).Append("/").Append(tPolys[i + 3] + 1);
               sw.WriteLine(sb);
            }
         }
      }
      catch(Exception err)
      {
         Debug.Log("Error saving file: " + err.Message);
      }
      sw.Close();

      terrain = null;
      EditorUtility.DisplayProgressBar("Saving file to disc.", "This might take a while...", 1f);
      EditorWindow.GetWindow<ExportTerrain>().Close();
      EditorUtility.ClearProgressBar();
   }

   void UpdateProgress()
   {
      if (counter++ == progressUpdateInterval)
      {
         counter = 0;
         EditorUtility.DisplayProgressBar("Saving...", "", Mathf.InverseLerp(0, totalCount, ++tCount));
      }
   }
}
```

And then import the terrain in your project but you need to take care of unrapping and texture on it after importing on Unity.

---
Tags: unity, terrain
---


# Question
Title: How do I recognize squares, rectangles ... (like in TwoDots)?
I currently working on a small mobile game. Not a clone of TwoDots(!) but I need to recognize patterns like they do and I use the game as an example. How the game works? Players have to connect dots. Players can only connect a dot to its direct neighbor in the grid. So the next dot has to be left, right, above or below. Dots can only be added once to a sequence. Connecting a dot to one that is already part of the sequence closes the sequence.

See here http://youtu.be/8RDm6wQ9QbM?t=1m41s (just the next 20 seconds)

What I want to know is when a player connects dots, are there any enclosed dots?

My idea was to store the players touch directions (next to the dots and their position in the grid). For the blue square this would mean {1,2,3,4} if you start from the bottom left and connect counterclockwise. Then I could simply check the number of directions in the array (=4). From my grid I know that the start-dot is \[3|3\] and the end-dot is also \[3|3\]. This means it has to be a square and there is nothing enclosed because it is the smallest possible rectangle/square.

The problem starts with bigger squares e.g. the purple one. Starting from the bottom left and connect counterclockwise again there would be the following sequence {1,1,1,2,2,2,3,3,3,4,4,4}. How do I know that this is a square/rectangle or some strange stuff and furthermore how do I know if there are any dots inside?

I can count all directions (3x1, 3x2, 3x3, 3x4) and see that all directions appear 3 times. It has 12 directions. 12 is divisible by 4 so it could be a square. But sadly 12 directions doesn't have to be a square nor a rectangle because \[1,2,1,2,1,2,3,3,3,4,4,4\] would also close the pattern with the the same amount for each direction.

Well... the green one really makes my brain hurt. Green is definitely not a rectangle nor a square. I know that there might be any dots enclosed because there are more than 4 directions stored in the array and the start- and end-dot are the same but how do I get the three question marks? Same goes for the blue dots which are enclosed by the purple square.

I am totally lost here and I think... or better I hope I am overthinking/missing something here.

Thanks for your help! proudcastle

```
Some Possible Squares:
4x OO |8x OOO |12x OOOO |16x OOOOO |20x... 24x... etc.
   OO |   O?O |    O??O |    O???O |
      |   OOO |    O??O |    O???O |
      |       |    OOOO |    O???O |
                        |    OOOOO |

Some Non-Square Rectangles:
6x OOO OO |8x OOO OOOO OO |10x OOOO OOOOO OO |12x OOOOO OOOOOO OO etc.
   OOO OO |   O?O OOOO OO |    O??O OOOOO OO |    O???O OOOOOO OO
       OO |   OOO      OO |    OOOO       OO |    OOOOO        OO
          |            OO |               OO |                 OO
                          |               OO |                 OO
                                             |                 OO

Some Strange Stuff
10x OOOOO   OOO  OOOO  OO   OOOO |12x  OOOOO  OOOO   ...
      O?O  OO?O  O?OO  OO   OOOO |     O??OO  O??OO
      OOO  OOOO  OOO   OOO   OO  |     OOOO   OOOOO
                       OOO       |

```

# Answer
> 1 votes
Here is an easy way to detect any figures that have intersections or are "closed":

1. You know the list of dots that are used in the selection with their coordinates (from first selected dot to last) e.g.: (1,1) (2,1) (3,1), (3,2), (4,2) ...
2. If your list has two identical coordinates - you obviously have intersection
3. Profit!

This is usable for the kind of figures that are formed from two dots:

---
Tags: grid, puzzle
---


title: Unity Mathf.Atan2 algorithm complexity

text:
# Question
Title: Unity Mathf.Atan2 algorithm complexity
using Unity5.5.1f; using C#;

So I have a circle (2D) divided equally by 16 directions, and I also have a direction V which is different from the other 16.

In order to know which direction is the closest I thought of two apporaches:

1. Dot product between V and all the other directions and choose the max one
2. Store atan for all the 16th directions then compute atan for V and see which angle is the closest to V's

My questions are,does anyone know what is the complexity of Mathf.Atan2? Or of an Atan2 algorithm in general? I read it gets worse and worse as the angle becomes bigger, is it true?

# Answer
> 3 votes
It doesn't make a lot of sense to talk about algorithmic complexity (in the big-O sense) for the way we use atan2 in game development. Our inputs are always one fixed size (32 bit floats for the Mathf version), whereas complexity analysis looks at how the algorithm performs as the input gets arbitrarily large (not strictly in magnitude, but in how many bits it takes to write it). So, we could trivially say atan2 is O(1) for our purposes - its execution has a constant upper bound, set by whatever the worst-case pair of floats might be.

So, I'm going to interpret your question instead as **"How can I efficiently categorize a Vector2 into one of 16 evenly-spaced directions?"**

Empirically testing this in Unity, doing 10000 calls to Mathf.Atan2 takes about 1 millisecond on my laptop's i7, which means on average each call costs something like a tenth of a microsecond. I'd be willing to bet that this is efficient enough for your needs. And it's clear:

```
Vector2[] directions = // populate this with your 16 directions.
                       // Counter-clockwise from (1, 0)

Vector2 RoundToNearestDirection(Vector2 vector) {
     // Convert the input vector to an angle.
     float angle = Mathf.Atan2(vector.y, vector.x);
     // Round to one of 16 buckets, using modulo to wrap 16 back to 0.
     int index = Mathf.Round((angle * 8 / Mathf.PI) + 16) % 16;
     // Look up the corresponding entry in our direction table.
     return directions[index];
}

```

If you wanted to, you could replace `Atan2` above with an `ApproximateAtan2` method you define based on examples like these, though you may find that some vectors very close to the edges of the 16 direction buckets get slightly mis-categorized this way. It probably wouldn't be noticeable in gameplay, but you'll have to make the call whether a few compute cycles is worth adding the extra uncertainty and opportunity for bugs into your codebase.

Compare this against how messy it gets when we try to avoid runtime trigonometry and its approximations:

```
Vector2 RoundToNearestDirection(Vector2 vector) {

    // If given a near-zero vector, punt and return an arbitrary direction.
    if(Mathf.Approximately(absolutes.sqrMagnitude, 0f))
       return directions[0];

    Vector2 absolutes = new Vector2(Mathf.Abs(vector.x), Mathf.Abs(vector.y));

    int index;

    if(absolutes.x > absolutes.y) {
        int inSegment = IndexInSegment(absolutes.y/absolutes.x) * Mathf.Sign(vector.y);
        if(vector.x > 0) {
            index = (16 + inSegment) % 16;
        } else {
            index = 8 - inSegment;
        }
    } else {
        int inSegment = IndexInSegment(absolutes.x/absolutes.y) * Mathf.Sign(vector.x);
        if(vector.y > 0) {
            index = 4 - inSegment;
        } else {
            index = 12 + inSegment;
        }
    }

    return directions[index];
}

// Use constant tangent ratios that will be pre-computed, so there's no runtime trig.
int IndexInSegment(float a) {
    if(a < Mathf.Tan(Mathf.Deg2Rad * 1f * 180f/16f)
       return 0;

    if(a < Mathf.Tan(Mathf.Deg2Rad * 3f * 180f/16f)
       return 1;

    return 2;
}

```

This code is not nearly so clear as the code using atan2. The trig let us see every salient operation on 3 lines, and we can verify in our heads that it's working as intended. This though - if I hadn't told you what this function does, would you have guessed? If it contains bugs, would we notice from looking at the code?

My strong suspicion is that this added code complexity, uncertainty, and sheer added surface area for bug accumulation is not going to be worth whatever fraction of a tenth of a microsecond we might hope to shave off of the standard atan2.

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


title: How to make an object destructible?

text:
# Question
Title: How to make an object destructible?
I have some 3d models that I have downloaded from Unity asset store. Most of the time, these objects are not "separatable" so I can't apply a destructible effect.

Is there a way to separate a model into small pieces, whether by using Blender, or a Unity script, or something else?

# Answer
> 1 votes
It depends what you want the separate pieces to look like. If you mean destroy into recognizable chunks, that requires a lot of complex art work. Technically that can be done in Blender, but frankly that's harder than modeling the things in the first place.

However you may also get the effect you want by shattering the mesh into separate polygons. In that case, there are ways to accomplish that through scripting. Just search the Asset Store for "destroy mesh script" to see several options.

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


# Question
Title: How should I manage Roguelike levels/maps in JavaScript?
I am developing a Roguelike in JavaScript using ROT.js. I'd like to keep with traditional gameplay (permadeath, randomly generated dungeons/mobs/items), but I want to have a statically defined overworld with randomly generated dungeons beneath.

Currently, I use the TILED map editor to create my overworld map and export it to JSON/JS format and import/parse the map into my game. For randomly generated dungeons, I use ROT.js's built in dungeon generator tool to create dungeons that are in the same JSON/JS format that the TILED maps are in.

The issue I am facing is finding an efficient way to store these maps and levels once they are generated, alongside the overworld. Right now, I just throw the generated maps into a JavaScript object indexed by the name of the map. Here's an example of how I do this currently:

```
levels = {};
// map class parses TILED map json and creates actors based on ascii
let map = new Map(TiledMaps["overworld"]);
levels["overworld"] = map;
let dungeon = new Map(randomMap(...)); // random map generates tiled map
levels["dungeon1"] = dungeon;
// to switch levels, just set the current game map
Game.map = levels["dungeon1"];

```

Is this a good approach? I would like to consider the possibility of having different types of dungeons. So, in the overworld, you might visit different sections of the world and those have different dungeons. Something like Link to the Past perhaps? Any advice?

# Answer
> 2 votes
I see nothing fundamentally wrong with your approach. Just a few thoughts:

`Map` is a pre-existing javascript data type. So unless the code in your answer actually uses this type of `Map`, you probably want to rename your custom data type to something unique, e.g. `DungeonMap` or similar.

JSON is a good format because it has little syntactic overhead and is also very well readable by humans. It should be totally sufficient for reasonably sized maps created by ROT. You could even store the maps in the browser of the user via `localstorage` so you don't have to reload it every time from the server, although it's probably a good idea to store it serverside as backup and create a hash so you can check if it has been manipulated.

Depending on the size of the dungeons, you might want to keep them in separate objects so you don't have to load the entire gameworld object, but rather load the data only when it is indeed needed.

---
Tags: javascript, tiled, roguelikes
---


# Question
Title: Why am I unable to move a player that extends image?
I wanted to create a simple game where I will be able to move a player image horizontally. I am using Screens (at least trying to do so) and created the below:

```
public class GameScreen implements Screen {

    private JumpingKitten jumpingKitten;
    private Stage stage;
    private OrthographicCamera camera;
    private SpriteBatch spriteBatch;
    private Player player;

public GameScreen(JumpingKitten jumpingKitten) {
    this.jumpingKitten = jumpingKitten;
    this.createCamera();
    this.stage = new Stage(new StretchViewport(1026.0f, 768.0f, this.camera));
    this.spriteBatch = new SpriteBatch();
    Gdx.input.setInputProcessor(this.stage);
    init();
}

private void init() {
    initPlayer();
}

private void initPlayer() {
    player = new Player();
    stage.addActor(player);
    stage.act();
}

private void createCamera() {
    this.camera = new OrthographicCamera();
    this.camera.setToOrtho(false, 1026.0f, 768.0f);
    this.camera.update();
}

@Override
public void render(float delta) {
    this.clearScreen();
    handleInput();
    this.camera.update();
    this.spriteBatch.setProjectionMatrix(this.camera.combined);

    spriteBatch.begin();
    stage.draw();
    spriteBatch.end();
}

private void clearScreen() {
    Gdx.gl.glClearColor(0.15F, 0.15F, 0.3F, 1.0F);
    Gdx.gl.glClear(16384);
}

private void handleInput() {
    if(Gdx.input.isKeyPressed(Input.Keys.A)) {
        player.STARTING_X -= 50 * Gdx.graphics.getDeltaTime(); // STARTING X incorrect
        System.out.println("A is pressed"); // shown in console
    }
    if(Gdx.input.isKeyPressed(Input.Keys.D)) {
        player.STARTING_X += 50 * Gdx.graphics.getDeltaTime();
    }
}

```

And below is the player class:

```
public class Player extends Image {

private static final int PLAYER_WIDTH = 119;
private static final int PLAYER_HEIGHT = 136;

public static int STARTING_X = 100;
public static final int STARTING_Y = 100;

public Player() {
    super(new Texture("Cat_Idle_1.png"));

    this.setOrigin(100, 100);
    this.setSize(PLAYER_WIDTH, PLAYER_HEIGHT);

    this.setPosition(STARTING_X, STARTING_Y);

}

```

Even though I have completed some simple tutorials, I am unable to retrieve the x coordinate of the player object. This is stopping me from translating the player object along the x axis. Can someone explain what I am doing wrong, here? I honestly think that I jumped into something I shouldn't have.

# Answer
> 0 votes
Your `STARTING_X` and `STARTING_Y` is just the *start* position of the object, not the objects actual position. To change the objects position use `player.setPosition(x, y)` or the `setX(x)` and `setY(y)` methods. To retrieve the current position of your player you use the `getX()` and `getY()` methods.

So your `handleInput` would look like this:

```
private void handleInput() {
    float moveAmount = 50 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Input.Keys.A)) {
        // Same as your player.x -= moveAmount, but correct this time.
        player.setX(player.getX() - moveAmount);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.D)) {
        player.setX(player.getX() + moveAmount);
    }
}

```

---

Some other comments:

* You don't need to create a new `SpriteBatch`. Your stage has its own internal `SpriteBatch` already.
* You don't need to create a new `OrthographicCamera`. Your `Viewport` has its own internal `Camera` already.
* When you use a `Viewport` you need to make sure to call `viewport.apply()` and `viewport.update(width, height)`.
* You **need** to call stage.act() in your render method as well as stage.draw().

With this in mind your code should be something like this (only edited parts included):

```
public class GameScreen implements Screen {
    // These two are not needed.
    // private OrthographicCamera camera;
    // private SpriteBatch spriteBatch;

public GameScreen(JumpingKitten jumpingKitten) {
    ...
    // No need to create a new camera for the viewport.
    this.stage = new Stage(new StretchViewport(1026.0f, 768.0f));
}

private void initPlayer() {
    ...
    // No need to call stage.act() here.
    // stage.act();
}

// We don't need to create a new Camera.
//private void createCamera() {
//    this.camera = new OrthographicCamera();
//    this.camera.setToOrtho(false, 1026.0f, 768.0f);
//    this.camera.update();
//}

@Override
public void render(float delta) {
    ...

    // Instead of camera.update() we call viewport.apply().
    // We don't need to manually set projection matrix, stage does this internally.
    // this.camera.update();
    // this.spriteBatch.setProjectionMatrix(this.camera.combined);
    stage.getViewport().apply();

    // Stage uses internal batch and uses begin() and end() internally.
    // spriteBatch.begin();
    stage.act(); // <- Don't forget this! You need to update your stage every frame.
    stage.draw();
    // spriteBatch.end();
}

//We need this method to update the viewport dimensions!
@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height);
}

```

---
Tags: libgdx
---


title: tcp multiplayer security/structure

text:
# Question
Title: tcp multiplayer security/structure
I'm creating a real time multiplayer game. Each piece of data needs to be received, but it still needs to be as fast as possible which is why I don't want to use TLS for every request.

Here's what I was thinking:

The player logs in using TLS, and receives a session ID and symmetric key that the server generates

The server stores the player's ip address and symmetric key in the database for future reference

When they start a match, they receive a match ID, and send data to the server including the match ID, their session ID, and any necessary data using a symmetric encryption algorithm

The server takes their IP, finds the symmetric key from the database, and decrypts the message and authenticates the user based on the session ID

If everything checks out, the server accepts the data.

Is this approach plausible/efficient? would it be better for me to store the each player's symmetric key using their IP, or for me to get rid of the IP/symmetric key link table and send the data with the session id not encrypted, and store the key using the session id?

Any answers/comments would be greatly appreciated.

# Answer
> 0 votes
You seem to have two misconceptions which will mean that it won't work for a large part of your potential player-base:

1. You assume IPs are static and never change. That's wrong. Many ISPs reassign customer IP addresses daily.
2. You assume that everyone has an unique IP. Also wrong. It's quite frequent that multiple users share the same external IP address via NAT.

Two connections coming from the same IP address is evidence that they *might* be the same person, but it's no proof. So never try to use IP addresses as identifiers for people (or even machines).

Also, the benefit of this scheme is very small. TLS only needs expensive asymmetric encryption during the handshake when the connection is established. After the connection is established, it uses a symmetric key for encryption until the connection is disconnected.

So just use out-of-the-box TLS encryption.

---
Tags: multiplayer, security, encryption
---


# Question
Title: Prevent players from wallhacking in an online FPS?
Why do we still complain about wallhackers in multiplayer first-person shooters?

Isn't it possible to perform occlusion culling for all players server-side? For example, send player xyz information to client only when the player is visible in client's frustum and not occluded by any object ? Even if the collision-geometry is very, very simplified, most of the time cheater won't receive tactical information.

Why not do this?

# Answer
> 19 votes
Think you're lagging now? Just wait 'till you have to get real-time occlusion information from the server. Now you can walk around from behind a wall and bad guys will suddenly pop into view as the server catches up and sends you the updated occlusion data.

So my snarky comment tells it all. Likely the primary reason not to do this is lag and server load. If you want the server to know when another player is visible to you, that means the server has to know exactly what geometry each player is looking at and calculate that occlusion.

I agree that exploits like wall hacking can make the game not fun. And I see that developers would worry about this because they want to make the game as fun as possible. **However, when developers get to the point where their anit-cheat/hack counter-measures diminish game play and/or customer satisfaction, they'll lose far more customers than if they had just left it alone**. See DRM.

# Answer
> 17 votes
It's doable, and has been tried in research before; for a comparison of interest management schemes, see http://dl.acm.org/citation.cfm?id=1230069

As Byte56 said, it may require more CPU, but it may reduce your bandwidth, and reduce the likelihood of wall-hacks.

And as Byte56 said, an interest area strictly limited to the player's occlusion-area may reduce responsiveness on the client-side: ambushes will take at least half a round-trip to be displayed. However, you could make the player's interest area slightly larger than the occlusion area, so that the client receives the opponent's ambush a few seconds before it happens. That way, wall-hacks are still possible, but only at the very last moment.

# Answer
> 4 votes
The short answer is that yes, server side occlusion culling is possible, but it's often not done due to complexity and limited benefit.

Keep in mind that for a large portion of modern FPS games, complete occlusion is rare. Characters these days use cover or hide in grass, and the actual uniforms and camouflage actually has an impact on visibility. Walls and corridors still play a large part of online battle, but not as much as in years past.

Games with lots of tight corridors and opaque surfaces can (an sometimes have) used occlusion culling on the server for event filtering. This just doesn't work so well for large open environments and realistic cover/camo games.

Wall hacking is also only one small part of cheating in online games, and fixing each individual hack has not worked well so far. The best approaches have simply been high quality match making and player rating systems that filter out the cheaters and decrease the likelihood getting put into a frustrating match.

# Answer
> -3 votes
Cant game devs just write a side program that basically takes full control of the pc and doesn't allow any 3rd party software to load while the game is running? Don't they have to load the injectors after the game is started and mapped to memory? So just black list everything non os related from running. They have to make a type of UAC to stop services from loading after the game is loaded..

My other idea to completely prevent hacking is a bit more complex and involves running games like a linux live drive os.. Basically the game wouldn't use windows at all but use its own stripped down os which is designed to only have games load. So gamers might wanna stream or play music while gaming but this new way of running a game won't allow it.. Big deal, the devs could whitelist programs and stuff but I wouldn't bother.. you're trying to play a game, if you wanna multi task have a laptop near by etc.. Essentially you wanna run the game in sandboxie mode with encryption.. I think that is what its called.. Its like running a a game in a virtual temp os environment which is 100% controlled by the game maker.

And this sandboxie mode would be very similar to how console os and games function.. We don't see many hacks on console.. Wonder why? Because they can't load them onto the console and if they could the consoles os wouldn't be able to even read it recognize it.

---
Tags: 3d, networking, first-person-shooter, anti-cheat
---


# Question
Title: What is the intended usage of the Sprite class in LibGDX
I am making a small game in LibGDX and it all works, sprites are moving etc. The drawing is mainly done in the render() method of a Screen, using Batch.draw(TextureRegion). So far so good.

But now I would like my sprites to rotate. There are Batch draw methods for rotation (I think), but I noticed a bunch of useful methods in tne Sprite class. Problem is I do not know how to use them without making the rest of the program ugly.

I could have a Sprite as a member of each "game object", but that makes direct dependency of the game model on drawing mechanism, specifically LibGDX. Besides I can see problems with serialization and duplicate parameters (Sprite x,y vs model x,y etc) and unnecessary overhead.

Or I could subclass Sprite, which would probably be orders of magnitude messier.

Is there a common way of clearly separating the model part and rendering part of a small game? And how is Sprite typically used?

# Answer
The `Sprite` class is just that. A `Sprite`. It represents a texture in 2D space that can be transformed (moved, rotated, scaled) however you like. Think of it as a more sophisticated `Texture` (or `TextureRegion`) class that is used in the same way.

Your characters should probably not extend `Sprite` since your characters *aren't* sprites, they *have* sprites. Hence your character class would *contain* a `Sprite` not *extend* from it.

A minimalistic character class might look something like this:

```
public class Character {
    private float x, y; //Position
    private Sprite sprite;

    public void update() {
        // Before this update character velocity, position, etc...
        sprite.setPosition(this.x, this.y);
    }

    public void draw(Batch batch) {
        // This is how you draw a sprite.
        sprite.draw(batch);
    }
}

```

As for unnecessary overhead and serialization etc. you shouldn't worry. Premature optimization like that is the bane to everyone's existence. But you should never serialize textures of any kind anyways so you should probably make your sprite field `transient` (see this question if you don't know what `transient` is).
> 2 votes

---
Tags: libgdx, architecture, sprites
---


title: Getting crash on glDrawElements

text:
# Question
Title: Getting crash on glDrawElements
Here is the code where I initialize the VAO, vertex attributes(also the main VBO) and EBO(im using my own wrapper class for these "databuffers" to hide some of the API features and make life easier so i dont think the problem will be in the generic class as it was working without problems)

```
void initVAOManager(const bool& ebo) {

    if (_vaoID == 0)
        glGenVertexArrays(1, &_vaoID);

    glBindVertexArray(_vaoID);

    /**
    Here is the main data buffer (positions,colors,UVs)
    If it doesn´t exist a new one is created
    **/
    if (!_mainBuffer)
        _mainBuffer = new DataBuffer<T>(GL_ARRAY_BUFFER);

    _mainBuffer->bindBuffer();

    if (!_eboBuffer && ebo) {

        _eboBuffer = new DataBuffer<eboData>(GL_ELEMENT_ARRAY_BUFFER);

        _eboBuffer->bindBuffer();
    }

    //This is the position
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));

    //Color attrib pointer
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, color));

    //UV
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, uv));

    _mainBuffer->unbindBuffer();

    if (ebo)
        _eboBuffer->unbindBuffer();

    glBindVertexArray(0);
}

```

Then the render function (dont mind the for loop, as i want to render multiple objects from the batch in one function):

```
void renderBatchNormal()
{
    uploadData();

    glBindVertexArray(_VAOManager->getVAO());

    std::vector<eboData>

    for (std::size_t i = 0; i < _DATA.size(); i++) {
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    }

    glBindVertexArray(0);

    clearData();
}

```

The upload data function send a data from the vectors to their buffers, I can send it too but as Im using my generic wrapper and it worked before with normal drawings I assume there is no problem. And finally a class eboData(if anyone wondered) (basically just a blank class with an array of 6 indices)

```
class eboData {
public:
    GLuint indices[6];
};

```

However, this is causing crashes on the line where I try to execute the **glDrawElements** command, I read that it can be caused with no binded VAO while binding the ELEMENT BUFFER but as you can see from the code I´m doing it right(at least I think that). However, if I change the following line with:

```
std::vector<eboData> _eboVector;

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, _eboVector.data());

```

The code is working (problem is also that I don´t know how to render second item in the buffer as it is showing only the first one). Do you have any ideas what can cause this crash?

PS: glGetError() returns 0.

# Answer
**You're crashing because you unbind**.

If you check your creation code, you'll see that \_eboBuffer is first bound. At this stage \_eboBuffer is stored in your VAO and all is well. Then at the end you unbind \_eboBuffer, at which stage it's no longer stored in your VAO.

Unbinding, in general, is something that's actually not necessary and I would discourage it as a bad practice. Bind everything you need to use before you use it instead, and that way you can be certain that your state is what you intend.
> 1 votes

---
Tags: opengl, rendering, index-buffer
---