# Question
Title: Unused methods after component inheritance in component based architecture?
I have a **GameObject** class, which contains Components, like:

* Renderer
* Camera
* Behaviour
* Rigidbody

First **I inherited all of them from Component** which has an Update() method, and it is called every frame on every game objects' every component.

But then I noticed, that\** Renderer and Camera's Update method is unused\**. *(There are classes like RenderData & CameraData which are isolated and made from primitives, and upon creation of these Components, these Data's pointer is sent to the GraphicsEngine which will process them every frame.)*

So having an unused method is bad. So **I created a DynamicComponent class**, which inherits from Component, and Behaviour & Rigidbody classes are inherited from it.

I moved the Update() from Component to DynamicComponent, and **I have now 2 containers at gameobjects**:

* Components (for components which are inherited directly from Component)
* Dynamic Components (for components which are inherited from D.Comp.)

And every frame I only call DynamicComponents' Update().

Now I'm having another issue. **There is the Behaviour class, where should be a Start() method**, which is called on every Behaviour when the scene is fully initalized.

That means that I should **have a Components, D.Components and also a Behaviours container** at game objects.

**This looks very bad to me.**

Having a Component class, with Start(), Update(), etc is very simple and makes a very clean code, but this means that only a few derived classes implement its virtual methods.

What should I do?

# Answer
> 1 votes
Basically I'm with truthastup. I'm kind of a fan of the so called ECS pattern, which separate data and logic for Component and System. I think it's the pattern is good at making the engine architecture modular and flexible. I've also implemented a version of my own but it hasn't been used in commercial game, though.

On the other hand, the architecture you're using is more like Unreal and Unity engine, which is, lets say more conventional, but it's also easy to use. So follow this architecture is totally fine, there are many users of Unreal and Unity, which proves it can work, myself is also developing game by Unreal engine right now.

Anyway, the point is, I think to have so many layers of inheritance of Component is kind of shooting itself in the foot. The origin of Component based design is to let composition over inheritance and make things easier. So I'd say to have only one base class of Component and design a set of common virtual functions (Start(), Update() etc.) is very good to go.

You mentioned the problem that only a few derived classes implement some virtual functions, I think it's totally fine, since virtual functions are not always needed to be implemented. They are virtual because they "maybe" overridden, but not necessarily.

If your game engine is to be released for the public some day, then I'd strongly recommend to stick with a single Component base class and have all possible virtual functions in it, which is following the Unity way. Comparing Unity and Unreal's component based design, I'd say Unity is totally a winner, their architecture is clearer and easier to learn and use, and is more "component like". But Unreal's code base is far more older than Unity's, so maybe it's unfair/pointless to compare them, though.

# Answer
> 2 votes
> Having a Component class, with Start(), Update(), etc is very simple and makes a very clean code

I'm not sure this is true. In my code, Components are simple data structures without any functionality. They just keep some info about this GameObj.

For instance:

```
class GraphicsComponent: public Component{
    public:
    unsigned int gameobj_id;
    float posx, posy, posz;
    float scaling;
    std::string material_name;
}

```

My Systems have Init(), Update(), etc, and will update the Components during those functions. in `Engine::StartRunning()` I call every System's Init() function. Then, when I start my gameloop, I call every System's Update() function over and over again until someone tells me to stop.

```
class GraphicsSystem: public System{
public:
    void Init(){
        // *set up initial GameObj components* //
    }
    void Update(float delta_time){
        HandleSystemMessagesAndInput();
        // *do stuff with components* //
    }

    std::vector<GraphicsComponent> gfx_comps;
};

```

Different Systems will keep 'their data' about the GameObjs (it's all inside that Component), but they will have functions implementing their functionality. For example, `PhysicsSystem` will have a `PhysicsSystem::HandleCollisions( PhysicsComponent *phys_comp_a, PhysicsComponent *phys_comp_b)` function.

I still keep a global container of GameObjs for convenience, but that's kind of taboo. However, I find it useful to hang a GameObj's Components on a GameObj struct for intra-System bailouts. In reality I only really use this during Component add/remove (each System does its own Component adds/removes) and I would warn you against thrashing the cache by doing it too often.

P.S. This link has some good discussion about the tradeoffs in using different approaches: http://gameprogrammingpatterns.com/component.html

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


title: Incomplete rendering using OpenTK (VBO)

text:
# Question
Title: Incomplete rendering using OpenTK (VBO)
Using Assimp.net I did load obj file. assimp returns back Mesh object that contains vertexes, normals, faces, colors and texture. when I don't use VBO the object will load complete. like this :

But when I use VBO, rendering of object is incomplete. like this :

Here is my source code :

```
public class VBO : GameWindow
{
    public Mesh InputMesh { get; set; }
    Vbo vbo = new Vbo();
    int textureID;

    public VBO() : base(800, 600)
    {
        Keyboard.KeyDown += OnKeyDownInternal;
    }

    public VBO(Mesh mesh) : this()
    {
        this.InputMesh = mesh;
    }

    private void OnKeyDownInternal(object sender, KeyboardKeyEventArgs e) { OnKeyDown(e); }

    protected virtual void OnKeyDown(KeyboardKeyEventArgs e)
    {
        switch (e.Key)
        {
            // Lighting
            case OpenTK.Input.Key.L:
                if (GL.IsEnabled(EnableCap.Lighting)) GL.Disable(EnableCap.Lighting);
                else GL.Enable(EnableCap.Lighting);
                break;

            // Texture
            case OpenTK.Input.Key.T:
                if (GL.IsEnabled(EnableCap.Texture2D)) GL.Disable(EnableCap.Texture2D);
                else GL.Enable(EnableCap.Texture2D);
                break;

            // Dynamic Update
            case OpenTK.Input.Key.D:
                dynamicUpdate = !dynamicUpdate;
                break;

            // Exit
            case OpenTK.Input.Key.Escape:
                Exit();
                break;
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        GL.ClearColor(0.1f, 0.1f, 0.5f, 0.0f);
        GL.Enable(EnableCap.DepthTest);

        // Vertex Buffers
        vbo = LoadVBO(InputMesh);

        // Lighting
        GL.Enable(EnableCap.Light0);
        GL.Enable(EnableCap.Lighting);

        // Texture
        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Fastest);

        GL.GenTextures(1, out textureID);
        GL.BindTexture(TextureTarget.Texture2D, textureID);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

        //Bitmap bitmap = new Bitmap("..\\..\\Data\\logo.jpg");
        /*
        Bitmap bitmap = new Bitmap("3Pod_Lorna_001.png");
        BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
            ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        {
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
                OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
        }
        bitmap.UnlockBits(data);*/

        GL.Enable(EnableCap.Texture2D);
    }

    protected override void OnResize(EventArgs e)
    {
    }

    protected override void OnUpdateFrame(FrameEventArgs e)
    {
    }

    double counter = 0;
    protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

        GL.PushAttrib(AttribMask.LightingBit);
        GL.Disable(EnableCap.Lighting);
        GL.Color3(Color.White);
        /*
        textPrinter.Begin();
        textPrinter.Draw((1.0 / e.Time).ToString("F2"), font);
        GL.Translate(150, 0, 0);
        textPrinter.Draw("(L)ighting  (T)exture  (D)ynamicUpdate", font);
        textPrinter.End();
        */
        GL.PopAttrib();

        GL.MatrixMode(MatrixMode.Modelview);
        GL.LoadIdentity();
        Matrix4 modelview = Matrix4.LookAt(0.0f, 3.5f, 3.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
        GL.LoadMatrix(ref modelview);

        counter += e.Time;
        GL.Rotate(counter * 50, 0, 1, 0);

        Draw(vbo);

        SwapBuffers();
    }

    #region Upload
    private void GenAndFillBuffer(out int outGlBufferId, List<Vector3D> dataBuffer)
    {
        GL.GenBuffers(1, out outGlBufferId);
        GL.BindBuffer(BufferTarget.ArrayBuffer, outGlBufferId);
        var byteCount = dataBuffer.Count * (sizeof(float) * 3);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(byteCount), dataBuffer.ToArray(), BufferUsageHint.StaticDraw);

        VerifyBufferSize(byteCount);
        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
    }

    private void VerifyBufferSize(int byteCount)
    {
        int bufferSize;
        GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
        if (byteCount != bufferSize)
        {
            throw new Exception("Vertex data array not uploaded correctly - buffer size does not match upload size");
        }
    }

    private void UploadColors(out int colorBufferId, Mesh mesh)
    {
        GL.GenBuffers(1, out colorBufferId);
        GL.BindBuffer(BufferTarget.ArrayBuffer, colorBufferId);

        var colors = mesh.VertexColorChannels[0];
        // convert to 32Bit RGBA
        var byteCount = colors.Count * 4;
        var byteColors = new byte[byteCount];
        var n = 0;
        foreach (var c in colors)
        {
            byteColors[n++] = (byte)(c.R * 255);
            byteColors[n++] = (byte)(c.G * 255);
            byteColors[n++] = (byte)(c.B * 255);
            byteColors[n++] = (byte)(c.A * 255);
        }

        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(byteCount), byteColors, BufferUsageHint.StaticDraw);

        int bufferSize;
        GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
        if (byteCount != bufferSize)
        {
            throw new Exception("Vertex array not uploaded correctly");
        }

        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
    }

    private void UploadTextureCoords(out int texCoordBufferId, Mesh mesh)
    {
        GL.GenBuffers(1, out texCoordBufferId);
        GL.BindBuffer(BufferTarget.ArrayBuffer, texCoordBufferId);

        var uvs = mesh.TextureCoordinateChannels[0];
        var floatCount = uvs.Count * 2;
        var temp = new float[floatCount];
        var n = 0;
        foreach (var uv in uvs)
        {
            temp[n++] = uv.X;
            temp[n++] = uv.Y;
        }

        var byteCount = floatCount * sizeof(float);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(byteCount), temp, BufferUsageHint.StaticDraw);
        VerifyBufferSize(byteCount);
        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
    }

    private void UploadFaces(out int elementBufferId, out int indicesCount, out bool is32Bit, Mesh mesh)
    {
        GL.GenBuffers(1, out elementBufferId);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, elementBufferId);

        var faces = mesh.Faces;

        // TODO account for other primitives than triangles
        var triCount = 0;
        int byteCount;
        is32Bit = false;
        foreach (var face in faces)
        {
            if (face.IndexCount != 3)
                continue;
            ++triCount;
            if (face.Indices.Any(idx => idx > 0xffff))
                is32Bit = true;
        }

        var intCount = triCount * 3;
        if (is32Bit)
        {
            var temp = new uint[intCount];
            byteCount = intCount * sizeof(uint);
            var n = 0;
            foreach (var idx in faces.Where(face => face.IndexCount == 3).SelectMany(face => face.Indices))
                temp[n++] = (uint)idx;

            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)byteCount,
                temp, BufferUsageHint.StaticDraw);
        }
        else
        {
            var temp = new ushort[intCount];
            byteCount = intCount * sizeof(ushort);
            var n = 0;
            foreach (var idx in faces.Where(face => face.IndexCount == 3).SelectMany(face => face.Indices))
                temp[n++] = (ushort)idx;

            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)byteCount, temp, BufferUsageHint.StaticDraw);
        }

        int bufferSize;
        GL.GetBufferParameter(BufferTarget.ElementArrayBuffer, BufferParameterName.BufferSize, out bufferSize);
        if (byteCount != bufferSize)
        {
            throw new Exception("Index data array not uploaded correctly - buffer size does not match upload size");
        }

        GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
        indicesCount = triCount * 3;
    }

    Vbo LoadVBO(Mesh mesh)
    {
        Vbo vbo = new Vbo();

        if (mesh.VertexCount == 0) return vbo;
        if (mesh.FaceCount == 0) return vbo;

        // Color Array Buffer
        if (mesh.HasVertexColors(0))
            UploadColors(out vbo.ColorBufferId, mesh);

        // Normal Array Buffer
        if (mesh.HasNormals)
            GenAndFillBuffer(out vbo.NormalBufferId, mesh.Normals);

        // TexCoord Array Buffer
        if (mesh.HasTextureCoords(0))
            UploadTextureCoords(out vbo.TexCoordBufferId, mesh);

        // Vertex Array Buffer
        if (mesh.HasVertices)
            GenAndFillBuffer(out vbo.VertexBufferId, mesh.Vertices);

        // Element Array Buffer
        if (mesh.HasFaces)
            UploadFaces(out vbo.ElementBufferId, out vbo.NumIndices, out vbo.Is32BitIndices, mesh);

        // Store the number of elements for the DrawElements call
        vbo.NumIndices = mesh.FaceCount;

        return vbo;
    }

    #endregion

    void Draw(Vbo vbo)
    {
        // Push current Array Buffer state so we can restore it later
        GL.PushClientAttrib(ClientAttribMask.ClientVertexArrayBit);

        if (vbo.VertexBufferId == 0) return;
        if (vbo.ElementBufferId == 0) return;

        if (GL.IsEnabled(EnableCap.Lighting))
        {
            // Normal Array Buffer
            if (vbo.NormalBufferId != 0)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, vbo.NormalBufferId);
                GL.NormalPointer(NormalPointerType.Float, Vector3.SizeInBytes, IntPtr.Zero);
                GL.EnableClientState(ArrayCap.NormalArray);
            }
        }

        // Color Array Buffer (Colors not used when lighting is enabled)
        if (vbo.ColorBufferId != 0)
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo.ColorBufferId);
            GL.ColorPointer(4, ColorPointerType.UnsignedByte, sizeof(int), IntPtr.Zero);
            GL.EnableClientState(ArrayCap.ColorArray);
        }

        // Texture Array Buffer
        if (GL.IsEnabled(EnableCap.Texture2D))
        {
            if (vbo.TexCoordBufferId != 0)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, vbo.TexCoordBufferId);
                GL.TexCoordPointer(2, TexCoordPointerType.Float, 8, IntPtr.Zero);
                GL.EnableClientState(ArrayCap.TextureCoordArray);
            }
        }

        // Vertex Array Buffer
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo.VertexBufferId);
        GL.VertexPointer(3, VertexPointerType.Float, Vector3.SizeInBytes, IntPtr.Zero);
        GL.EnableClientState(ArrayCap.VertexArray);

        // Element Array Buffer
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, vbo.ElementBufferId);
        GL.DrawElements(BeginMode.Triangles, vbo.NumIndices, vbo.Is32BitIndices ? DrawElementsType.UnsignedInt : DrawElementsType.UnsignedShort, IntPtr.Zero);

        // Restore the state
        GL.PopClientAttrib();
    }

    struct Vbo
    {
        public int VertexBufferId;
        public int ColorBufferId;
        public int TexCoordBufferId;
        public int NormalBufferId;
        public int ElementBufferId;
        public int NumIndices;
        public bool Is32BitIndices;
    }
}

```

Where is my mistake?

# Answer
Finally I found the answer!

I changed this line :

```
GL.DrawElements(BeginMode.Triangles, vbo.NumIndices, vbo.Is32BitIndices ? DrawElementsType.UnsignedInt : DrawElementsType.UnsignedShort, IntPtr.Zero);

```

to This :

```
GL.DrawElements(BeginMode.Triangles, vbo.NumIndices * 3, vbo.Is32BitIndices ? DrawElementsType.UnsignedInt : DrawElementsType.UnsignedShort, IntPtr.Zero);

```

and problem solved.
> 0 votes

---
Tags: c#, opengl, vbo, opentk, assimp
---


# Question
Title: Data flow: Game design balancing data to game
I'm thinking about how to get the game design balancing data (unit values, quest conditions etc.) to a game. I wonder how you would solve/have solved it?

Conditions:

* Java server
* Unity mobile client (C# scripting language)
* Git based repositories

Requirements:

* Client needs balancing data
* Server needs balancing data
* Data origin must be Excel
* Data has be available on mobile without doing an app update

**First problem: Transform excel data in something readable and get it to the client/server.**

My idea would be to transform the excel data to JSON and commit/push it.

**Second problem: How do the client/server get the data?**

My idea would be to have a service running which delivers the data via HTTP.

These ideas are quite primitive and that must be a problem many games had so solve. Didn't find any useful though.

# Answer
> 1 votes
> My idea would be to transform the excel data to JSON and commit/push it.

Did you consider using Excel CSV files? They are just rows separated by line-breaks with values separated by semicolons. This is very version-control friendly, it is easy to write a parser for this on your server and you can just edit them with Excel without having to do any more conversion than pressing save.

Another option is to use Excel to edit XML files. This requires some work to set up, but gives you more features than plain CSV.

> My idea would be to have a service running which delivers the data via HTTP.

You can do that, but considering that your server needs to read and parse the data anyway, you can also have your server send it to the client as part of your game protocol. You could either dump all the data on login or during play when the data is first needed. You could develop a fancy protocol for encoding your game data as space-conserving as possible, but unless you already know that your data will be very large, this is likely premature optimization. And if you decide that you need to conserve bandwidth, you will likely get almost the same results by simply sending your data through a stock compression algorithm like Zip.

# Answer
> 0 votes
First, your storage type. Let's think about it, what can be a bigger bottleneck, calculating stuff client side or sending data from client to server? Obviously the latter one.

Let's look at the same data in both json and a format made for this:

```
{"a":"Some String","b":{"c":9,"d":10}}

|a.Some String,b-|c-9,d-10||

```

A lot shorter. Especially if you send a lot of data through a connection that' not really made for these kinds of things. The latter one actually is just a simplification for json. Everything is there and I'm sure it can be converted to a JSON object on client side. Why use a pre-made format, if you can optimize it?

The second problem: Getting the data.

This depends on what you want. If the data is not mandatory, and can be updataed some time later, then I'd do something like the following:

```
1.) Server sends a message to the client's about the new data, **but it doesn't send the data itself**.
2.) Here the client can say 2 things:
    a) It's busy, he will get the data later
    b) You can send the data eithout a problem, so you send it
3.) In case a) if the phone becomes available to get the data, he sends a message requesting it, and then the server sends it.

```

If the data is mandatory, then leave out case a)

---
Tags: game-design, dataflow
---


# Question
Title: How to throw b2body with various speed at fixed position?
Above image is for ref to better representation.

I have box2d object and i know start point & end point position.

Now i want to give any force or impulse such that b2body will first collide at end point BUT with different speed also should collide at that same end point.

How should i achieve this?

# Answer
Let's say you have a gravity force `g` (m/s²). The horizontal speed doesn't change, so you first need to calculate the amount of time it reaches the target horizontally:

```
t = distanceX / speedX

```

The object need tk reach the target in the same time vertically too. We will have a speed of `vY` (m/s) at start and `vY - g * t` (m/s) at the end vertically (positive speed goes upwards). The average vertical speed is

```
vAvg = (vY + vY - g * t) / 2 = vY - g * t / 2

```

This average speed needs to be so big, that the object would reach the target position in time t if there's no gravity

```
vY - g * t / 2 = distY / t

```

You should be able to get the starting upwards velocity by adding `g * t / 2` to `distY / t`

So, together, to get the vertical speed vY, you need to do:

```
t = distX / vX
vY = distY / t + g * t / 2

```
> 1 votes

---
Tags: physics, box2d, physics-engine
---


title: Unity3D Automatic Mipmap

text:
# Question
Title: Unity3D Automatic Mipmap
I'm using Unity3D. I'm working advanced topics. For example Mipmap.

How I can automatic mipmap (use camera distance) for textures?

Thank you.

# Answer
> 1 votes
Just check the box in texture import settings to enable mipmap generation. They are automatically in use.

For the mipmaps to have any effect, you need to have bilinear or trilinear filtering enabled. Nothing else has to be done if you are not manually trying to read the mip levels in custom shaders.

---
Tags: unity
---


# Question
Title: Marble / Wheel Game Physics - Kinetic vs Static Friction?
I've read a bit about the "normal force" modeling of friction here. I gather that it isn't a full picture, but a decent approximation, if it fits the needs of what you are trying to model.

It mentions that there's a static friction and a kinetic friction where the static friction is the amount of force that needs to be overcome before an object will begin moving, and then the kinetic friction specifies how much force you need to apply to keep the object moving.

For the case of a ball rolling or a wheel spinning, I know that a little bit of force will cause it to roll, while applying a lot of force will cause it to "slip" and lose contact / friction with the ground and start spinning.

In this case, is it the static friction that determines how much force you can apply to a wheel or a ball before it starts to slip, and then it's the kinetic friction that determines how it acts when it is slipping?

# Answer
> 2 votes
**TL;DR: Static friction.**

---

The amount of force needed to make the ball "slip" is determined by static friction.

Actually it's not too hard to understand: When the ball is not "slipping", in each infinitesimal moment of time the point of it which touches the surface doesn't move relative to it.

If the ball *is* "slipping", the dynamic friction determines how quickly it's angular velocity is being converted to linear velocity.

---
Tags: physics
---


# Question
Title: How to add a logo icon for my game in Java using Eclipse?
I really don't like the Java symbol as the icon for my game so I'd like to use a custom one isteand.

How and where would I add it into this code:

```
package Destiny;

public class Destiny_Starting_Window extends JPanel{

  JFrame window = new JFrame("DESTINY BETA 1.0 PC EDITION");
  Destiny_Starting_Window()
  {
    window.add(this);

    try{
      File sound = new File("Sounds//Main Menu.wav");
      AudioInputStream ais = AudioSystem.getAudioInputStream(sound);
      Clip clip = AudioSystem.getClip();
      clip.open(ais);
      clip.start();

    }catch(Exception e){
      System.out.println(e);
    }

    window.setLocation(341,192);
    window.setUndecorated(false);
    window.setSize(1366 , 768);
    window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    window.setVisible(true);
  }
  public void paint(Graphics g)
  {
    ImageIcon background = new ImageIcon("Images//Destiny Main.png");

    g.drawImage(background.getImage(),0,0,null);
  }
}

```

# Answer
When you compile your Java code, you are compiling it as **Java bytecode**.

It is not a standard executable, thus there is no definition of an "Icon" to it or anyone else. The operating system will use an Icon associated for Jar files, which gives the "Java symbol" as an icon.
> 0 votes

---
Tags: java
---


# Question
Title: Custom Editor for Map/Dictionary in Unity
I'm trying to build my own little ResourceManager in Unity that will allow me to tag resources (ranging from materials to prefabs) to a label in the editor, and then access them in game.

The ResourceManager itself is really easy to write- it's just a Dictionary. However the Unity Editor doesn't seem to be able to serialize (and thus render) Dictionaries.

To get around this, I created a list of key-value pairs which gets loaded into the dictionary by unity. That way Unity gets its list and I get my Dictionary. However, when I try and run the code shown below, I can only add a single entry to the list. Any idea what I'm doing wrong?

ResourceManager.cs

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

public class ResourceManager : MonoBehaviour, ISerializationCallbackReceiver {
    private Dictionary<string, Object> resources = new Dictionary<string, Object>();

    #region Unity
    // Unity doesn't know how to deal with maps, so we give it a list to work with
    public List<ResourceEntry> entries;

    // Dictionary -> List
    public void OnBeforeSerialize() {
        entries.Clear();
        foreach(string key in resources.Keys) {
            entries.Add(new ResourceEntry(key, resources[key]));
        }
    }

    // List -> Dictionary
    public void OnAfterDeserialize() {
        resources = new Dictionary<string, Object>();
        foreach(ResourceEntry entry in entries) {
            resources[entry.key] = entry.value;
        }
    }

    [System.Serializable]
    public class ResourceEntry {
        public string key;
        public Object value;

        public ResourceEntry() {}

        public ResourceEntry(string key, Object value) {
            this.key = key;
            this.value = value;
        }
    }
    #endregion

    private static ResourceManager instance;
    public static Object Get(string category, string key) {
        instance = instance ?? GameObject.FindObjectOfType<ResourceManager>();
        if( instance.resources.ContainsKey(key)) {
            return instance.resources[key];
        } else {
            return null;
        }
    }
}

```

ResourceManagerEditor.cs

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

[CustomEditor(typeof(ResourceManager))]
public class ResourceManagerEditor : Editor {
    private ReorderableList list;

    public void OnEnable() {
        list = new ReorderableList(serializedObject, serializedObject.FindProperty("entries"), true, true, true, true);
        list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
            SerializedProperty element = list.serializedProperty.GetArrayElementAtIndex(index);
            rect.y += 2;
            EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("key"), GUIContent.none);
            EditorGUI.PropertyField(new Rect(rect.x + 70, rect.y, 160, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("value"), GUIContent.none);
        };
        list.drawHeaderCallback = (Rect rect) => {
            EditorGUI.LabelField(rect, "Resources");
        };
    }

    public override void OnInspectorGUI() {
        serializedObject.Update();
        list.DoLayoutList();
        serializedObject.ApplyModifiedProperties();
    }
}

```

# Answer
The issue is, that a dictionary cannot contain the same key multiple times, but when Unity creates a new entry of your list, whenever you resize it in the inspector, it will just copy the last item. This means, you are trying to add a key, which already exists to the dictionary. This doesn't work and could throw an exception, but in your case, you were simply replacing the existing first entry with the new one, therefore never growing bigger than one.

```
public void OnAfterDeserialize()
{
    // No need to create the dictionary again, just clear it out.
    resources.Clear();

    foreach (ResourceEntry entry in entries)
    {
        // This "works" but hides your mistake.
        // If resources[key] doesn't exist or already exists,
        // this key will simply be created or overriden.
        resources[entry.key] = entry.value;

        // To show the mistake, make this line explicitly throw an error
        // when you try to add a key, that already exists:
        resources.Add(entry.key, entry.value);
    }
}

```

Now you will notice, that you are trying to add the same key twice, which throws an error. To work around this, you can easily use your existing custom editor and instead of copying the last item, create a new one with a unique key.

Here is the complete working code:

```
using UnityEngine;
using System.Collections.Generic;
using UnityEditor; // Remember to move editor code into Editor folder or #if UNITY_EDITOR
using UnityEditorInternal;

public class ResourceManager : MonoBehaviour, ISerializationCallbackReceiver
{
    private Dictionary<string, Object> resources = new Dictionary<string, Object>();

    // Hide this, because it will not work correctly without the custom editor.
    [HideInInspector]
    [SerializeField]
    private List<ResourceEntry> entries = new List<ResourceEntry>();

    // Dictionary -> List
    public void OnBeforeSerialize()
    {
        entries.Clear();
        // You can iterate a dictionary like this if you want.
        foreach (KeyValuePair<string, Object> kvp in resources)
        {
            entries.Add(new ResourceEntry(kvp.Key, kvp.Value));
        }
    }

    // List -> Dictionary
    public void OnAfterDeserialize()
    {
        resources.Clear();
        foreach (ResourceEntry entry in entries)
        {
            resources.Add(entry.key, entry.value);
        }
    }

    [System.Serializable]
    public class ResourceEntry
    {
        public string key;
        public Object value;

        public ResourceEntry() { }

        public ResourceEntry(string key, Object value)
        {
            this.key = key;
            this.value = value;
        }
    }
}

[CustomEditor(typeof(ResourceManager))]
public class ResourceManagerEditor : Editor
{
    private ReorderableList list;

    public void OnEnable()
    {
        list = new ReorderableList(serializedObject, serializedObject.FindProperty("entries"), true, true, true, true);
        list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
        {
            SerializedProperty element = list.serializedProperty.GetArrayElementAtIndex(index);
            rect.y += 2;
            EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("key"), GUIContent.none);
            EditorGUI.PropertyField(new Rect(rect.x + 70, rect.y, 160, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("value"), GUIContent.none);
        };

        list.onAddCallback = (ReorderableList list) =>
        {
            int index = list.serializedProperty.arraySize;
            list.serializedProperty.arraySize++;
            list.index = index;

            // Important! When adding a new element to the list (and dictionary),
            // the newly created key must be unique.
            SerializedProperty element = list.serializedProperty.GetArrayElementAtIndex(index);
            element.FindPropertyRelative("key").stringValue = System.Guid.NewGuid().ToString(); // Create some kind of unique key, like a GUID or adding a number to the last one.
        };
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        list.DoLayoutList();
        serializedObject.ApplyModifiedProperties();
    }
}

```

The only change that matters to your specific question is the "onAddCallback" in the custom editor. There you can change the way Unity creates a new list element and give it a unique key at initialization. Remember, you can still edit the value in the inspector, but should make sure that the user doesn't enter a key, that already exists somewhere else.
> 1 votes

# Answer
I believe your problem here is that you are clearing out your list in OnBeforeSerialize() and recreating it in onAfterDeserialized(). I think your problem is that you are expecting OnAfterDeserialized() to be called after OnBeforeSerialize() and after you have added a new item to your list in the custom inspector (a reasonable assumption).

However this does not seem to be how Unity works. OnBeforeSerialize() gets called fairly frequently but OnAfterDeserialized() does not always get called afterwards. If you add some debug log messages to both these methods you will be able to see this issue yourself in the editor.

This unfortunately means that you end up clearing out your list in the first method, and then it gets cleared out again before the second method has had a chance to recreate the dictionary from your list.

There is another question posted here discussing this issue and it points to a Unity blog post here discussing the Serialization system in Unity.

Hope that helps
> 0 votes

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


# Question
Title: Can A* path finding cost functions allow for path following shapes?
Recently I begun developing a game prototype which could create procedural generated dungeons using a collection of room types. To ensure the hallway paths between these rooms would always be connected I implemented a A\* path finding algorithm following along the tile map of randomly placed rooms.

The problem with doing this however is I was not necessarily trying to find the shortest path between rooms which in most cases would be a diagonal. Since being thematically a 'dungeon' I wanted them to twist and turn at 90 degree angles. By using a Manhattan distance for the heuristic I managed to get the intended shape but I've ended up with one final problem which I come to you kind people to help me with :).

Though now using 90 degree angles to move the path, its saves doing the run till the end of path(See picture below). This makes the whole thing at a distance feel cramped in places instead of using all the space effectively. Seeing how simply changing the heuristic from distance to Manhattan distance has made a difference my question is, is there a cost function I could implement that would give the desired results of this non conventional path? Any answers would be appreciated, thank you.

**Note:** The algorithm also has access to the normal direction of the start and end goals.

# Answer
> 3 votes
Your problem is simple, and as such the solution is too. What you want essentially, is for any time that your A\* connects two rooms whose doors are 90 degrees from each other to remain standard, when the doors connecting two rooms are 180 degrees from each other, use the A\* algorithm twice in the generation phase, from the door to the separating midpoint (rounded to that nearest tile of course) and from that tile to the next door.

# Answer
> 2 votes
Manipulate the tile cost function to make use of the distances (as the crow flies) from start to destination, in addition to the Manhattan distances. Add weights to these halves of the cost function so that you can prioritize the Manhattan distance, and produce a desirable result with little effort.

The smaller weight you apply to the crow-distance relative to the Manhattan distance, the more likely the desired Manhattan distance will take over. If your current algorithm has a 50/50 choice, you want to sway the decision into picking a tile further from your room.

# Answer
> 1 votes
I think the easiest way would be to implement a penalty for straightaways longer than a certain amount; say, half the distance between the two points you're trying to connect, rounded down to the nearest unit of measurement you're using (grid square?).

A harder way would be to take the solution and break it up into pieces; for instance, if the solution is up 5, over 5, you could break it into up 2, over 5, up 3. The problem with this solution is it might not be a valid path -- my first suggestion is better because you are modifying the algorithm to find a better path that will always work instead of taking a path and making it better such that it might not work.

---
Tags: path-finding, procedural-generation, heuristics
---


# Question
Title: What is the difference between getWidth and getBackBufferWidth in LibGDX?
In regards to `gdx.graphics`, what is the difference between using `getWidth` and `getHeight`, and using `getBackBufferWidth` and `getBackBufferHeight`?

---

I am learning LibGDX and Java. I programmed formerly in pygame. To my knowledge, `getBackBuffer` means the width and height of the actual window. Is that true?

# Answer
The documentation explains it. `getWidth` and `getHeight` return the size of the *client area* (this is generally the usable portion of your game window). `getBackBufferWidth` and `getBackBufferHeight` return the size of the *frame buffer*, where actual drawing happens before it's presented to the window.

Sometimes these values differ; for example you might render to frame buffer that is smaller than the window and let presentation to the window upsample it, to achieve a "pixelated" effect. Similarly you might use a larger frame buffer and let it downsample to achieve a crude anti-aliasing effect.

You can look at the source to verify this; note that the specifics of the behavior of the functions differ based on which backend ends up being used. For example, compare this implementation with this one.
> 1 votes

---
Tags: libgdx
---


# Question
Title: Data-oriented design and Component Sytem cross-referencing
Let's assume we're talking about a game (engine) which is written in C++. This is more like a design question but I can't find any suitable description.

**Component System**

The Component System says that an Entity in the world is defined by its components. This system is flexible, modular and really powerful. I've used Unity (a lot) and I like its concept. This also solves the traditional class-hierarchy problem.

Example components:

* **StaticTransform**: Position, Rotation, Scale - a StaticTransform can be a child (and of course a parent) of another StaticTransform (this describes the Entity-hierarchy in the scene)
* **Rigidbody/Transform**: Position, Rotation, Force, etc. - I could use the StaticTransform data, but I'd like to separate the concepts. That's why I have Position and Rotation (but not Scale) data. A Rigidbody can not be a child of another object but can be a parent of StaticTransform.
* **MeshRenderer**: LocalBounds, WorldBounds, Mesh, Material - this component is used to generate draw calls to render the mesh with a specific material.
* **AudioSource**: AudioData - A simple audio source which can be world-space (using one of the transforms) or global (in this case the transform component is irrelevant)
* **AudioListener**: Only one AudioListener is allowed. Most of the time it's added to the player's Entity. It uses the transform's data.
* **Camera**: FoV, Clipping planes, etc. - Of course a Camera can be used to render the meshes from that point of view. Multiple cameras are allowed.

**Data-oriented design (DoD)**

The key concept of the DoD is to focus on data and data-access instead of code. There are some additional "rules" like: "When there is one, there are many". Most of the time this means that the data itself is stored in a cache-friendly way: contiguous memory with linear access (aka. iterating the array one-by-one). In a "Component System world" the component itself does not exist but the corresponding system stores and manages the data.

In a system like this, raw or managed pointers are forgotten, instead ids and/or handles (special id with additional info) are used. Most of the time a special entityId -\> componentId map is used to match the entity to the component. This way the component data can be packed (moved in the array) so the iretation is fast (cache-friendly).

In theory this work really well. Blog posts and other discussions show examples how to do it with a single "component". However I cannot find any good solution to the cross-referencing problem.

**The cross-reference problem**

Using the example components described above: The MeshRenderer depends on the (both static and dynamic) Transform component because the World matrix is requried to render/cull the mesh. The AudioSource, Camera and AudioListener also depend on the Transform component.

The entities can be arranged into a hierarchy using the Transform's parent-child relation. When the user updates the transform of a root object, every child Transform must be updated as well. This means we are jumping back-and-forth in the memory.

Rendering all meshes all the time seems to be a bad idea. That's why people implement spatial trees which can be used to cull meshes and other renderable objects efficiently. Again, this kills the cache-friendly part.

**Question**

Should I even use the DoD concept in a complex system like this? The hierarchy, the spatial trees and the cross-referencing kill the linear access (so the cache/prefetcher-friendlyness) advantage. It seems using a "stable vector" (adding/removing elements and resizing the container do not invalidate iterators) is not worse than packed vectors.

Is there any good solution to the problems described above? I like the key concept of the DoD but I'm failing to apply it.

# Answer
> 1 votes
I would not necessarily mimic in the component system the necessary data structures your logic systems require to function. There is an advantage to keeping the component system straight forward and simple and using a layer of indirection here.

As an example, when the level is loaded, an entity is created that contains a `Transform` and a `Mesh` component.

A `RenderComponentSystem` is responsible for detecting this entity has been created, it examines the components of the entity and detects this `Mesh` component. This system is responsible for interacting with the `RenderSystem` so that the mesh is loaded and a specific `RenderSystem` data structure is created, I call a `Renderable`.

This `RenderComponentSystem` also detects that the entity has a `Transform`, and based on whether its a parent `Transform` or a child `Transform`, it interacts with the `RenderSystem`'s scene graph to create a scene node and sets the appropriate position, orientation, and scale.

Finally, the `RenderComponentSystem` attaches the `Renderable` to the scene node.

How the scene graph is traversed or culled is simply a `RenderSystem` detail. From a component system perspective, it doesn't care nor is it concerned. The point is that the component system is meant to provide a simple abstraction for taking a data-driven component when composing entities and influence specific system behavior.

As changes are made to the `Transform` or the `Mesh`, the `RenderComponentSystem` simply iterates the components, clones/updates the attributes on the associated scene node or `Renderable`. This could be done by using a simple map-lookup or some associative pointer between the component and the render system's data structures.

---
Tags: c++, architecture, component-based, data-oriented
---


# Question
Title: How to create custom editor script only for one field of an object and leave the rest default in Unity?
I have a script attached to a game object. The script has many public fields and I'm satisfied with how Unity displays most of the fields for editing in the Editor. Except for a few. I'd like to write a complex custom editor script for those fields and leave the rest as is - public and visible in the Editor. I don't want to write lots of extra code to mimic what the editor does so far.

The perfect scenario would be to be able to define a custom editor script for a certain type (the type is not derived from MonoBehavior and cannot be). If a field of that type is public in any script attached to a GO I'd like the Editor to display it the way I've defined.

# Answer
> 5 votes
In your MonoBehavior script, you can use `[HideInInspector]` to hide your variable.

```
public class GameObjectScript: MonoBehaviour
{
    public int randomInt;

    [HideInInspector]
    public string name;
}

```

---

You can edit your Inspector view by creating an editor script for `GameObjectScript` that inherits from `Editor`.

```
[CustomEditor(typeof(GameObjectScript))]
public class GameObjectScriptEditor: Editor
{

    GameObjectScript myScript;

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector(); //Drawing the default inspector except the one you hide.
                               //Which is only int randomInt

        myScript.name = EditorGUILayout.TextField("My Name: ", myScript.name); //Draw whatever you want in the inspector
    }
}

```

Please note to place the `GameObjectScriptEditor` into `"Asset/Script/Editor"`. You can read more in the Unity documentation.

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


title: Basic LibGDX Game won't run

text:
# Question
Title: Basic LibGDX Game won't run
**Relevant background information**

I'm developing a game in Java & LibGDX. Well, I started a project. I made a game with LibGDX about a year ago before. I made a new project with the Gradle setup and imported it into eclipse. I ran it and it didn't work

**The problem**

In the basic template it displays the badlogic image. It says it's not there or it can't find it.

```
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: badlogic.jpg
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:148)
at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:100)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:92)
at com.kymed.dank.rpg.GameState.create(GameState.java:16)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:149)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: badlogic.jpg (Internal)
at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:136)
at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:222)
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:145)

```

Though it's in the assets folder

# Answer
> 2 votes
Make sure you set the working directory of your runtime configuration for the desktop launch to the `assets` folder, if you have included Android in your project. Otherwise, the assets folder should be `core/assets`.

If that does not fix it, then catch the exception under the debugger, and inspect its nested exception for clues.

---
Tags: java, libgdx
---


title: Monogame Dragging 3D object edges

text:
# Question
Title: Monogame Dragging 3D object edges
I am having trouble rendering 3D models with monogame. The problem only occurs when I export the object from blender with two materials on it. Example:

Monogame sees those two different materials and renders them correctly. Here comes the problem.. When you start moving the object around you can clearly see the edges which are with the snow material dragging or glitching. Image to see what I mean:  As you can see the edges on the bottom with the Stone\_Normal material appear ok but the edges with the snow material are glitching. This is only happening when you move the object around and it doesn't have to be fast. In this example, I am just rotating the object around its axis.

# Answer
> 1 votes
Can't really tell from the image but it could be z flickering. Are you using an unnecessary high far clip value?

Also, how does your transformations handle rotations? I guess your model is divided in sub meshes. Are the rotation and local matrix each mesh working as expected? Can you post the render code?

---
Tags: xna, 3d, monogame, blender
---


# Question
Title: Unity transform.rotation not giving real value
i confused , when the object is at **0 rotation ( not rotated yet )** , it giving real value ( **0** ) , but when the object is **rotated 180 degree** , transform.rotation is giving false value ( **1** ) , this is the screenshot :

If the picture is not clear enough , go here https://i.stack.imgur.com/miWIE.png .

Then this is my script that debugged the code and rotate the object :

```
void RotateFlip() {
    GameObject databasegameobject = GameObject.Find ("database");
    database databasechange = databasegameobject.GetComponent<database>();
    Debug.Log ("current object rotation is " + theiconarrow.transform.rotation.z + " degree ");
    if (databasechange.pengertianmenustate == 2) {
        if (theiconarrow.transform.rotation.z == 0 ) {
            theiconarrow.transform.Rotate (new Vector3 (theiconarrow.transform.rotation.x, theiconarrow.transform.rotation.y, 180), Space.World);
        }

    }

    if (databasechange.pengertianmenustate == 1) {
        if (theiconarrow.transform.rotation.z == 180) {
            theiconarrow.transform.Rotate (new Vector3 (theiconarrow.transform.rotation.x, theiconarrow.transform.rotation.y, 180), Space.World);
        }
    }
}

```

I don't understand why this thing happened , is this a kind of bug or what ?

**I am sorry if this already asked somewhere , but i just don't know how to find it at search engine ( neither here ) .**

Extra question ( optional ) : is there any application to build app with easy coding and not an game engine ?

# Answer
> 1 votes
Unity, like many 3D softwares uses Quaternions to deal with rotation (prevent the Gimbal Lock problem). You get a quaternion when you call `theiconarrow.transform.rotation` (a quaternion is represented by 4 values : x, y, z, w, but are not really the angles around the 3 axis with an additional value).

However, because quaternions are not easily readable by humans, the inspector shows you the euler angles (pitch, yaw, roll) of the rotation (which *are* the angles around the 3 unit axis). In your code, you can get the euler angles by calling : `theiconarrow.transform.eulerAngles`.

---
Tags: unity, 2d, rotation, transformation
---


# Question
Title: How to render sprite array efficiently in j2me game?
I am working on a landscape java game.

I have a sprite array like this;

```
Sprite stickArray[] = new Sprite[10];

```

and initializing it like this with visibility as false.

```
for (int j = 0; j < stickArray.length; j++) {

        if (stickArray[j] != null) {

            stickArray[j].setPosition(stickX, stickY);
            stickArray[j].setVisible(false);
        }
    }

```

Later I want to position it like one after another vertically on repeating a key.pressBool is false initially.

```
public void keyRepeatInGame(int keyCode) {
    int gameKey = getGameAction(keyCode);
    Graphics g = getGraphics();
    if (gameKey == FIRE || keyCode == KEY_NUM5) {
        pressBool = true;
    }
}

```

Later I have written code like this; Initially one Sticksprite is there.above this sprite, I want to place each sticks on clalling keyrepeat()in space key.

```
for (int i = 0; i < stickArray.length; i++) {
            if (pressBool) {
                if (i == 0) {
                    stickArray[i].setPosition(stickSprite.getX(),
                            stickSprite.getY() - stickSprite.getHeight());
                    stickArray[i].setVisible(true);
                } else {
                    stickArray[i].setPosition(stickArray[i-1].getX(),
                            stickArray[i-1].getY() - stickArray[i].getHeight());
                    stickArray[i].setVisible(true);
                }
            }
        }

```

This code is working partially.Stick is getting added on the sprite,all at once.

How can I change the code to make the sticks repeatedly getting added on calling keyrepeat() only, and make it visible one by one properly?

# Answer
> 0 votes
It is adding all of them because you are saying so by doing a loop on all your sticks and setting them as visible. All of them.

What you might want to do is something like this :

```
int index = 0;

while (gameLoopOngoing)
{
    pressBool = checkForKeyPressed();
    if (pressBool)
    {
         if (index < stickArray.length)
              stickArray[index].setVisible(true); // Too lazy to write positionning too but you get the point
         index++;
    }
    pressBool = false;
}

```

I am putting `pressBool` at false in the end to force a key press again but that may not be working depending on the way you get the input.

---
Tags: java
---


# Question
Title: Is replacing a struct field in a class generating garbage using C#?
I am somewhat aware of the differences between classes and structs, when each is allocated on the heap vs the stack, what happens when calling methods etc.

As far as I know, the memory for a struct field in a class is located on the heap, since it is part of the class. What happens when the struct is replaced with a new instance though? Is the content in the area on the heap that the old instance pointed to simply replaced with the content of the new instance? Or is the memory of the old instance targetted for garbage collection and the new instance getting some fresh memory?

```
struct Vector2 { ... }
class Player
{
     public Vector2 Position;
     ...
}

void Main // Whatever
{
    var player = new Player();
    player.Position = new Vector2(); // <--- Will this cause garbage collection?
}

```

# Answer
> 2 votes
No, inspecting disassembly, correct me if I am wrong, appears to construct it in-place(compiled by VS2015 compiler) - `lea` loading the address of the struct and `movq` the value there

```
            var vec = new Vector2();//for comparison
lea         edi,[ebp-4Ch]  //address of
xorps       xmm0,xmm0  //zeroing
movq        mmword ptr [edi],xmm0  //moving result to edi address
            player.Position = new Vector2();
mov         eax,dword ptr [ebp-44h]
cmp         al,byte ptr [eax+4]
lea         edi,[eax+4]  //address of
xorps       xmm0,xmm0  //zeroing
movq        mmword ptr [edi],xmm0  //moving result to edi address

```

# Answer
> 4 votes
## Simple Answer

This isn't properly precise, but it's "good enough" for most day-to-day work:

**Value types like structs do not *themselves* create garbage collection overhead.**

If you already have some memory set aside for a struct somewhere, assigning a new value to it doesn't give the compiler or runtime any cause to go reserve memory elsewhere - it already has the space it needs to store the value.

Contrary to a comment above, the `new` keyword applied to value types in C# does not mean there's a heap allocation (ie. potential garbage generation) happening. In this context, `new` just means "invoke the constructor method to decide how to populate this variable." So these two lines are equivalent:

```
int myInt = new int();
int myInt = 0;

```

In both cases, it's the `int myInt` part that said "I want somewhere to store an integer," and the two different conclusions just sort out what value to stick in there. (They'd likely both compile to the constant 0 anyway).

## More Complicated Answer

This section is based on a pair of in-depth discussions by Eric Lippert.

Despite how often it's claimed "structs are allocated on the stack" (even in Microsoft's own documentation), "stack" is an implementation detail of C# on desktop - there's nothing in the language spec that says every implementation must allocate `structs` on the stack. And in fact there are cases where structs get allocated on the heap:

* If the `struct` is a member of a `class`, then it will be stored in the class. This doesn't create additional GC allocations beyond the one for the class instance itself.
* If the struct gets "boxed" (eg. if you use Unity's `SendMessage(string methodName, object value)` method to send it as payload, that `object value` instance is a reference type and gets allocated on the heap). Here it's the boxing that's creating garbage collection entries.
* If the `struct` is captured in a lambda or anonymous method, or part of an iterator block (you can think of this like the first point - we're creating an instance of an object that can have a lifetime independent of the current scope, so we set aside some memory for it, eg. the iterator object, and the struct it needs gets pulled along for the ride, but isn't itself creating another garbage collection entry beyond the one for the iterator instance)

So what's the real difference with value types like structs? Copy versus reference semantics.

```
myType foo = newFoo();
foo.baz = 0;

myType bar = foo;
bar.baz = 1;

```

Did this code create one new `myType` instance, so references `foo` and `bar` both point at this instance (ie. now `foo.baz == 1`)? It did if `myType` is a reference type. That means the `myType` instance needs to exist in memory at least as long as the lifetime of every reference to it, which is where garbage collection comes in, to handle these types of "long-lived" storage needs.

Or, did this code create two new `myType` instances, and *copy* the value of `foo` into `bar` (ie. it retains `foo.baz == 0`). It did if `myType` is a value type. That means that as soon as `foo` or `bar` go out of scope, we can safely let the data they were referencing expire, since there aren't any other references to it. (Even any methods using the data with a `ref` modifier would have themselves exited first - the semantics won't let us give the data to something with an independent lifetime like a Coroutine or Thread without copying it to them) The compiler & runtime can reliably treat these values as "short-lived" and avoid creating extra garbage tracking overhead for them.

# Answer
> 3 votes
No, that line will not have any impact on the garbage collector. You are right in that the struct lives within the block of heap memory allocated for the class; the garbage collector only cares about tracking the class.

The "new" keyword here is a red-herring; using new on a struct never does a heap allocation or impacts the garbage collector in any way (unless of course the constructor of the struct news up some reference types (classes) of its own).

---
Tags: c#, memory, struct
---


title: Unity - Lots of 3d models

text:
# Question
Title: Unity - Lots of 3d models
I have about 60 3D models with each model being about 4mb in size.If i import them all to unity, my app will be about 240mb in size!.My app requires internet access so should i just upload my models to a server or something?

# Answer
Downloading your models at runtime doesn't solve the problem. Instead of doing a huge download when installing the game they now need to do a huge download when they start the game. Even worse is that they will have to download it from your servers instead of Google's content delivery network. This will be more expensive for you and likely less fast for your users.

You are also deceiving users about the real download size of your game, which people will take into account when giving their reviews of your game.

So instead of wondering how to get all that data onto the user's device, you should rather wonder if your game really *needs* to be 240 MB.

When you have 4 MB models in an android game, then those models might be overly detailed for the small screen size and limited hardware. A 4MB model would either have over 100.000 polygons or several MB of textures.

So you might want to look into reducing the number of vertices, into using lower resolution textures or into making more reuse of textures.
> 3 votes

---
Tags: unity
---


# Question
Title: Error: Framework 'Mono / .NET 3.5' not installed
Recently I installed Ubuntu-Mate 16.10. Unity and Monodevelop works, but when I try to compile the javascript on Monodevelop, appears an error:

Error: Framework 'Mono / .NET 3.5' not installed. (Assembly-CSharp)

On 14.04 all works very well but not here....what is the way to fix this problem??

I searched on the internet and I can't find the answer.

# Answer
**Change your target Framework in MonoDevelop**

* In the solution explorer, go to **Assembly-CSharp** and click on the little cogwheel.
* In the Dropdown, select **Options**
* Then, under **Build / General** select whatever is installed on you machine.

---

Alternatively, if you want to stick with 3.5, you can install the Mono reference assemblies like this:

`sudo apt install mono-reference-assemblies-3.5`
> 2 votes

---
Tags: unity
---


title: Destroy object copies?

text:
# Question
Title: Destroy object copies?
I want to know how to destroy object copies.

```
    public GameObject sparks;

void Update() {

}

void OnTriggerEnter(Collider bulletv) {

    if (bulletv.gameObject.CompareTag("enemy"))
    {
        Destroy(this.gameObject);
        Instantiate(sparks,transform.position,transform.rotation);
        // destroy sparks copies after 2 seconds !!!
    }
}

```

# Answer
> 4 votes
Save a reference to the object you instantiate, like this:

```
GameObject a = Instantiate(sparks,transform.position,transform.rotation);
Destroy(a, 2f);

```

# Answer
> 1 votes
One of the simpler ways to destroy a gameobject after it has been instantiated is to use the `Invoke` method, in a similar way demonstrated in the documentation:

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

public class ExampleScript : MonoBehaviour {

    void Start() {
        Invoke("SelfDelete", 2);
    }

    void SelfDelete() {
        Destroy(gameObject);
    }
}

```

---
Tags: unity
---


# Question
Title: Deferred Shading and Transparency Clarification?
So, this is a bit of a simple question, but I can't seem to find a real answer anywhere. I've been looking into implementing deferred rendering using MRT into my in-progress render engine, but I'm a bit hesitant to for the following reason.

I've read in a few places now that deferred shading does not support transparency natively, and if I wanted to achieve transparency, I would need to resort to forward shading of these transparent objects. But, the idea of "transparency" seems a bit vague because it seems as if there might (corrct me if I'm wrong) be two types of transparency.

One type being the sort of overlay transparency, where I, say, tile a wall with a brick texture. Then I want the wall to be 50% transparent so I apply that on top of the already textured object. This appears to be one "mode" transparency in which the engine, as part of its rendering pipeline, inserts this transparency manually.

The next type in my mind is using a texture that already has an alpha value associated with it, i.e. a 256x256 image of a person, where everything that isn't the person has an alpha value of zero. Then, if I were to billboard that image of the man onto a simple quad (which is what I'm actually trying to do in my game, for reference), would that sort of "native" transparency on the parts of the image with zero alpha still render as transparent, even in a deferred rendering situation?

Does such a distinction exist between these two types of transparency, or are they merely two sides of the same coin when it comes to deferred rendering?

# Answer
> 3 votes
They're both the same thing, in that they both require anything visible *through* the transparent portions of the surface to have been rendered already, so they can be available in the framebuffer for blending with the transparent surface as it is rendered.

Traditional deferred rendering effectively only stores the "front-most" pixels, the ones for the transparent surface in this case. But since the data for what was behind those transparent pixels is lost, the transparency cannot be resolved with traditional deferred rendering.

So it doesn't matter that you use alpha data in textures to compute transparency, or if you flat-out decide "this entire model will be 50% transparent." Neither works with traditional deferred rendering.

---
Tags: rendering, transparency, deferred-rendering
---


# Question
Title: How do i get the drawing to loop automatically with out need for user input scrolling?
```
#include <iostream>
#include <time.h>
#include <iomanip>
#include <SDL.h>
#include <stdlib.h>
#include <string.h>
#include "screen.h"
#include "Stars.h"
#include "Allstars.h"

int main(int argc, char* argv[]) {

    //seeding random number generator

    srand(time(NULL));

    //------------------------------------------------------------------------------
    /***CREATING SDL WINDOW***/
    /***CREATING RENDERER & TEXTURE***/
    /***CREATING A BUFFER***/

    Screen screen1;
    screen1.init();

    //-----------------------------------------------------------------------------
    /***GAME LOOP***/

    /*UPDATING buffer with texture information*/

    Allstars allstars1;

    while (true) {
        int num=0;
        screen1.screenClear();
        allstars1.updateStarPosition();

        // Allstars class to retrieve  m_pstars from the Allstars class into the main function.

        const Stars * const pStars = allstars1.getStars();

        for (int i = 0; i < allstars1.NSTARS; i++) {
            Stars star = pStars[i];

            // here is where i tried to loop each star back to the bottom of the screen  when they reached the top of the screen.

            if(num>3 && star.m_y_star<-0.97 && star.m_y_star>-1){

                    star.m_y_star=0.99;
                    star.m_x_star= star.m_x_star;

                }

//each star is given a random location by giving co-ordinates: m_x_star & m_y_star a random value using a function in Stars.h
// You can't get negative co-ordinates on the screen so we map from [-1,1] to [0 to SCREEN_WIDTH and 0 to SCREEN_HEIGHT]

            int x = (star.m_x_star + 1) * ((Screen::SCREEN_WIDTH) / 2);
            int y = (star.m_y_star + 1) * ((Screen::SCREEN_HEIGHT) / 2);
            screen1.setPixel(x, y, 128, 0, 255);
        }

        /*UPDATED USED TO UPDATE TEXTURE and RENDERER and PRESENT DRAWING ON SCREEN*/
        screen1.update();

        /* Check for messages and events
         */

        //Quitting SDL through clicking 'x' button event
        if (screen1.processEvents() == false) {
            break;

        }
        num++;
    }
    //-----------------------------------------------------------------------------
    /***FREEING MEMORY & QUITTING SDL***/
    screen1.close();
    return 0;
}
//------------------------------END OF MAIN----------------------------------------

```

I tried to get use a for loop to change the vertical position of the star once it draws close to the top of the window but that doesn't seem to influence the program. Stars (purple dots) seem to drift off the screen and don't appear from the bottom of the screen again. No errors occur and i have incorporated checks to prevent the stars being plotted off of the screen. Can someone help me make these purple dots loop infinitely without the need for scrolling.

# Answer
I assume two things:

1. The constructor of `Allstars allstars1;` initializes the random positions of all the `Stars` contained therein.
2. `allstars1.updateStarPosition();` translates the current set of stars vertically in the range `[-1, 1]` by some very small amount, say 0.001, as you say.

From there, as I understand it, you want to loop through all your stars snapping the y-position of any in the range `(-0.97, -1)` to `0.99` *while maintaining their x-position*.

---

First, move the declaration and initialization of `int num = 0` out of the `while(true)` loop because setting it to 0 each loop means:

```
if(num>3 && star.m_y_star<-0.97 && star.m_y_star>-1)

```

is *always false*. However, if you still want to use it then reset `num = 0;` inside that `num>3` y-position range check. Although I do see in your comments that you've since changed the condition for the better.

---

The constant pointer to constant data means that *nothing* `pStars` points to can be changed.

```
const Stars * const pStars = allstars1.getStars();

```

Moreover,

```
Stars star = pStars[i];

```

makes a **copy** of your `allstars1` element, which means anything you do to it will not affect anything in `allstars1`

Both these statements together mean any y-position snapping you do in the `for` loop only affects the **copies** of `allstars1` elements, and therefore the results only last one frame. This is why you only see a line of stars along the bottom of the screen instead of scrolling stars.

---

The quick and dirty solution is simply to remove the constant-data qualifier, that is change:

```
const Stars * const pStars = allstars1.getStars();

```

to this:

```
Stars * const pStars = allstars1.getStars();

```

Then instead of instantiating a copy for each pStar\[i\] element, just use it directly:

```
if(num>3 && pStar[i].m_y_star<-0.97 && pStar[i].m_y_star>-1){
    pStar[i].m_y_star=0.99;
//  pStar[i].m_x_star= pStar[i].m_x_star;    // unnecessary self-assignment
}

```

The self-assignment line is unnecessary; the x-coordinate is constant whether or not you self-assign it.

The same applies here too:

```
int x = (pStar[i].m_x_star + 1) * ((Screen::SCREEN_WIDTH) / 2);
int y = (pStar[i].m_y_star + 1) * ((Screen::SCREEN_HEIGHT) / 2);

```

---

Given that you are using a constant raw pointer to non-constant data you might as well move your `pStars` pointer outside your `while(true)` loop. That will save you an assignment each frame.

---

As a general note look into SDL\_GetTicks() instead of `<time.h>`. Also look into c++ passing by reference, and operator\[\] overloading, they'll save you a lot of pointer debugging headaches in the future.
> 0 votes

---
Tags: game-design, sdl, game-loop, sdl2
---


# Question
Title: naming conventions in game code / vocabulary
I'm just starting out as a game developer, and I'm finding some difficulty when naming classes.

I usually call the class that handles everything `World`, `Map`, or `Grid`. Then there's the names, inside.

---

For example, I'm making a Frogger clone, and I have a class for everything that moves on screen (I try to use MVC and I'm talking about the model here - I have `Sprite` classes in the view), and I named it `Object` for lack of a better name. Then there's a subclass from `Object` which I named `Frog` (though I could name it `Player`) and another one for the things controlled by the computer, which I don't know what to call (it could be `Enemy` or `Obstacle` or something appropriate for cars and trucks). This class also includes the turtles, which are more like helpful objects, yet are not powerups.

---

How should I manage my naming conventions?

# Answer
If you're having trouble naming things it's probably because your class design itself is messy. Just hearing you talk about your code it seems like you're overusing inheritance.

Also, there are a ton of questions on here about MVC and generally speaking it isn't a good pattern to try to force into things. Gaming is more like Model view viewmodel than mvc anyway.

I don't think there's a specific reference for what you're looking for. Also, in general SE sites are better if you ask specifically what you're looking for instead of a reference for what you're looking for. For example, draw out your specific class hierarchy and ask what might be the best way to name your obstacles-that-also-can-be-useful, or whatever.
> 4 votes

# Answer
Tetrad is correct that your ideas seem a bit messy at the moment. But to answer the question more directly (small picture rather than big picture) for those who come hereafter:

Typically you want a few classes with a lot of properties, rather than subclasses. Here's a wikipedia reference someone gave me when I asked this exact same question like 4 days ago in a chatroom. (Thanks Alex, for helping me find it again).

For example (of what not to do): Among the entities we've got `Frog`, `Truck`, `Land`, `Water`. Land and Water are stationary, or static. Frog and Truck are moving, or dynamic. So we could make `Static` and `Dynamic` subclasses and put each one into those classes. On the other hand, both a Truck and the Water will kill you. Maybe Water is Dynamic, instead? Water and Truck are both in the `Enemy` class? Well... no.

It's better to use properties on the various entities. `Frog` and `Truck` have the `canMove` property. `Truck` and `Water` have the `killOnContact` property.

**To Clarify and make Direct** You'll find that it's easier to come up with names for the behaviors and features and what not, than it is to come up with a single category in which something should go. (The same reason each SE site has tags rather than categories).
> 0 votes

---
Tags: software-engineering
---


# Question
Title: Size of .skp gets doubled after importing to Unity
I have created a 3D model in SketchUp, and it is about 1.6Mb in size. After importing it to Unity, the size more than doubled to 4Mb.

Why is that?

# Answer
> 1 votes
Unity is converting the file from .skp to its own internal binary format, which is less compressed because it is ready for runtime usage.

---
Tags: unity, 3d-modeling
---


# Question
Title: GLSL - Stretched vertices after translating
I'm trying to translate 3D object in my game engine. I copied all formulas from my old, working game engine, where translation was working.

When I set position and rotation to 0, everything looks to be fine, but when I try to change position of my 3D object, something strange happens. I'm not sure if it is projection matrix issue, or maybe transform matrix issue.

```
Position: x = 0, y = 0, z = 0
Rotation: x = 0, y = 0, z = 0

```

```
Position: x = 0, y = 0, z = 0
Rotation: x = 0, y = 45.0, z = 0

```

```
Position: x = 1.5, y = 0, z = 0
Rotation: x = 0, y = 0, z = 0

```

```
Position: x = 3.5, y = 0, z = 0
Rotation: x = 0, y = 0, z = 0

```

I checked all formulas once again, checked transformation matrix output, projection matrix output, and everything seems to be fine.

Here is my vertex shader:

```
#version 400

in vec3 position;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void)
{
  gl_Position = projectionMatrix * viewMatrix * transformationMatrix * vec4(position,1.0);
}

```

and fragment shader:

```
#version 400

uniform vec2 textureVec;

layout(location = 0) out vec3 out_Diffuse;
layout(location = 1) out vec3 out_Texture;

void main(void)
{
  out_Diffuse = vec3(0.5, 0.5, 0.5);
  out_Texture = vec3(textureVec, 0.0);
}

```

Projection matrix formula:

```
  float aspectRatio = static_cast<float>(windowSize.x) / static_cast<float>(windowSize.y);
  float yScale = static_cast<float>((1.0f / tanf(MathUtil::degToRad(fov / 2.0f))));
  float xScale = yScale / aspectRatio;
  float frustumLen = farPlane - nearPlane;

  projectionMatrix.m00 = xScale;
  projectionMatrix.m11 = yScale;
  projectionMatrix.m22 = -((farPlane + nearPlane) / frustumLen);
  projectionMatrix.m23 = -1.0f;
  projectionMatrix.m32 = -((2.0f * nearPlane * farPlane) / frustumLen);
  projectionMatrix.m33 = 0.0f;

```

View matrix formula:

```
  viewMatrix.setIdentity();
  viewMatrix.rotate(Vector3(1.0f, 0.0f, 0.0f), MathUtil::degToRad(transformComponent->rotation.x));
  viewMatrix.rotate(Vector3(0.0f, 1.0f, 0.0f), MathUtil::degToRad(transformComponent->rotation.y));
  viewMatrix.scale(Vector3(1.0f, -1.0f, 1.0f));

  Vector3 negativeCam = Vector3::negate(transformComponent->position);

  viewMatrix.translate(negativeCam);

```

And transformation matrix formula:

```
  transformationMatrix.setIdentity();

  transformationMatrix.translate(position);
  transformationMatrix.rotate(Vector3(1.0f, 0.0f, 0.0f), MathUtil::degToRad(rotation.x));
  transformationMatrix.rotate(Vector3(0.0f, 1.0f, 0.0f), MathUtil::degToRad(rotation.y));
  transformationMatrix.rotate(Vector3(0.0f, 0.0f, 1.0f), MathUtil::degToRad(rotation.z));
  transformationMatrix.scale(scale);

```

Same happens for "y" and "z" position axis, but object "rotates" in different axis.

I also checked my VAO loader, vertices, uniform values loader, and everything else. If you need more code, let me know.

# Answer
> 0 votes
What you see is perspective distortion caused by wide Field Of View. With perspective camera, objects near the view edges get "stretched", compared with objects in view center. The more the FOV, the larger they "stretch".

You might want to reduce the FOV, or even try to switch to Orthographic camera, if you want objects to "stretch" less or keep their size/proportions constant.

---
Tags: glsl
---


title: Draw UI from two VR cameras

text:
# Question
Title: Draw UI from two VR cameras
I have a third party package that is for mobile VR. it consist of two cameras that giving me the feel of VR Look. I have designe a user interface which i want to show from my both VR cameras but the problem both camera showing single UI. My UI not duplicating for each camera instead its only showing single UI as image depicted. How can i duplicate My UI so that it show from both VR cams

# Answer
> 0 votes
I am able to get my answer from **here**, slightly outdated but valid post for unity 5.2 also:

1. Create two different canvases in your scene.
2. Select the Render Mode for each canvas as Screen Space - Camera.
3. Then assign the camera for each of those canvases as required.
4. Then that particular canvas will be drawn using the camera assigned to it.

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


# Question
Title: Unity TopDown parallax effect only working in three of four directions
I'm a hobbyist at programming so I'm sure I'm missing something very simple:

Basically I have a script that has a method for repositioning a 3x3 grid of tiles every time the player goes out of the center tile. They are ordered in a List 0-8 left to right, top to bottom. The strange thing is it works perfectly for tile indexes 0,1,2,3 and 5, but the bottom row doesn't re-orient the tiles correctly even though it's using the same method that works for all the other tiles.

No errors thrown in the log.

Here is the method I created and the switch statement that calls the method. TilesArr is instantiated in the Start() function and is declared in the script class itself.

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

public class ParallaxBG : MonoBehaviour {
public GameObject tile;
public GameObject containter;
public GameObject player;
public int SlowDownFactor = 300;
public float tileWidth = 5f;

private List<GameObject> TilesArr = new List<GameObject>{ };

//this is a method for shifting the tiles in any direction.
public List<GameObject> arrangeTiles(List<GameObject> arrayToModify, int startingTile, bool columnMod, int iterationQty, int xMod, int yMod, int newArrayStartingIndex){
    List<GameObject> arrayClone = new List<GameObject>(arrayToModify);
    if (columnMod) {
        for (int i = startingTile; i < startingTile+(iterationQty*3); i+=3) {
            arrayClone[i].transform.position = arrayClone[i].transform.position + new Vector3 (xMod*tileWidth,yMod*tileWidth,0);
            GameObject thisTile = arrayClone [i];
            //int rotation = Random.Range (0, 3);
            //thisTile.transform.Rotate(0,0,90*rotation);
            arrayClone.RemoveAt (i);
            arrayClone.Insert ((i - startingTile) + newArrayStartingIndex,thisTile);
        }
        return arrayClone;
    } else {
        for (int i = startingTile; i < (startingTile + iterationQty); i++) {
            arrayClone [i].transform.position = arrayClone [i].transform.position + new Vector3 (xMod * tileWidth, yMod * tileWidth, 0);
            GameObject thisTile = arrayClone [i];
            //int rotation = Random.Range (0, 3);
            //thisTile.transform.Rotate(0,0,90*rotation);
            arrayClone.RemoveAt (i);
            arrayClone.Insert ((i - startingTile) + newArrayStartingIndex, thisTile);

        }
        return arrayClone;
    }
}

// Use this for initialization
void Start () {
    float pX = player.transform.position.x;
    float pY = player.transform.position.y;
    for (int i = 0; i < 9; i++) {
        GameObject Tile = Instantiate (tile);
        Tile.name = "t" + i;
        Tile.transform.SetParent (containter.transform,false);
        Tile.transform.localScale = new Vector2(tileWidth,tileWidth);
        int rotation = Random.Range (0, 3);
        Tile.transform.Rotate (0, 0, rotation * 90);

        if (i <= 2) {
            Tile.transform.position = new Vector2 ((pX - 1 + i)*tileWidth, pY + tileWidth);

        } else if (i >= 3 && i <= 5) {
            Tile.transform.position = new Vector2 ((pX - 4 + i)*tileWidth, pY);

        } else {
            Tile.transform.position = new Vector2 ((pX - 7 + i)*tileWidth, pY - tileWidth);

        }
        TilesArr.Add (Tile);

    }
}

// Update is called once per frame
private int counter = 0;
void Update () {
    if (counter == 0) {
        Vector2 playerVelocity = player.GetComponent<Rigidbody2D> ().velocity/SlowDownFactor;
        Vector2 pTrans = (Vector2)player.transform.position;

        //we just grab player velocity and slowed it down.
        //tile index starts at 0 on each Update() call
        int tileIndex = 0;
        foreach (var Tile in TilesArr) {

            //loop starts with complete=false
            bool complete = false;

            Tile.transform.position = new Vector2 (Tile.transform.position.x - playerVelocity.x, Tile.transform.position.y - playerVelocity.y);
            Vector2 tTrans = Tile.transform.position;

            if (tileIndex != 4 && (Mathf.Abs (pTrans.x - tTrans.x) < (tileWidth / 2)) && (Mathf.Abs(pTrans.y - tTrans.y) < (tileWidth / 2))) {
                List<GameObject> moveOne;

                switch (tileIndex) {
                case 0:
                    moveOne = arrangeTiles (TilesArr, 6, false, 3, -1, 3, 0);
                    TilesArr = new List<GameObject>(arrangeTiles (moveOne, 5, true, 2, -3, 0, 3));
                    for (int i = 0; i < 9; i++) {
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);

                    }
                    complete = true;
                    break;
                case 1:
                    TilesArr = new List<GameObject>(arrangeTiles (TilesArr, 6, false, 3, 0, 3, 0));
                    for (int i = 0; i < 9; i++) {
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);
                    }
                    complete = true;
                    break;
                case 2:
                    moveOne = arrangeTiles (TilesArr, 6, false, 3, 1, 3, 0);
                    TilesArr = new List<GameObject>(arrangeTiles (moveOne, 3, true, 2, 3, 0, 5));
                    for (int i = 0; i < 9; i++) {
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);

                    }
                    complete = true;
                    break;
                case 3:
                    TilesArr = new List<GameObject>(arrangeTiles (TilesArr, 2, true, 3, -3, 0, 0));
                    for (int i = 0; i < 9; i++) {
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);
                    }
                    complete = true;
                    break;
                //there is no case 4 because that is center tile.
                case 5:
                    TilesArr = new List<GameObject>(arrangeTiles (TilesArr, 0, true, 3, 3, 0, 2));
                    for (int i = 0; i < 9; i++) {
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);
                    }
                    complete = true;
                    break;
                    //WHY IS THE BOTTOM ROW NOT WORKING??
                case 6:
                    moveOne = arrangeTiles (TilesArr, 0, false, 3, -1, -3, 6);
                    TilesArr = new List<GameObject>(arrangeTiles (moveOne, 2, true, 2, -3, 0, 0));
                    for (int i = 0; i < 9; i++) {
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);

                    }
                    complete = true;
                    break;
                case 7:
                    TilesArr = new List<GameObject>(arrangeTiles (TilesArr, 3, false, 3, 0, -3, 6));

                    for (int i = 0; i < 9; i++) {
                        Debug.Log (TilesArr [i].name);
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);
                    }
                    complete = true;
                    break;
                case 8:
                    moveOne = arrangeTiles (TilesArr, 0, false, 3, 1, -3, 6);
                    TilesArr = new List<GameObject>(arrangeTiles (moveOne, 0, true, 2, 3, 0, 2));
                    for (int i = 0; i < 9; i++) {
                        TilesArr[i].transform.position = new Vector2 (TilesArr[i].transform.position.x,TilesArr[i].transform.position.y);

                    }
                    complete = true;
                    break;
                default:
                    Debug.Log ("were in the middle");
                    break;

                }

            }
            tileIndex += 1;
            if(complete){
                break;

            }
        }
        //counter = 0;
    }
    //counter = 1;

}

```

}

# Answer
I've found the solution, it had to do with way my List.RemoveAt() command was affecting the order of the array when the starting index was less than the index i wanted to move the items to.

The revised method below works:

```
public List<GameObject> arrangeTiles(List<GameObject> arrayToModify, int startingTile, bool columnMod, int iterationQty, int xMod, int yMod, int newArrayStartingIndex){
        List<GameObject> arrayClone = new List<GameObject>(arrayToModify);
        //COLUMN
        if (columnMod) {
            for (int i = startingTile; i < startingTile+(iterationQty*3); i+=3) {
                //modifying columns does not need an IF statement with respect to the starting index and the insert index because I can only move the column 2 spaces away max,
                //but the script iterates by 3 units so the each next iteration retains the correct element in the 2nd and 3rd position upon completion of the loop.  VERY CONFUSING BUT IT WORKS!

                arrayClone [i].transform.position = arrayClone [i].transform.position + new Vector3 (xMod * tileWidth, yMod * tileWidth, 0);
                GameObject thisTile = arrayClone [i];
                arrayClone.RemoveAt (i);
                arrayClone.Insert ((i - startingTile) + newArrayStartingIndex, thisTile);
            }
            return arrayClone;
        //ROW
        } else {
            for (int i = startingTile; i < (startingTile + iterationQty); i++) {
                if (startingTile > newArrayStartingIndex) {
                    arrayClone [i].transform.position = arrayClone [i].transform.position + new Vector3 (xMod * tileWidth, yMod * tileWidth, 0);
                    GameObject thisTile = arrayClone [i];
                    arrayClone.RemoveAt (i);
                    arrayClone.Insert ((i - startingTile) + newArrayStartingIndex, thisTile);
                } else {
                    arrayClone [startingTile].transform.position = arrayClone [startingTile].transform.position + new Vector3 (xMod * tileWidth, yMod * tileWidth, 0);
                    GameObject thisTile = arrayClone [startingTile];
                    arrayClone.RemoveAt (startingTile);
                    arrayClone.Add (thisTile);
                }

            }
            return arrayClone;
        }
    }

```
> 1 votes

---
Tags: unity, c#, tilemap, debugging, parallax-scrolling
---


# Question
Title: How to combine Actor.setPosition and Actor.hit?
Why after using Actor.setPosition, input coordinates in Actor.hit come with a shift in the values specified in setPosition?

Create scene:

```
public class MyActor extends Actor {
...
    int width = 70;
    int height = 70;

    public MyActor(Texture img, int x, int y, int realX, int realY) {
...
        sprite = new Sprite(img, x, y, width, height);
        this.setPosition(realX, realY);

```

Standard search Actor:

```
public class GameScreen implements Screen, InputProcessor {

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        Vector2 coord = stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY));
        Gdx.app.log("touchDown", "" + coord.x +","+ coord.y);

        selectedActor = (MyActor)stage.hit(coord.x,coord.y,false);

```

...

```
public class MyActor extends Actor {

    @Override
    public Actor hit(float x, float y, boolean touchable) {
        if(!touchable)
            Gdx.app.log("Actor.hit:", "" + x +":"+ y);
        return x < getX()|| x >= getX() + width || y < getY()||  y >= getY() + height ? null : this;

```

But come the distorted values.

Coordinates Click: touchDown: 26.25,81.250015.

MyActor in the values obtained from the offset, the multiple of 70:

* Actor.hit: -43.75:11.250015
* Actor.hit: -43.75:81.250015
* Actor.hit: 26.25:11.250015
* Actor.hit: 26.25:81.250015

Why? How to fix?

`UPDATE`

```
public class MyStage extends Stage {
...
    @Override
    public Actor hit(float x, float y, boolean touchable) {

        return super.hit(x,y,touchable);

```

# Answer
I have been facing the same problem.After a couple of trial and errors, I have solved the problem in my game. Ever since, using **actor.setPosition(x,y)**, all my clicks obtained from the functions **Gdx.input.getX()** and **getY()** (left clicks in my case), was shifting the origin to x,y. It was as if **setPosition()** was acting as some sort of **setOrigin()** function. These were the changes I had made, since the problem. One or more of these changes could solve your problem:

* Setting the input processor as (this), instead of the stage.
* Using your **coord** variable as Vector3 and passing it through **camera.unproject(coord)**, to obtain values in world co-ordinates. This makes the clicks independent of any localized reference frame.
* Removing **stage.screenToStageCoordinate**s function, as a natural consequence of converting **coord** to Vector3. Moreover, point no 2 deals with the conversion factor.
> 1 votes

---
Tags: libgdx
---


# Question
Title: What is the revenue split between me and Google in the Play store?
I want to sell an app on the Google Chrome store for $0.50. How much of this will I pocket after Google's cut?

# Answer
what i got from here https://support.google.com/googleplay/android-developer/answer/112622?hl=en , 0.50 * 70% = 0.35 $ or 35 cents
> 3 votes

---
Tags: google-play
---


# Question
Title: UNITY Prevent 3D Text Render Trough All Object Without Shader
im tired of those answer i found trough search engine that just keep saying " the trick is to modify the shader " without thinking because they want to gain reputation , in my case , i have **2 3D text** , one of them using **special font** and the other one using **default font** , and **the shader to prevent the text render trough all object from http://wiki.unity3d.com/index.php?title=3DText is not working** and giving ***weird white square*** plus ***i don't want to change from default Arial font because i want to make them look different*** , i also **cannot use sprite** as background because i need to change their color trough script to give some effect , this is my picture showing my problem -- :

If the picture is not clear , go here https://i.stack.imgur.com/hLqC9.png

The menu dropped is at Z = 100 while the background is at Z = 20 , as you see , the text is rendered while the other not ( such as the border , ect ).

And this is the picture when my special font without using the shader

If the picture is not clear , go here https://i.stack.imgur.com/vbrQ1.png

Now the picture of my special font using the shader

If the picture is not clear , go here https://i.stack.imgur.com/hMAR2.png

Is there any possible way to prevent the text rendered without shader / change the background to sprite ?

Im sorry if this already asked somewhere , i just cannot find it at search engine ( neither here ) .

# Answer
Finally ! i found out the answer myself , the way to do it is by creating material , make the material type ( or shader ) into sprite / default ! using that way i stil can change the color of the background .

Before :

After adding material :

Proof i still can change the color of the object that have the material in it :
> 0 votes

---
Tags: unity, 2d, 3d, graphics, text
---


# Question
Title: How to compensate for moving objects with client side prediction?
I'm implementing a game server that supports Star Control-like melee. So you have ships flying and shooting, with super simple velocity/acceleration/dampening physics to drive movement.

I've read Valve, Gafferon and Gambetta and implemented Gambetta's algorithm for client prediction:

Client prediction works on the player ship by updating its position from the server as it comes and then reapplying the yet-unprocessed-by-the-server input to the player ship.

Unfortunately, it doesn't work well for my game. I believe it has to do with the fact that Gambetta's example doesn't take into account objects that are already moving, or commands that are updated on a step by step basis. (by "step" I mean frame). So in my game the player presses up to accelerate the (already moving) ship, which continues moving on the client, sends the command to the server and usually receives the world snapshot from the server on the next step. I get something more like:

The player command runs at client **step 3**, but on the server its only run at server **step 5**. By the time the world snapshot is received by the client at client **step 6**, the prediction is way off, especially in faster velocities.

The crux of the problem is that the client runs the command at **step 5**, but the server runs it at **step 6**. I thought about maybe sending the client step with the command, and have the server roll back and re-run the command with the client time step. That might lead to a slew of other problems though - like what happens to commands received since the rollback, or how cheating clients can exploit by changing the sent step.

Reading and watching videos like this one from Google mentions a different approach, where you gradually change player position to match that of of the snapshot over a few steps.

**My questions:**

* Can you make Gambetta's algorithm work with constant step movement? Or is it conceptually incompatible with my game?
* Is gradual interpolation over steps the correct way to go then? If so, how do you interpolate an already moving object from the client position to match that which was just received from the server?
* Can these methods, gradual interpolation and Gambetta's algorithm work in tandem, or are they mutually exclusive?

# Answer
> 9 votes
During the 6 months since I asked this question, I ended up developing a complete open source game server to deal with this exact issue (and many others!): https://lance-gg.github.io/

The R&D involved now allows me to answer my own questions:

* *Can you make Gambetta's algorithm work with constant step movement? Or is it conceptually incompatible with my game?*

**Gambetta's algorithm will not work when the movement of the entity is not deterministic (from the client's POV). If an entity can be affected without input by physics or other players, for example a more elabroate approach needs to be taken.**

* *Is gradual interpolation over steps the correct way to go then? If so, how do you interpolate an already moving object from the client position to match that which was just received from the server?*

**This touches on a different topic, which is client reconciliation of server updates. Gradual interpolation works, but for very fast paced games like the one in the question it is better to actually implement extrapolation**

* *Can these methods, gradual interpolation and Gambetta's algorithm work in tandem, or are they mutually exclusive?*

**They can work together, but only if the entity movement is deterministic from the client POV. So it won't work if the the entity is affected by physics or psuedo-physics like inertion, drag etc'**

# Answer
> 1 votes
Your game seems to be too "real-time" to think in terms of time steps. I'd only think in terms of "turns" if the game can be considered "turn-based". Otherwise, just abandon the idea of turns or steps. Everything becomes easier then :)

Note that you predict locally for your player, and interpolate only for other entities (as explained in the 3rd article in the series). The way to deal with server updates for objects that were already moving is server-side reconciliation, explained in the bottom half of the 2nd article (the one you linked towards).

Hope this helps :)

---
Tags: movement, networking, multiplayer, movement-prediction
---