# Question
Title: RPG Maker MV stop refreshing items in shop
Well, the thing is that i've been using Attachable Augments (a GREAT plugin made by Yanfly, check yanfly.moe for more info) for a while, but I feel that something was not there. You can buy items and buy things, but why not buying items with already attached parts?

So i've tried to make a plugin. This works with the idea to only make one weapon of one type (for example 'sword') and then use different materials to change the stat buffs/debuffs (for example, making the 'steel' material in order to make the sword).

As far as i've gone, i managed to select random attatchments for one object and attached them to this item, and it shows correctly in the shop. The problem is that every time I exit the 'buy' menu or the shop an enter again, the 'new' object is just the older but with new attachments and added buffs, so i have one weapon with the older stats and the newer stats.

What can I do in order to make this work?

This is the pluggin code:

```
if (Imported.YEP_X_AttachAugments) {
    console.log("Iniciado el plugin");                                      ///< Remover en la versión final. Solo es un mensaje de consola inutil
    var MaxAttachableItemCount = 100;                                       ///< This would be the value of all attachable augments for one object. Default (100)
    var GenericAttachableItems;                                             ///< Empty Array that would change with the items of the last category
    var LastCategory = null;                                                ///< It saves the last category searched

    var paramsRA = PluginManager.parameters('YEP_X_Random_Attaches');       ///< Parameters of this plugin
    var paramsAA = PluginManager.parameters('YEP_X_AttachAugments');        ///< Parameters of Yanfly plugin
    var enabled_param = Boolean(paramsRA['Enabled'] || true);               ///< Enabled parameter
    var augmentSlotsParamW = String(paramsAA['Weapon Slots'].split(','));   ///< Weapon Slots
    var augmentSlotsParamA = String(paramsAA['Armor Slots'].split(','));    ///< Armor Slots
    var startingWeapons;
    var firstTimeOpennedShop = true;                                        ///< Says if it's the first time the shop is open or not

    /** function randomAttach(category)
     * This would generate and attach one attachable
     * item to the object 'category'
     * type.
     */
    //Slifer.Random.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded;
    function randomAttachFind(category){
        //this.cout("Stating search of random Attachment");
        var Attach = new Array();
        //if(Slifer.Random.isDatabaseLoaded){
        category = category.toUpperCase();
                this.LastCategory = null;
                this.GenericAttachableItems = new Array();
                this.MaxAttachableItemCount = 0;
                                                        ///< No category
                //cout($dataItems);
                var contador = 0;
                for (var i = 1; i <= $dataItems.length-4; i++) {
                    //cout("Object: " + $dataItems[i]);
                    var eval = $dataItems[i].augmentTypes;
                    cout ("Eval: " + eval[0] + " eval length: " + eval.length);
                    var pushed = false;
                    for (var l = 0; l < eval.length; l++) {
                        if(category ==  eval[l] && pushed == false){
                            pushed = true;
                            var aux = $dataItems[i];
                            //cout("Attached: " + aux);
                            this.GenericAttachableItems.push(aux);
                            //cout("Finded!");
                        }
                    }
                }

                this.MaxAttachableItemCount = GenericAttachableItems.length + 1;                    ///< Get the arrayLenght
                //this.cout("MaxAttachableItemCount: " + this.MaxAttachableItemCount);
                var randomNumber = Math.floor((Math.random() * MaxAttachableItemCount) + 1);        ///< Generate a random number
                randomNumber -= 1;                                                                  ///< This is to match the array index
                //this.cout("randomNumber: " + randomNumber);

                Attach = GenericAttachableItems[randomNumber];                                  ///< Obtaining the Attachment

        //}
        this.LastCategory = category;
        //cout("This is the selected item: ");
        //cout(Attach);
        return Attach;
    }

    function cout(message){
        console.log(message);
    }
    /** function AttachableItemCount(item_name)
     * This would count all attachable items for
     * one object.
     */

    /** function proccessingNoteTags()
     * This proccesses the notetags reffearing the plugin.
     * The useful notetags are said upper.
     */
    function proccessingNoteTags(){

    }

    /** Game_Interpreter.prototype.pluginCommand = function(command, args)
     * This would proccess the plugin commands and call the necesary
     * functions to work.
     */
    var alias_pluginCommand = Game_Interpreter.prototype.pluginCommand;     ///< Aliasing
    Game_Interpreter.prototype.pluginCommand = function(command, args) {
        alias_pluginCommand.apply(this);
        switch (command){
            case "RandomShop":
                this.makeItemList();    ///< Call Shop
                break;
        }
    };

    /**
     * goods[0] -> Item Type
     * goods[1] -> Item ID
     * goods[2] -> Item Price
     * goods[3] -> Item Concrete Price
     *
     * $dataItems[x]   -> Item at x index
     * $dataWeapons[x] -> Weapon at x index
     * $dataArmors[x]  -> Armor at x index
     */

    Window_ShopBuy.prototype.makeItemList = function() {
        this._data = [];
        this._price = [];
        var attach =  new Array();
        var first = false;
        this._shopGoods.forEach(function(goods) {
            var item = null;
            switch (goods[0]) {
            case 0:
                item = $dataItems[goods[1]];
                break;
            case 1:
                item = $dataWeapons[goods[1]];
                if(firstTimeOpennedShop == true){
                    cout(item);
                    if(startingWeapons == null){
                        startingWeapons = new Array();
                        startingWeapons.push(item);
                        first = true;
                    }
                    if(true && startingWeapons != null){
                        startingWeapons.push(item);
                    }
                    ///< Here we have to give random attaches!
                    console.log("Finding item augments");
                    console.log("Item slots lenght" + item.augmentSlots.length)
                    ItemManager.removeAllAugments(item);
                    for(var slotId = 0; slotId < item.augmentSlots.length; slotId++){
                        attach.push(randomAttachFind(item.augmentSlots[slotId]));
                        console.log("Slot id: " + slotId);
                        console.log("Slot name: " + item.augmentSlots[slotId]);
                        console.log(attach[slotId]);
                    }

                }else if (firstTimeOpennedShop != true){

                }
                break;
            case 2:
                item = $dataArmors[goods[1]];
                break;
            }
            if (item) {
                this._data.push(item);
                this._price.push(goods[2] === 0 ? item.price : goods[3]);
                ItemManager.installAugments(item,attach);
                attach = new Array();
            }
        }, this);
        this.firstTimeOpennedShop = false;

    };

```

There's some code that doesn't do anything. Don't care about it, that will be future code. (It's my first plugin and my first time with javascript, so I don\`t know if there's a better way to do it or what i'm doing wrong)

# Answer
> 2 votes
Well, I've solved some of the problems!

Here is the actual code:

```
Window_ShopBuy.prototype.makeItemList = function() {
            if(this.firstTimeOpennedShop == undefined || this.firstTimeOpennedShop == null)
                this.firstTimeOpennedShop = true;
            else
                this.firstTimeOpennedShop = false;
            this._data = [];
            this._price = [];
            var attach =  new Array();
            var itemID = 0;
            this._shopGoods.forEach(function(goods) {
                var item = null;
                switch (goods[0]) {
                case 0:
                    item = $dataItems[goods[1]];
                    break;
                case 1:
                    item = $dataWeapons[goods[1]];
                    cout("DEBUG: "+this.firstTimeOpennedShop);
                    if(this.firstTimeOpennedShop == true){
                        cout(item);
                        if(startingWeapons == null){
                            startingWeapons = new Array();
                            startingWeapons.push(item);
                        }
                        if(this.firstTimeOpennedShop == true && startingWeapons != null){
                            startingWeapons.push(item);
                        } else {
                            item = startingWeapons[itemID];
                            itemID++;
                            firstTimeOpennedShop = false;
                        }
                        ///< Here we have to give random attaches!
                        console.log("Finding item augments");
                        console.log("Item slots lenght" + item.augmentSlots.length)
                        ItemManager.removeAllAugments(item);
                        for(var slotId = 0; slotId < item.augmentSlots.length; slotId++){
                            attach.push(randomAttachFind(item.augmentSlots[slotId]));
                            console.log("Slot id: " + slotId);
                            console.log("Slot name: " + item.augmentSlots[slotId]);
                            console.log(attach[slotId]);
                        }

                    }else if (this.firstTimeOpennedShop != true){

                    }
                    break;
                case 2:
                    item = $dataArmors[goods[1]];
                    break;
                }
                if (item) {
                    this._data.push(item);
                    this._price.push(goods[2] === 0 ? item.price : goods[3]);
                    ItemManager.installAugments(item,attach);
                    attach = new Array();
                }
            }, this);
            this.firstTimeOpennedShop = false;
            itemID = 0;
        };

```

---
Tags: javascript, rpg-maker
---


title: Question about performance

text:
# Question
Title: Question about performance
I'm new of the topic, and today, I tried my first OpenGL program. It simply drawa a particular figure to the screen, and allows the user to rotate around it with buttons.

Writing code, I was thinking about rendering. When I create a list with `glBeginList` and I rotate, I cancel the figure on the screen and rotate the camera, before redrawing the figure.

Do I have to cancel everything and redraw for animation, or is there another way?

# Answer
> 4 votes
This is a common query among beginners, and yes, it can seem wrong that you have to redraw everything rather than just the parts that have changed.

However, your GPU prefers it if you do this. It can make assumptions, throw away previous frames, not have to worry about preserving old data, and take faster code paths.

So yes, you should redraw everything, and don't worry about performance if you do so.

---
Tags: opengl
---


# Question
Title: Find your value between four values in a grid based on distance, Unity
Please note: Originally posted in stack overflow, redirected due to nature of problem.

I am making a procedural mesh game. I am trying to calculate the temperature for the player's current chunk by getting nearby temperature values and interpolating.

The way this works is, let's say we are at world space 95, 0, 65 (x,y,z). What I do is:

1) generate, using perlin noise, temperature values for every 20 squares (smartly generated to only do so to the 4 squares most relevant to us at any given time). We will get the points: 80, 0, 60 100, 0, 60 80, 0, 80 100, 0, 80

Each of these points is fed into a perlin noise generator and spits out a number. That number is the temperature.

So, in order to make the climate smoothly transition, I need to figure out how to get the distance each point weighted against its temperature so I can calculate the temperature of the space I am standing in.

If there is a name for this (there must be, I'm essentially sampling a gradient made by four points) and a way to do it, please just link that instead.

I tried taking the distance from my point to each point and multiplying that number against the temperature at that point, but I'm not sure if that's a correct first step, or what to do from there (just average the four resulting numbers?!).

# Answer
The term you are looking for is bilinear interpolation.

If you have a grid of values, and you want to know what a value is when it's inbetween grid points, you can use bilinear interpolation to do this.

To do this you get the 4 grid points around the point you are looking at. You then interpolate the two values across the X axis, and then interpolate between those two values across the Y axis.

Here's an image showing how this works:

The values at the corners are 7, 0, 3, 5 as labeled, and if you need to get the value where the relative coordinates inside of the grid cell are (0.2, 0.8), you can use linear interpolation to find the value for that point as 5.16.

It doesn't actually matter if you interpolate across the X axis and then the Y axis or the other way around, it comes up with the same value.

You can read more about bilinear interpolation here:

http://blog.demofox.org/2015/04/30/bilinear-filtering-bilinear-interpolation/

Note that bilinear interpolation is only ONE way to do this. There are many other ways to do this, but another popular method is bicubic interpolation. While linear interpolation interpolates values, bicubic interpolation interpolates both values as well as value slopes (the first derivative) so can be helpful in circumstances where you want smooth derivatives, like you might in the case you describe.

It works by doing cubic interpolation across one axis, and then the other, just like how bilinear interpolation works across one axis, and then the other.

For cubic interpolation (across a single axis) you need the closest 4 points on that axis, not just the closest 2 line linear needs.

The math is a bit more complex, but you can read more about the details here:

http://blog.demofox.org/2015/08/08/cubic-hermite-interpolation/

This link shows the differences when using a couple different types of 2d interpolations on pixels in an image, and has source code for each:

http://blog.demofox.org/2015/08/15/resizing-images-with-bicubic-interpolation/

EDIT:

I just noticed you are working in 3d not 2d. Everything I said still applies though. Interpolate the values across the X axis, then the Y axis, then the Z axis, and you'll have your result.

You'll need to interpolate 4 values across the X axis.

Then, you'll need to interpolate 2 values across those values, along the Y axis

Lastly, you'll interpolate across those 2 values along the Z axis to get your resulting value.

In 3d, the terminology is trilinear interpolation and tricubic interpolation.
> 1 votes

# Answer
You do not need to do anything special: Perlin noise *is a gradient noise* and is designed to give you an interpolated value at any point, not just at the square corners. Just use your Perlin noise generator at the player’s position.
> 1 votes

# Answer
What you will want is some form of linear interpolation, with weightings based on the distances to each square.

You could, if you wanted to be spiffy, model an actual thermal conduction coefficient.
> 0 votes

---
Tags: c#, mathematics, vector
---


# Question
Title: Accessing cbuffer values in other functions
I have a shader that is not loading correctly and causing my Vertex Shader object to be a nullptr and Visual Studio is throwing an exception. The specific issue that is occurring is at the following lines below:

```
 D3DX11CompileFromFile(L"shaders.shader", 0, 0, "VShader", "vs_5_0", 0, 0, 0, &VS, 0, 0);

```

and because of that not compiling correctly, the corresponding call create the shader is throwing the nullptr exception.

```
dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &pVS);

```

I am guessing that it is due to a syntax error within the shader. I have a cbuffer that holds the view and projection matrices and would like to multiply those with the vertices as they are passed. What is the correct syntax to use the variables in the cbuffer in another functino within the shader file?

**windowSource.cpp**

```
void ParseGraphics() {
    // Build constant buffer for matrix data
    D3D11_BUFFER_DESC matrixBufferDesc;
    ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc));
    matrixBufferDesc.ByteWidth = sizeof(VS_CONSTANT_BUFFER);
    matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    matrixBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    matrixBufferDesc.MiscFlags = 0;
    matrixBufferDesc.StructureByteStride = 0;

    D3D11_SUBRESOURCE_DATA matrixSubResourceData;
    matrixSubResourceData.pSysMem = &shaderMatrixBuffer;
    matrixSubResourceData.SysMemPitch = 0;
    matrixSubResourceData.SysMemSlicePitch = 0;
    hr = dev->CreateBuffer(&matrixBufferDesc, &matrixSubResourceData, &pShaderMatrixConstantBuffer);
    if (FAILED(hr)) {
        OutputDebugString(L"Matrix Buffer Creation Failed");
    }

    devContext->VSSetConstantBuffers(0, 1, &pShaderMatrixConstantBuffer);

    // Create Vertex Buffer
    D3D11_BUFFER_DESC v_bd;
    ZeroMemory(&v_bd, sizeof(v_bd));
    v_bd.Usage = D3D11_USAGE_DYNAMIC;
    v_bd.ByteWidth = sizeof(Vertex) * 6;
    v_bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    v_bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    dev->CreateBuffer(&v_bd, NULL, &pVBuffer);

    // copy vertices into buffer
    D3D11_MAPPED_SUBRESOURCE msr;
    devContext->Map(pVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &msr);
    memcpy(msr.pData, square, sizeof(square));
    devContext->Unmap(pVBuffer, NULL);

}

void BuildPipeline() {
    // Load and Compile Shaders
    ID3D10Blob *VS, *PS;
    D3DX11CompileFromFile(L"shaders.shader", 0, 0, "VShader", "vs_5_0", 0, 0, 0, &VS, 0, 0);
    D3DX11CompileFromFile(L"shaders.shader", 0, 0, "PShader", "ps_5_0", 0, 0, 0, &PS, 0, 0);

    // Create shaders from the data in the Blobs Buffer
    dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &pVS);
    dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pPS);

    // Apply Shaders to the device context
    devContext->VSSetShader(pVS, 0, 0);
    devContext->PSSetShader(pPS, 0, 0);

    // Define the layout of the input given to the shaders
    D3D11_INPUT_ELEMENT_DESC ied[] =
    {
        {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},

    };

    dev->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
    devContext->IASetInputLayout(pLayout);

}

```

**shaders.shader**

```
struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

cbuffer VS_CONSTANT_BUFFER : register(b0) {
    matrix viewMatrix;
    matrix projMatrix
}

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;

    output.position = mul(position, viewMatrix);
    output.position = mul(output.position, projMatrix);
    output.color = color;

    return output;
}

float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

```

**UPDATED CODE**

**New shaders.shader file**

```
struct Vin {
    float3 position : POSITION;
    float4 color : COLOR0;
};

struct VOut{

    float4 position : SV_POSITION;
    float4 color : COLOR1;
};

cbuffer VS_CONSTANT_BUFFER : register(b0) {
    matrix viewMatrix;
    matrix projMatrix;
};

VOut VShader(Vin input)
{
    VOut output;
    output.position = mul(float4(input.position, 1), viewMatrix);
    output.position = mul(output.position, projMatrix);
    output.color = input.color;

    return output;
}

float4 PShader(VOut output) : SV_TARGET
{
    return color;
}

```

# Answer
> 2 votes
Ok so a few things, you missed a ; after your projmatrix and at the end of the CB struct and the rest here:

Looking at your inputlayout

```
D3D11_INPUT_ELEMENT_DESC ied[] =
{
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},

};

```

You have the POSITION as a vector3 and then in your vertex shader input you have it as a vector4, should be "float3 position : POSITION0;"

```
VOut VShader(float3 position : POSITION0, float4 color : COLOR0)

```

Your pixel shader input should be the same as the vertex shader output

```
float4 PShader(VOut input) : SV_TARGET

```

The way to access a CB from a different function is just the way you are doing it, think of a CB as a holder for global variables you can use them in any shader stage that you bind the CB to.

How I would write the shader:

```
struct VOut
{
float4 position : SV_POSITION;
float4 color : TEXCOORD0;
};
struct Vin
{
float3 position : POSITION0;
float4 color : COLOR0;
};
cbuffer VS_CONSTANT_BUFFER : register(b0)
{
matrix viewMatrix;
matrix projMatrix;
};

VOut VShader(Vin Input)
{
VOut output;

output.position = mul(float4(Input.position,1), viewMatrix);
output.position = mul(output.position, projMatrix);
output.color = Input.color;

return output;
}

float4 PShader(VOut input) : SV_TARGET0
{
return color;
}

```

----------------------------------EDITS------------------------------------------

You really need to make sure you are writing your code correct.

You missed a 0 on the end of the vertex input POSITION and the vertex output should be COLOR0 and SV\_TARGET should be SV\_TARGET0, the COLOR semantic has funky interpolation if I recall so you should always use TEXCOORD when passing color to the pixel shader, in fact I use TEXCOORD for passing most things.

You should really go have a look at the MSDN docs and read about shader Semantics.

One more thing, looking at your CPU code again I see you are using the directX utility lib and that could be your problem have a look here you should be using the built in dx11 compiler look here.

> **D3DX11CompileFromFile function**
>
> **Note** The D3DX (D3DX 9, D3DX 10, and D3DX 11) utility library is deprecated for Windows 8 and is not supported for Windows Store apps.
>
> **Note** Instead of using this function, we recommend that you compile offline by using the Fxc.exe command-line compiler or use one of the HLSL compile APIs, like the **D3DCompileFromFile API**.

I use sharpDX but its just a wrapper around directX so you should be able to convert this snippet over:

```
Dim Res As CompilationResult = ShaderBytecode.CompileFromFile("Shader.fx", "VShader", "vs_5_0", ShaderFlags.Debug Or ShaderFlags.PackMatrixRowMajor, D3DCompiler.EffectFlags.None, Nothing, ShaderInc)

```

I use that and get a working shader just checked it a few times.

You should have a look at one of my other answers and set visual studio up so you can compile shaders with it and get error and warnings in the output window and lots of other cool stuff.

---
Tags: c++, directx11, hlsl
---


# Question
Title: How to draw 2D racing tracks using vector graphics?
See this game.

I am trying to build a similar one using Unity. However, I am not sure how to build the scene, specifically, the walls. Unity 2D allows me to create Sprite, but what kind of sprite should I use? Or I am on the wrong direction?

# Answer
I found a pretty good example http://www.iforce2d.net/b2dtut/top-down-car, which uses Box2D.

To create the track, one creates a subclass of a `world` class and populates it with a pre-defined world, stored in a file, usually a json file. To create such a file, one can use Box2D's world editor. A good editor is R.U.B.E, another is Epic-World-box2d-editor(search github). I haven't tried either but according to their doc, they are what I am looking for.

As for how to render the simulation from a top-down view, one can define the world to be zero-gravity. Then, to drive the car forward or backward, just give the car a positive or negative velocity in `y` direction, respectively. To drive the car left or right, give the car a positive or negative velocity in `x` direction, respectively. One can apply fictions too.
> 1 votes

---
Tags: unity, 2d, rendering
---


# Question
Title: In WebGL, how can I efficiently render a mesh many times per frame, without instancing?
I'm using WebGL and I want to render a single mesh many times at different locations. I know about WebGL 2's `drawArraysInstanced()` and `drawElementsInstanced()` calls, but I think only Firefox supports them now.

The only solutions I see are :

1. Put all the meshes in a single buffer and render it with a single call to `drawArrays()`/`drawElements()`, but that would be a waste of memory because the mesh contains a lot of vertices and if the meshes are not static I would need to re-load the vertices in gpu memory every frame or so.
2. Have a single mesh in memory and render each instance with a separate call to `drawArrays()`/`drawElements()`, updating the model matrix between each call. I don't think that's the best way.

Any ideas? Thanks

# Answer
You need the same exact mesh, thus you only need one vertex buffer with the mesh info of 1 model. No need for very long vbos.

Remember, if you don't multiply the mesh's position with a model matrix in the shader, then you get the mesh in the center of the scene without any rotation.

If you want it to be in the scene multiple times at different positions, bind the model obly once, then for each of them load in a different model matrix to the shader and call the appropariate draw function.

This is pretty efficient, you only send 2 calls to the GPU every time you render a new model, and it uses significantly less VRAM thab the instancing method (you don't need a separate vbo for the locations).
> 1 votes

# Answer
Putting all your meshes in one big buffer and render it with one drawArrays call is not even half as bad. However, this has a few drawbacks. If a mesh ever needs to change, you'll have to update the buffer. Whilst that is not that expensive, if this happens frequently and with multiple objects, it will become a bottleneck.

It all depends on how many objects you have and how much they have to move. If its all static geometry, you'll be fine with one big buffer (although I would still recommend just using instanced anyway). If they should move every frame, you should use multiple drawcalls.

The only way to make sure is just to try it and look at the results.
> 0 votes

---
Tags: opengl, webgl
---


# Question
Title: Replacing all objects in scene with another object
I have around 100 objects (prefab A) in my scene, all in different positions.

Is it possible to replace all of these objects with another object (prefab B), so that the prefab B objects are placed in the same position as the prefab A objects were?

I want this done in the editor, not in game.

# Answer
> 2 votes
This can be easily done, manually, in a variety of ways. Unfortunately, you report having **100** game objects that you wish to exchange, in this way. Rather than manually completing the task, let us write a *script* to do it.

Note that this is still specific to the *editor*. Using the namespace `UnityEditor`, you have the ability to manipulate the editor, which allows you to complete repetitive tasks such as this one.

---

This is a stand alone script that you can attach to *any* game object, in order to complete the described task with less repetition. It allows you to replace game objects en mass, by either storing them into an array, or by using tags to automatically construct an array.

Note that you specifically mention *position*. I also take *rotation* in to account, as well as potential parenting. If you do not wish to include rotation, simply use `Quaternion.identity` for the rotation value. If you do not wish to include parenting, simply remove the `if` statement that handles it.

```
using UnityEngine;  // UnityEngine gives us general access.
using UnityEditor;  // UnityEditor gives us editor-specific access.

/// <summary>Performs manual iteration to swap out one game object for another.</summary>
public class PrefabSwitch : MonoBehaviour
{
    /// <summary>The new object to instantiate in place of the old object.</summary>
    public GameObject newPrefab;
    /// <summary>The old objects, intended to be swapped out for iterations of
    /// the new object.</summary>
    public GameObject[] oldGameObjects;
    /// <summary>The string tag to use when replacing objects by tag.</summary>
    public string searchByTag;

    /// <summary>Swaps all the game objects in oldGameObjects for
    /// a new newPrefab.</summary>
    public void SwapAllByArray()
    {
        // Store a boolean to detect if we intend to swap this game object.
        bool swappingSelf = false;

        // For each game object in the oldGameObjects array,
        for (int i = 0; i < oldGameObjects.Length; i++)
        {
            // If the current game object is this game object,
            if (oldGameObjects[i] == gameObject)
            {
                // Enable the flag to swap this game object at the end, so we
                // do not destroy it before the script an complete its task.
                swappingSelf = true;
            }
            else
            {
                // Else, we are not dealing with the game object local to this
                // script, so we can swap the prefabs, immediately.
                SwapPrefabs(oldGameObjects[i]);
            }
        }

        // If we have flagged the local game object to be swapped,
        if (swappingSelf)
        {
            // Swap the local game object.
            SwapPrefabs(gameObject);
        }
    }

    /// <summary>Swaps all the game objects that use the tag <code>searchByTag</code>.
    /// If empty, we will use the tag of the local game object.</summary>
    public void SwapAllByTag()
    {
        // If searchByTag is null,
        if (searchByTag == "")
        {
            // Set searchByTag to the tag of the local game object.
            searchByTag = gameObject.tag;
        }

        // Find all the game objects using the tag searchByTag,
        // store them in our array, and proceed to swapping them.
        oldGameObjects = GameObject.FindGameObjectsWithTag(searchByTag);
        SwapAllByArray();
    }

    /// <summary>Swaps the desired oldGameObject for a newPrefab.</summary>
    /// <param name="oldGameObject">The old game object.</param>
    void SwapPrefabs(GameObject oldGameObject)
    {
        // Determine the rotation and position values of the old game object.
        // Replace rotation with Quaternion.identity if you do not wish to keep rotation.
        Quaternion rotation = oldGameObject.transform.rotation;
        Vector3 position = oldGameObject.transform.position;

        // Instantiate the new game object at the old game objects position and rotation.
        GameObject newGameObject = Instantiate(newPrefab, position, rotation);

        // If the old game object has a valid parent transform,
        // (You can remove this entire if statement if you do not wish to ensure your
        // new game object does not keep the parent of the old game object.
        if (oldGameObject.transform.parent != null)
        {
            // Set the new game object parent as the old game objects parent.
            newGameObject.transform.SetParent(oldGameObject.transform.parent);
        }

        // Destroy the old game object, immediately, so it takes effect in the editor.
        DestroyImmediate(oldGameObject);
    }
}

/// <summary>Custom Editor for our PrefabSwitch script, to allow us to perform actions
/// from the editor.</summary>
[CustomEditor(typeof(PrefabSwitch))]
public class PrefabSwitchEditor : Editor
{
    /// <summary>Calls on drawing the GUI for the inspector.</summary>
    public override void OnInspectorGUI()
    {
        // Draw the default inspector.
        DrawDefaultInspector();

        // Grab a reference to the target script, so we can identify it as a
        // PrefabSwitch, instead of a simple Object.
        PrefabSwitch prefabSwitch = (PrefabSwitch)target;

        // Create a Button for "Swap By Tag",
        if(GUILayout.Button("Swap By Tag"))
        {
            // if it is clicked, call the SwapAllByTag method from prefabSwitch.
            prefabSwitch.SwapAllByTag();
        }

        // Create a Button for "Swap By Array",
        if (GUILayout.Button("Swap By Array"))
        {
            // if it is clicked, call the SwapAllByArray method from prefabSwitch.
            prefabSwitch.SwapAllByArray();
        }
    }
}

```

---

### Replace By Tag

Replacing game objects by tag seems to be the most viable option, short of manually selecting the group of game objects you wish to swap out. If the set of game objects you are swapping out are all of the same prefab, replacing by tag is even easier.

First, you want to make sure that all of the targeted objects have the same tag. If needs be, you can make a temporary tag, to specifically mark the objects you wish to swap. You can apply this tag to the *prefab* of the old objects, and simply update it to impact all of them. Keep in mind that *only* the game objects you intend to swap should use this tag; the script will target *all* game objects using the given tag.

### Replace By Array

Replacing by array still requires a small amount of manual work, but allows you to quickly select a group of game objects, and immediately swap them out. This method is especially useful, as it allows you to quickly select the desired group, and is more reliable in that you confirm exactly which objects will be affected.

Note that you can select a group of objects and drag them on to a public array, to add them to the list as shown, below. If you drag *additional* objects on to the array in the same way, where there are already objects in the array, the new objects will simply be *added* to the array, along with the original objects that were already there.

Also note that you can click on the padlock icon, at the top right corner of the inspector, to lock that view. If you do not do this, selecting your group of old game objects will take focus away from the selected object. This is especially annoying when the selected object was the container for your script, and in taking focus away, you are unable to drop your selection on to the scripts public array.

# Answer
> 4 votes
This will be an unusual way to go about it, because you don't want to script it. It will still take some time, but it's better than doing it one by one, and it should work as well as you want it to.

1. Select all the game objects you want to change.
2. Right click on one of the game objects while they are all selected, select *"3D Object"*, and select any of the options.

3. Place a copy your prefab in the scene, and then copy it with `ctrl + c`. Select one of the newly made child objects and paste the prefab with `ctrl + v`. Rinse and repeat until each of the new child objects has a copy of your prefab attached.
As I did not have any other game objects between my new game objects, in the hierarchy, I was able to quickly move between each game object by pressing the  key, twice. If this is the case, for you, you should be able to repeat the pattern of (, , `ctrl`+`v`). Remember that you have to paste the prefab on the *child game objects*; not the parents.
4. Search for the prefab by name, and select them all. Set their coordinates to (0, 0, 0). This will set them to the exact same position as the parent game objects.

5. Clear the search result from the search bar by selecting the X. This will let you return to the full scene view, while still keeping all of those game objects selected. Drag and drop the selected game objects on to the scene name, which should remove them as parents from the original game objects.

6. Remove the original game objects. If you did everything right, your new objects should be where you wanted them to be, and the old ones should be gone.

# Answer
> 1 votes
Yes, Unity's inspector panel allows you to copy components from one GameObject and then paste them on another, by clicking on the cog icon at the top right of the component.

In your case, you want to copy the Transform component (by default, the first component).

See images below for visual reference.

# Answer
> 1 votes
If the top level gameObject of your prefabs serves merely as a container for the components of the prefab, then you can try the following:

* Create an new instance of PrefabA ('PrefabA\_New')and PrefabB on the same position (eg. 0,0,0).
* Copy the contents of PrefabB's container gameObject, into the container of PrefabA\_New, on the same level as the original contents of PrefabA\_New. Unity will tell you that this will break the prefab. Accept.
* Delete PrefabA\_New's original content (do not delete PrefabB's content that you dragged into PrefabA\_New).
* Click 'Apply' on PrefabA\_New so that it updates PrefabA. This will cause all the other instances of PrefabA to be the same as PrefabA\_New (Which, in effect, is the same as PrefabB).

You can then proceed to delete PrefabB and PrefabA\_New.

I hope this works. Good luck!

---
Tags: unity
---


# Question
Title: How to use traditional pixel coordinates system in modern OpenGL? (3.1) (with C++/GLFW)
This question is very similar to my other question, however the solution provided there does not work when using OpenGL 3.1. glOrtho seems to do absolutely nothing no matter where I call it in OpenGL 3.1. Googling this didn't give me any decent results. Should I be doing something in the fragment/vertex shaders, or?

# Answer
In modern OpenGL (\> 2.0 actually) the matrix stack has been removed . The matrix stack was part of the fixed pipeline. The fixed pipeline (for example, glBegin, glEnd) is deprecated and has been replaced in favour of a programmable pipeline.

This requires you to use shaders and supply your own transform matrices. I recommend reading this for a great tutorial set on modern OpenGL. It covers everything from the basic setup of drawing a triangle to the matrices you need.

Keep in mind, comparing to older versions (with glOrtho for example) this new pipeline is much harder to learn and understand. There is not really an easy way out.

EDIT: Fixed my statement about the removed pipeline (as Dudeson pointed out). The older OpenGL code should still work on newer platforms, but you can't use both in modern OpenGL (its bad practice to use the fixed pipeline eitherway)
> 1 votes

# Answer
Yes, you should do something in the shader. A simple vertex shader would be something like:

```
#version 140

in vec3 position;

uniform mat4 mvp;

void main() {
    gl_Position = mvp * vec4(position, 1.0);
}

```

GLSL's versions

Where `mvp` is your full matrix (projection, view, model) that you pass from your code. In your case, you want your projection to be orthogonal matrix by either making one yourself or use a library like glm.
> 0 votes

# Answer
This is how a usual orthographic projection matrix looks like. r, l, t, b, f, and n are the positions of the right, left, top, bottom, far and near clipping planes respectively. To achieve your desired effect:

```
r should be the width of the display in pixels
l is 0
t is 0,
b should be the height og the display in pixels
f should be something like 1000
n should be something like -1000

```

The last 2 doesn't matter, but f should be bigger than n.

After you created this matrix, you need to create a shader, load in this as the projection matrix and multiply the eye-space position of the vertex with it.
> 0 votes

---
Tags: opengl, c++, coordinates, pixel
---


title: What am I doing wrong? Date comparison

text:
# Question
Title: What am I doing wrong? Date comparison
There's this one precious little if in my code that is not doing what I want him to do.

Language is written in C# and doing it in Unity

Basically, I put a date on the Inputfield, which is linked to: BonoFinish, as soon as BonoFinish reaches DateTime.Now, it should appear a new gameobject, problem is... it does crap. What am I missing? Here's the code:

```
if (BonoFinish ==  DateTime.Now)
    {

        PagPrincipal.SetActive (false);

        print (DateTime.Now);

        Bonos.SetActive (true);

        Debug.Log ("funciona");

        Invoke ("apagaBonos", 30f);
    }

```

Also, Bonofinish is written like this: `BonoFinish = DateTime.ParseExact (HoraBono.text, "dd-MM-yyyy HH:mm", null);`

# Answer
`DateTime.Now` returns a `DateTime`. This is an object that represents both a date *and* a time. Equality comparison will naturally check both the date and time portions, and the time portion has millisecond accuracy.

That means that comparison will only ever be true for exactly one millisecond, so it's very unlikely you will ever *see* it be true. One iteration of a game loop can easily be several milliseconds long and cause you to skip the point in time where "now" precisely equals your stored date; even if you only parse your stored date out to minute resolution, there are still values in the second and millisecond fields (they're 0).

Chances are you only want to compare the date and time down to a more reasonable granularity, such as (perhaps) *just* the date. You can do this by comparing the components you care about directly:

```
var now = DateTime.Now;
if(now.Year == BonoFinish.Year && now.Month == BonoFinish.Month...)

```
> 1 votes

# Answer
Josh Petrie's answer is good in and of itself, but accessing different components of `Datetime.Now` and the `BonoFinish` object that many times might create a bottleneck point. A better way of doing the check would be to subtract them from each other, and then check whether the remaining time is good for you.

```
 var datetimetoday = DateTime.Today;
 var datetimenow = DateTime.Now;
 print(datetimenow - datetimetoday);
 print((datetimenow - datetimetoday).Hours);
 if((DateTime.Now - DateTime.Today).Hours>10)
 {
     print("This code works!");
 }

```

Right now (at hour 14:24 for my local time) this code gives the following results:

> 14:23:28.3691344 //(That's hours:minutes:seconds.ticks)
>
> 14
>
> This code works!

You have also gotten rid of possibly 6 combined if statements and made them into a subtraction (which actually uses ticks, so it's a one-off calculation) and an if statement.
> 1 votes

# Answer
As an alternative to Josh's code, this is definitely because it is comparing the time components. You can eliminate the time component in a number of ways. I find using `DateTime.Date` more succinct:

```
if (BonoFinish.Date ==  DateTime.Now.Date)
{
    //Your code
}

```

This equates the 2 dates with a time of `00:00:00`
> 1 votes

# Answer
I am not sure I understood where the problem is, if you are having troubles getting inside the If statement, or you can get in but your GameObject doesn't spawn.

In the first case, try to Debug on console both BonoFinish and DateTime.Now to be sure they are the same, and in case, why they do not match. ParseExact is a very precise function and it is expecting a valid input format (which you seem to be providing), the only test you can make are about HoraBono.text and if its input is well-formatted and recognized by the function.

In the second case, assuming that you can reach "Debug.Log ("funciona")", two possible things can cause the object not to spawn: 1) there is an error inside apagaBonos function, or you are not actually "ticking" 30 seconds. This can be due to a lot of factors, for example you could be calling this code inside an Editor script.
> 0 votes

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


# Question
Title: 2d starship combat, hit chances based on bearing and speed (vector)?
Thinking about a 2d strategy game, where you move your starships turn by turn and fire guns at each other.

Instead of the traditional approach of "range" lowering hit chances, im thinking about some sort of system that throws vectors at each other to calculate relative bearing and speed to calculate hit chances.

I.e. a fast, small ship is harder to hit than a slow, big chip, but in addition the relative bearing (im thinking: is the target flying straight towards your X/Y = good hitchance, or is it strafing very narrowly, low hitchances depending on speed).

Getting the relative the bearing (angle) on an approaching vessel would be easy using atan2, but how could this be translated it into a hitchance that goes up if the angle is like 330 to 30 degree and goes down if its different (as an example) ?

# Answer
You simply need a parametrical equation.

A good way to get how different the 2 ship's angle is is to use dot product on the ship's direction vector and the normalised version of the vector pointing from the current ship to the other ship. This'll return 1 if the ship is looking right at the other ship and -1 if it's looking in the other direction. We should normalize this value by addibg 1 to it and then dividing the sum by 2. In equation this looks like this:

```
angleParam := (dot(direction, normalize(vec2(otherX - currentX, otherY - currentY))) + 1) / 2

```

Now the speed: You should have a max speed of a ship, and the speed of the 2 spaceships (currentSpeed and otherSpeed). To get a value between 0 and 1:

```
speedParam := (currentSpeed - otherSpeed) / maxSpeed / 2;

```

I don't know how you calculate the size, but let's assume it's a value between 0 and 1. If it's not between 0 and 1, then you need to somehow map it between these 2 values.

To get a chance from these, you can use the following equation:

```
chance := (angleParam * ⅓ + speedParam * ⅓ + sizeParam * ⅓)

```

This is a value between 0 and 1.

You can change the ⅓s to any value you want based on how you want the chance to be calculated (like when size has a bigger impact on aiming than speed, then you should make size have a bigger multiplier than speed), but they should add up to 1.
> 2 votes

# Answer
Using the angles you provided as example, I took the liberty of assuming a few other data / scenarios.

Let's say you want a 100% hit chance when the angle difference is 0, and have the "good extremes" to be 75% at 330º and 30º, with intervals between those.

The first thing you should do is check if the angle is between 0 and 180, or between 180 and 360. If it's in the second bracket, you'll want to subtract 360 to its value. In either case, you'll then divide the angle by 30, to obtain a range of values that will go from -1 at 330, to 1 at 30.

You'll then want to divide that desired dispersion (in this case, 25%) by the inverse of the absolute value of this multiplier, in order to know how much to reduce from the accuracy.

Example code for Unity in C# (untested):

```
if(angleDiff >= 180 && angleDiff <= 360)
{
    angleDiff -= 360;
}

precisionMultiplier = angleDiff / 30;

if(precisionMultiplier != 0)
{
    accuracyReduction = dispersion / (1 / Mathf.Abs(precisionMultiplier));
}

chanceToHit = 100 - accuracyReduction;

```

There are many things you can do with this, and there is room for several more variables / improvements. For instance, you can have each ship start with a default precision, different to 100%, and have that number be at its maximum when the angle difference is 0 by using its precision instead of the hard-coded "100".

Also, keep in mind that the precision multiplier, if divided by 30, will vary from -6 to 6 when accounting all 360 degrees, so you can have a separate logic, indicating a different accuracy decay, by contemplating the cases in which its value is greater beyond the -1 to 1 range.
> 1 votes

---
Tags: vector, angles, strategy
---


title: C++ OpenGL loading models fast

text:
# Question
Title: C++ OpenGL loading models fast
I'm looking for a faster solution that will allow me to load objects faster with OpenGL and currently when trying to load, parse and pass the data on my main thread it takes a while... Would multi-threading be a reasonable solution to this and if so, how would I go about it?

Would I make a second thread with the same context and save the data once it has loaded or...

Would I create a second thread to load and parse the data, then pass it back to the first thread to save to the GPU?

This is the limit of my knowledge of this subject at the minute, if anyone has any better solutions please drop me a comment.

# Answer
> 5 votes
You've mentioned "parse the data" a few times, which suggests to me that you're probably using .obj files; even if not, the fact that you have to parse data is sufficient.

The fastest work is the work that you don't have to do at all. Parsing data can be slow; parsing, interpreting, converting and validating plain text data from a .obj file is even slower.

The fastest model loading consists of the following steps:

* Memory-map the model file.
* Read and interpret a lightweight header to get basic info such as size, number of frames, etc.
* Pass the data pointer into a glBufferData call.
* Done.

With this kind of setup there is no parsing at all, there is no shuffling data around between multiple intermediate buffers, the model data goes directly into a VBO and is already in the format that GL will use it in.

There are some things that you can infer from all of this.

* Don't use .obj files.
* Prefer binary data over plain text data.
* Don't use .obj files.
* Keep your data in as close to the format that GL will consume it in as possible.
* Don't use .obj files.
* Move data between as few intermediate buffers as possible.
* Don't use .obj files.

Not using .obj files probably deserves some further discussion, particularly since you will frequently see them used in tutorials. .obj files are actually fine for tutorials, they're fine as an intermediate format and they're fine as an interchange format. What they're not fine as is a final format optimized for fast loading.

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


title: Monogame - Sprite sheet animation

text:
# Question
Title: Monogame - Sprite sheet animation
I have a sprite sheet that contains a character walk cycle, and I have made a player class that allows the player to move and cycle through the walk animation, however the animation only works whilst walking to the right. I use the arrow keys to move up, down, left and right, meaning when I press any key, my player moves in the correct direction, but only performs the **animation of walking to the right**.

The current animation that works, has been called like this in the `LoadContent()` function:

```
spritesheet = Content.Load<Texture2D>("sprites2");

player = new Player(spritesheet, new Rectangle(0, 96, 32, 48),
new Vector2(100, 100), 4);

```

This does its job, as it calls each 4 sprites to complete the walking animation to the right, and `new Rectangle(0,96,32,48)` is the location cut out from the sprite sheet. However I need (for example) `new Rectangle(30, 101, 65, 52)` to be used also, which will correctly animate my character when the left arrow key has been pressed.

My question is, how would I get another location of the sprite sheet loaded, and then actually work when I press the correct key?

This is a very difficult question to ask and I very much apologize if it was difficult to understand. Accepting all edits to my question, and thank you in advanced.

# Answer
A very high-level thought would be to separate your sprite-sheet into different sheets for each direction so that on different key-presses you can specify which sheet to cycle through, and then you don't need to worry about confusing offsets
> 0 votes

# Answer
Store your animations in an animation dictionary. You can use a `Dictionary<string,Rectangle[]>` or create a more elaborate construction that holds more frame information (rectangle, timing, offsets).

So you have a dictionary like this (all pseudo code):

```
Animations["walk_right"]=new Rectangle[4]{new Rectangle(0,0,10,10), ... }

```

Keep in your character object the current animation and the timing.

```
 if(walking_to_right)
     current_animation="walk_right";
 if(walking_to_left)
     current_animation="walk_left";

 //-- do the timing stuff

```

then in the draw:

```
 spriteBatch.Draw(spritesheet,position,animation[current_animation][frame]);

```
> 3 votes

# Answer
A possible approach would be to have one animation per row, and then the desired row could be passed in based on the direction.
> 0 votes

---
Tags: c#, xna, sprites, monogame
---


# Question
Title: Non-integer speed values - is there a cleaner way to do this?
Often I will want to use a speed value such as 2.5 for moving my character in a pixel-based game. Collision detection will generally be more difficult if I do that, though. So I end up doing something like this:

```
moveX(2);
if (ticks % 2 == 0) { // or if (moveTime % 2 == 0)
    moveX(1);
}

```

I cringe on the inside every time I have to write that, is there a cleaner way to move a character with non-integer speed values or will I remain stuck doing this forever?

# Answer
# Bresenham

In the old times, when people were still writing their own basic video routines for drawing lines and circles, it was not unheard of to use the Bresenham line algorithm for that.

Bresenham solves this problem: you want to draw a line on the screen which moves `dx` pixels in the horizontal direction while at the same time spanning `dy` pixels in the vertical direction. There is an inherent "floaty" character to lines; even if you have integer pixels, you end up with rational inclinations.

The algorithm has to be fast though, which means that it can use integer arithmetic only; and it also gets away without any multiplication or division, only addition and subtraction.

You can adapt that for your case:

* Your "x direction" (in terms of the Bresenham algorithm) is your clock.
* Your "y direction" is the value you want to increment (i.e., the position of your character -- careful, this is not actually the "y" of your sprite or whatever on the screen, more an abstract value)

"x/y" here are not the location on the screen, but the value of one of your dimensions in time. Obviously, if your sprite is running in an arbitrary direction across the screen, you will have multiple Bresenhams running separately, 2 for 2D, 3 for 3D.

# Example

Let's say you want to move your character in a simple movement from 0 to 25 along one of your axes. As it is moving with speed 2.5, it will arive there at frame 10.

This is the same as "drawing a line" from (0,0) to (10,25). Grab Bresenham's line algoritm and let it run. If you do it right (and when you study it, it will very quickly become clear how you do it right), then it will generate 11 "points" for you (0,0), (1,2), (2,5), (3,7), (4,10) ... (10,25).

# Hints on adaptation

If you google that algorithm and find some code (Wikipedia has a pretty large treaty on it), there are some things you need to watch out for:

* It obviously works for all kinds of `dx` and `dy`. You are interested in one specific case though (i.e., you will never have `dx=0`).
* The usual implementation will have several different cases for the quadrants on the screen, depending on whether `dx` and `dy` are positive, negative, and also whether `abs(dx)>abs(dy)` or not. You of course also pick what you need here. You have to make especially sure that the direction which is increased by `1` every tick is always your "clock" direction.

If you apply these simplifications, the result will be very simple indeed, and get completely rid of any reals.
> 13 votes

# Answer
There is a simple way to do exactly what you want.

In addition to a `float` velocity you'll need to have a second `float` variable which will contain and accumulate a difference between *real* velocity and *rounded* velocity. This difference is then combined with velocity itself.

```
#include <iostream>
#include <cmath>

int main()
{
    int pos = 10;
    float vel = 0.3, vel_lag = 0;

    for (int i = 0; i < 20; i++)
    {
        float real_vel = vel + vel_lag;
        int int_vel = std::lround(real_vel);
        vel_lag = real_vel - int_vel;

        std::cout << pos << ' ';
        pos += int_vel;
    }
}

```

Output:

> 10 10 11 11 11 12 12 12 12 13 13 13 14 14 14 15 15 15 15 16

---

Alternatives include:

* Using floating-point coordinates under the hood, and rounding them.
This can cause precision problems if the coordinates have large absolute values.
* Using fixed-point coordinates.
This is probably superior to the solution suggested above, but you either need to find a fixed-point math library, or code fixed-point math manually, which requires more effort.
> 26 votes

# Answer
Use floating values for movement and integer values for collision and rendering.

Here's an example:

```
class Character {
    float position;
public:
    void move(float delta) {
        this->position += delta;
    }
    int getPosition() const {
        return lround(this->position);
    }
};

```

When you move you use `move()` which accumulates the fractional positions. But collision and rendering can deal with integral positions by using the `getPosition()` function.
> 16 votes

---
Tags: c++, 2d, movement, floating-point
---


# Question
Title: How to make it so that My SplashState will switch to my MenuState after few seconds
I have a SplashScreen class( SplashState) which will show first when someone opens my game, and what i want to do is that my Game will show the SplashState for lets say 5 seconds and after 5 seconds, it will switch to my MenuState. How can I do that(btw im a noob in java, sorry if I got you cringed)

My SplashScreen class

```
import java.awt.Graphics;

public class SplashScreen extends State {

private int duration;
private boolean running = false;

public SplashScreen(Handler handler) {
    super(handler);

}

@Override
public void render(Graphics g) {
    g.drawImage(Assets.Splash, 0, 0, 1280, 720, null);
}

@Override
public void tick() {
    if(handler.getMouseManager().isMiddlePressed())
        State.setState(handler.getGame().menuState);

}

public void run() {

}

public int getDuration() {
    return duration;
}

public void setDuration(int duration) {
    this.duration = duration;
}

}

```

My State Class(because my splash state extends to this class)

```
import java.awt.Graphics;
import com.vescorspel.game.MyFirstGame.Handler;

public abstract class State {

private static State currentState = null;

public static State setState(State state){
    return currentState = state;
}

public static State getState(){
    return currentState;
}

//CLASS

protected Handler handler;

public State(Handler handler){
    this.handler = handler;
}

public abstract void tick();

public abstract void render(Graphics g);

}

```

# Answer
You could do something simple like:

```
// private variables
private long lastTime = System.getCurrentTimeMillis();
//this is how long it has been running for
private long totalTime = 0;

// Then in the render method
long now = System.getCurrentTimeMillis();
long delta = now - lastTime;
totalTime += delta;
lastTime = now;

//Check if 5 seconds has elapsed
if(totalTime > 5000)
    setState(mainmenu);

```
> 1 votes

---
Tags: java
---


# Question
Title: Bullet physics C# script Is imparting force on rigidbody objects
I have recently made the simplest gun and bullet script that I could and it works amazingly, except for one problem that I've found. When I attach it to a game object with a rigid body the force of the bullets move the object back with quit a bit of force.

But what I can't seem to figure out is why the bullets are imparting force on the object at all. The bullets do not have a rigid body component. The way my guns work is with two scripts, one which acts as a simple spawning point when a key down event is given and what ever object you give it to spawn.

The second script is applied to the bullet itself which causes the bullet to have motion through `transform.Translate` with a speed variable. The best example I can give of this is when I attached two guns to the default unity jet and when I fired, it had enough force to move the jet back against its thrust speed.

I really would appreciate any help with this so I can move on with my project. I will provide the code bellow for the two scripts.

Thank you

```
public class Shoot : MonoBehaviour {
  public GameObject bullet;

  void Update () {
    if (Input.GetKey (KeyCode.Mouse0))
      Instantiate(bullet, transform.position, transform.rotation);
  }
}

```

---

```
public class MoveBullet : MonoBehaviour {

  public float speed = 1f;

  void Update () {
    transform.Translate (0, 0, speed);
  }
}

```

# Answer
your problem happened when merging two Boxcollider: When you attach rigid body to game Object the force of the bullets move the object back with quit a bit of force.

> Adding a Rigidbody component to an object will put its motion under the control of Unity's physics engine. Even without adding any code, a Rigidbody object will be pulled downward by gravity and will react to collisions with incoming objects if the right Collider component is also present.

you should Instantiate bullet in front of gun but you Instantiate it Inside the gun so try this: make a empty game object place it child of gun(in front of gun)

```
using UnityEngine;
using System.Collections;

public class gun : MonoBehaviour {
    public GameObject bullet;
    public Transform ShotPos;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
            Instantiate(bullet, ShotPos.position, transform.rotation);
    }
}

```

other way is making a vector as shotPos:

```
using UnityEngine;
using System.Collections;

public class gun : MonoBehaviour {
    public GameObject bullet;
    public Vector3 ShotPos;

    void Awake()
    {
        ShotPos = transform.position + new Vector3(0, 0, 1);// transform.position + transform.forward
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        Instantiate(bullet, ShotPos, transform.rotation);
    }
}

```
> 1 votes

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


# Question
Title: How can I render a tmx map at a given location?
I am using libgdx & trying to implement a *Binding of Issac* like dungeon. To do this I'm loading a tmx map when a dungeon room is created and rendering it to the screen. The issue is that the each room renders the map in the same place on top of each other. This all boils down to one question: How can I render a map at a specific x,y position, so that I can display the whole dungeon at once?

# Answer
Short answer: ***you can't***. A tiled map is always rendered at (0, 0). The only way to change this would be to implement some sort of hack; perhaps using VBOs to save each room to a texture then render it with an offset.
> -1 votes

---
Tags: java, libgdx, tiled
---


title: Row order in OpenGL DXT texture

text:
# Question
Title: Row order in OpenGL DXT texture
I'm using FreeImage and Squish library. I think there is no matter what row order is passed to `squish::CompressImage` (it's simply like inversed image). FreeImage stores rows from bottom to top, the `pixel(0, 0)` is placed in bottom-left corner. When I put RGBA or DXTn data to glTexImage the data at index 0 should be at top-left corner or at bottom-left corner?

# Answer
glTexImage takes it's data pointer starting from the bottom-left corner: https://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml

> The first element corresponds to the lower left corner of the texture image. Subsequent elements progress left-to-right through the remaining texels in the lowest row of the texture image, and then in successively higher rows of the texture image. The final element corresponds to the upper right corner of the texture image.

*However*, GL texcoords *also* begin from point (0,0) being the bottom-left corner, so the two cancel each other out, and for *most* (but *not all*) purposes you can treat glTexImage as though it started from top-left.

The exceptions are calls such as glTexSubImage, glCopyTexSubImage where you specify a rectangular region in the texture, and so you need to be aware that (0,0) is bottom-left.
> 0 votes

---
Tags: opengl, textures
---


# Question
Title: Parabolic movement of a gameObject in Unity
Currently I'm working on a 3D game. In this game my player is a ball and it can jump from tile to tile. The movement of the ball is 45 degrees left or right when it jumps. I want to make it jump in a parabolic path. But I'm unable to do that. I have used Mecanim, AngleAxis, and lerp as well. But the problem is when I use lerp and animation together, firstly the lerp works then the animation(Jump animation). Basically the ball has a parent and mainly the parent lerps between the tiles and the ball itself has the animation clip attached to it.

Any suggestions or help is appreciated.

# Answer
> 1 votes
Sounds like the problem is being over-complicated; this task can be achieved with Unity's built in physics and minimal amounts of code.

You can add a `Rigidbody` to the platforms and your player, enable `useGravity` on the player, enable `isKinematic` on the platforms, and then your script can simply call `AddForce` on the `Rigidbody` of the player.

You script could be as simple as this:

```
using UnityEngine;
using System.Collections;

public class Jumper : MonoBehaviour {

    public float m_jumpX;
    public float m_jumpY;

    private Rigidbody m_body;

    void Start () {
        m_body = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            m_body.AddForce(new Vector3(m_jumpX, m_jumpY, 0.0f));
        }
    }
}

```

You'll want to make sure they can't jump while they're already in mid-air (which this script doesn't cover) but this should at least get you going in the right direction. If you handle movement like this with Mechanim or manually lerping values, you're going to be in for a mess down the line when you want to adjust seemingly simple things; might as well use the tech Unity has already written for you.

# Answer
> 0 votes
I had done something similar in XVR a year ago, it took me some time to convert it in C# as a component but here it is:

```
public class parable : MonoBehaviour {
    public float ANIMATION_DURATION = 2.0f;
    public float FRAMES_PER_SECOND = 30.0f;
    public GameObject one;
    public GameObject two;
    // Use this for initialization
    void Start () {

    }

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

    }

    void OnDrawGizmos() {
        if(one != null && two != null){
            Gizmos.color = Color.yellow;
            Vector3[] points = parabolicMovement(one.transform.position, two.transform.position);
            foreach(Vector3 point in points){
                Gizmos.DrawSphere( point, .1f);
            }
        }
    }

    public Vector3[] parabolicMovement(Vector3 startingPos, Vector3 arrivingPos)
    {
        int framesNum = (int)(ANIMATION_DURATION * FRAMES_PER_SECOND);
        Vector3[] frames = new Vector3[framesNum];

        //PROJECTING ON Z AXIS
        Vector3 stP = new Vector3(0,startingPos.y,startingPos.z);
        Vector3 arP = new Vector3(0,arrivingPos.y,arrivingPos.z);

        Vector3 diff = new Vector3();

        Vector3 height = new Vector3(0,1,0);
        diff = ((arP-stP)/2) + height;
        Vector3 vertex = stP+diff;

        float x1 = startingPos.z;
        float y1 = startingPos.y;
        float x2 = arrivingPos.z;
        float y2 = arrivingPos.y;
        float x3 = vertex.z;
        float y3 = vertex.y;

        float denom = (x1 - x2)*(x1 - x3)*(x2 - x3);

        var z_dist = (arrivingPos.z - startingPos.z) / framesNum;
        var x_dist = (arrivingPos.x - startingPos.x) / framesNum;

        float A = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom;
        float B = (float)(System.Math.Pow(x3, 2) * (y1 - y2) + System.Math.Pow(x2, 2) * (y3 - y1) + System.Math.Pow(x1, 2) * (y2 - y3)) / denom;
        float C = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denom;

        float newX = startingPos.z;
        float newZ = startingPos.x;

        for(int i = 0; i < framesNum; i++)
        {
            newX += z_dist;
            newZ += x_dist;
            float yToBeFound = A*(newX*newX)+ B*newX + C;
            frames[i] = new Vector3(newZ, yToBeFound, newX);
        }
        return frames;
    }
}

```

The idea behind this is to create a list of subsequential points that, once they get animated, will represent a parabolic movement. The main function here is `parabolicMovement`, taken two positions it creates a list of points (excluding the starting point) which is `(ANIMATION_DURATION * FRAMES_PER_SECOND)` long. The OnDraw Gizmos is there just to show the current result, you can also create an inspector on height by moving its declaration at the top of your component, is something I didn't need at that time. Hope this helps :)

---
Tags: unity, c#, lerp, mecanim
---


# Question
Title: Spawn a prefab at random y position with different gap between prefabs
I have this code, and I want to be able to spawn my Wall prefab at random heights and gaps between the upper wall and wall under it, but it seems that my code will only spawn the wall with same gap between the walls.

```
public GameObject[] wall;
public float spawnMin = 1f;
public float spawnMax = 2f;
public Vector3 posWall = new Vector3(0,-4,0);
public float sizeWall = 1.0f;
private Vector3 dir = Vector3.up;

void Start ()
{
    StartCoroutine(Spawn());
}

IEnumerator Spawn()
{
    while (true)
    {
        GameObject wallTemp = (GameObject)Instantiate(
                wall [Random.Range (0, wall.Length)], posWall, Quaternion.identity);
        //Instantiate (obj [Random.Range (0, obj.Length)], pos, Quaternion.identity);
        posWall += dir * sizeWall;
        yield return new WaitForSeconds(Random.Range (spawnMin, spawnMax));
    }
}

```

I am looking for something like in the following diagram:

How would I go about doing this?

# Answer
> 3 votes
In your update, you describe placing the walls on either side of a room. From your description and diagram, you intend to use random heights for the walls. Instead, I would recommend randomly deciding *if* the wall is going to be placed.

Consider your diagram. In the diagram, you have walls of varying height; but if you consider each *segment* to be a wall, it is the amount of consecutive segments that change, not the actual height of the walls.

---

## The Solution

The script, below, will generate walls randomly as shown in your diagram. Rather than randomly changing the *height* of each wall, I sequentially move to each segment, and use a random number to determine *if* I am going to place a wall. Note that I have included an additional `Editor` class, to allow us to randomly generate the wall from the inspector. This allows us to quickly view multiple iterations.

### WallGenerator

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

public class WallGenerator : MonoBehaviour
{
    /// <summary>The X-Coordinate for the left wall.</summary>
    public float leftWallPosition;
    /// <summary>The X-Coordinate for the right wall.</summary>
    public float rightWallPosition;
    /// <summary>The Y-Coordinate for the wall at the base of the level.</summary>
    public float wallBasePosition;

    /// <summary>The height of each individual floor. Ideally, this value should
    /// match the wall height, to avoid clipping.</summary>
    public float floorHeight;
    /// <summary>The amount of floors in the level.</summary>
    public int floorCount;

    /// <summary>How frequently are walls spawned? At 1, walls should spawn
    /// every time. At 2, walls should spawn roughly half the time. Any negative
    /// number is converted to 1 before use.</summary>
    public int wallFrequency;

    /// <summary>Array of prefab wall pieces to randomly select from.</summary>
    public GameObject[] prefabWall;
    /// <summary>Holds reference to pieces that have already been placed.</summary>
    public List<GameObject> oldWall;

    /// <summary>Generates the wall.</summary>
    public void GenerateWall()
    {
        // Destroy the old wall, if there is one.
        // This is only to allow quick repetition.
        DestroyOldWall();

        // For each floor,
        for (int i = 0; i < floorCount; i++)
        {
            // Spawn a wall at the left position, and spawn a wall at the right position.
            SpawnWall(leftWallPosition, (i * floorHeight));
            SpawnWall(rightWallPosition, (i * floorHeight));
        }
    }

    /// <summary>Spawns a wall piece. May randomly choose not to.</summary>
    /// <param name="xPosition">X position of the wall piece.</param>
    /// <param name="yPosition">Y position of the wall piece.</param>
    void SpawnWall(float xPosition, float yPosition)
    {
        // If wallFrequency is less than one,
        if (wallFrequency < 1)
        {
            // We have a logical issue performing the Random function;
            // Reset wallFrequency to one, walls should always spawn.
            wallFrequency = 1;
        }

        // Find a random number between zero and wallFrequency,
        // and if that number is zero,
        if(Random.Range(0, wallFrequency) == 0)
        {
            // Load a random wall piece from the prefabWall, and determine the position.
            GameObject wallPiece = prefabWall[Random.Range(0, prefabWall.Length)];
            Vector3 position = new Vector3(xPosition, yPosition, 0);

            // Instantiate the wall piece, and load it in to the oldWall list.
            wallPiece = (GameObject)Instantiate(wallPiece, position, Quaternion.identity);
            oldWall.Add(wallPiece);
        }
    }

    /// <summary>Checks if a wall already exists,
    /// and destroys it immediately, if it does.</summary>
    void DestroyOldWall()
    {
        // If the old wall list is not empty,
        if (oldWall.Count > 0)
        {
            // for each wall object in the old wall list,
            for (int i = 0; i < oldWall.Count; i++)
            {
                // destroy the wall piece immediately,
                // so it will take effect in the editor.
                DestroyImmediate(oldWall[i]);
            }

            // Clear out the old wall list.
            oldWall.Clear();
        }
    }
}

/// <summary>Custom editor to allow us to trigger the GenerateWall.</summary>
[CustomEditor(typeof(WallGenerator))]
public class WallGeneratorEditor : Editor
{

    /// <summary>Calls on drawing the GUI for the inspector.</summary>
    public override void OnInspectorGUI()
    {
        // Draw the default inspector.
        DrawDefaultInspector();

        // Grab a reference to the target script, so we can identify it as a
        // WallGenerator, instead of a simple Object.
        WallGenerator wallGenerator = (WallGenerator)target;

        // Create a Button for "Generate Wall"
        if(GUILayout.Button("Generate Wall"))
        {
            // if it is clicked, call the GenerateWall method from WallGenerator.
            wallGenerator.GenerateWall();
        }
    }
}

```

### WallGenerator in Action

Below, you can see `WallGenerator` generating walls, where `wallFrequency == 0`, `wallFrequency == 1`, `wallFrequency == 2`, and `wallFrequency == 10`. As you can see, the lower frequency reliably builds an entire wall, where a frequency of 2+ randomly skips.

---

## Considerations

### The Dimensions of the Building

Given that the walls are all being placed using a script, it is essential that you provide the correct values relative to your building. It would be a good idea to generate your wall a couple of times, in the editor, to visually confirm that the walls are being placed correctly.

Note that if you increase the value of `floorCount`, the walls will potentially build higher. You might manipulate this variable to place walls on the roof, for example.

### The Wall Piece

It is important to have reliable wall pieces, when using the above script. For example, it is assumed that the point of origin will be the base of the wall. If you simply scaled out a cube, the point of origin would be in the center, and cause your walls to spawn in the ceiling.

The best way to solve this problem, and to keep everything neat, is to simply create a separate point of origin. Place a cube at the center base of your wall, and parent your actual wall piece to it. Now, your wall will spawn at the base. You can remove everything from the base cube, apart from the transform.

---
Tags: unity, c#, random, spawning
---


# Question
Title: No intellisense with with Unity 5.5, Visual Studio Code integration, OSX 10.12.1
I get this with the listed software. It doesn't recognize object types and I can't use reference-finding. I have the Omnisharp plugin installed and updated. Just wondering if this is supposed to work properly yet. I'm opening it with Assets-\>Open Project In Code.

# Answer
In the .csproj file, there's this:

```
<Reference Include="UnityEngine">
  <HintPath>/Applications/Unity 5.5.0f3/Unity.app/Contents/Managed/UnityEngine.dll</HintPath>
</Reference>

```

Note the space in the file path. Changing Unity's location to

`/Applications/Unity5.5.0f3`

then deleting the generated `.sln` and `.csproj` files fixed it.
> 0 votes

---
Tags: unity, visual-studio-code
---


# Question
Title: How to Reciprocally draw on a 3D mesh and 2D UI Image in Unity?
My question is a bit involved so I'm going to split it into parts and attach a picture.

1) In Unity I'd like to be able to draw a line on a 3D worldspace mesh with the mouse.

2) As I'm drawing on the 3D worldspace mesh, I need to have a 2D UI Image component that represents the same 3D worldspace mesh surface. The UI Image component needs to show the line drawing update in real-time on the UI.

3) I need to be able to also draw a line on the 2D UI Image component and have the line show up on the 3D worldspace mesh.

Currently, I have implemented part 1 by using raycasting and drawing my line on the world coordinates of the returned raycasthit. This works great.

Now, I'm a little at a loss as how to correctly map the world coordinates of the line to the 2D UI Image component's coordinates. I know if I can figure out how to complete step 2, step 3 would simply be reversing the process for step 2.

Here's a picture visualizing what I'm trying to achieve:

# Answer
Unfortunately I cannot serve you with code, but hopefully with some hints:

For 1: First you need the coordinate of the mouse on the texture which surrounds this 3D mesh. You can use the Unity's ray class and send one from the camera origin towards the mouse and therefore detect where it collides with the mesh. Once you have that coordinate you should be able to transform it into the texture coordinate as you know the transformation of the mesh and you also know the UV coordinates of the texture on the mesh (assuming that you assigned those yourself).

The you can use the Texture2d class which has functions like setPixel to modify or replace the texture (google for "unity modify texture runtime" for more information).

2. Just asign the Texture (which is part of the material) of the 3D mesh onto some GUI element. If I'm not wrong it will actually change both at the same time this way because what you asign is just a reference to the actual texture which is handled by Unity. Otherwise just copy it after every change.

3. Again if you draw onto the 2d representation, the 3D representation will be modifed as well: Question is, is the 3D mesh actually some strange, perhaps even concave figure? If so, how do you actually want its surface to look like in 2D? Because the user wouldn't really expect the 3D result if he draws in 2D. Or is the 3D mesh just a plain, flat wall (like in your picture)? If so, the method I describe should work well. A cube would probably work too if you display the edges onto the 2D representation as a guidance for the user. Curved figures wouldn't really make sense.

Good luck!
> 1 votes

# Answer
I have a basic solution for Step 2, but it's not reversible for Step 3.

Simply make a isometric camera and make the display at the bottom of the view

Creating an Isometric Camera in Unity
2 cameras renderring at the same time

Another method (my imagination) is make the Line Drawing to "modify" the material of the mesh, and then use the same material on the 2D UI Image. Hence when the material is changed, both the Mesh and the Image will change their materials too.
> 0 votes

---
Tags: unity, gui, image, raycasting, decal-system
---


title: Load nextLevel with a button click

text:
# Question
Title: Load nextLevel with a button click
Can anyone help me someone with this code?

I'd like to go to the next level by clicking a button: example my level name is L1,L2,L3,L4,L5,L6,L7 and when I finish level L1, I want to go to level L2 with the click of a button, and from L5 go to L6 like this.

```
public class GameLevels : MonoBehaviour {

 public Button Play;
 private int idLevel;
 // Use this for initialization
 void Start ()
 {
     idLevel = PlayerPrefs.GetInt("idLevel");
     Play.interactable = false;
 }
 public void SelectLevel(int i){
     idLevel = i;
     PlayerPrefs.SetInt ("idLevel", idLevel);
     Play.interactable = true;
 }

 public void LoadLevel(string Levels)
 {
     SceneManager.LoadScene (Levels);
 }
 public void Replay()
 {
     SceneManager.LoadScene ("L" + idLevel.ToString ());
 }
 public void loadNextLevel()
 {

 }
}

```

# Answer
If this is the Replay button and it works (As we don't have the full code, I'm not sure if it works but I'm assuming it does):

```
public void Replay()
{
    SceneManager.LoadScene ("L" + idLevel.ToString ());
}

```

Then it stands to reason that the following should be the next level's code:

```
public void loadNextLevel()
{
PlayerPrefs.SetInt("idLevel", idLevel+1);
SceneManager.LoadScene ("L" + (idLevel+1).ToString ());
}

```

Since idLevel is declared as an int, you can just add 1 and then turn it into a string.

You can also do this (when you load the next level, idLevel will be reset if I'm not mistaken, so it should be safe to do it this way too):

```
public void loadNextLevel()
{
idLevel++;
PlayerPrefs.SetInt("idLevel", idLevel);
SceneManager.LoadScene ("L" + idLevel.ToString ());
}

```

P.S. You shouldn't have to turn it into a string because when you add an int to a string, it will also act as a string. Just make sure you do the math before the string addition, so don't forget to use the parentheses where we do `(idLevel+1)`. So, `SceneManager.LoadScene ("L" + (idLevel+1));` should also work.
> 1 votes

# Answer
try the simple code. it ll solve your problem

//to reload the Level

```
public void Replay(){
    Application.LoadLevel (Application.loadedLevel);
}

```

//To load next level

```
public void NxtLevel(){
    Application.LoadLevel (Application.loadedLevel + 1);
}

```

this ll load the level by using level id. Located in build settings -\> Scenes in build.
> 2 votes

# Answer
Its may look like this :

```
 public class GameLevels : MonoBehaviour {

 public Button Play;
 private int idLevel;
 // Use this for initialization
 void Start ()
 {
     idLevel = PlayerPrefs.GetInt("idLevel");
     Play.interactable = false;
 }
 public void SelectLevel(int i){
     idLevel = i;
     PlayerPrefs.SetInt ("idLevel", idLevel);
     Play.interactable = true;
 }

 public void LoadLevel(string Levels)
 {
     SceneManager.LoadScene (Levels);
 }
 public void Replay()
 {
     SceneManager.LoadScene ("L" + idLevel.ToString ());
 }
 public void loadNextLevel()
 {
  int idLevelSecond = PlayerPrefs.GetInt("idLevel");
  string thelevelnumber = idLevelSecond.ToString();
  string leveltoload = "L" + thelevelnumber;
  Debug.Log(leveltoload);
  SceneManager.LoadScene(leveltoload);
 }
}

```

**UNTESTED !** if the code did not work, tell me.
> -3 votes

---
Tags: unity, scenemanager
---


title: How do you add AdMob to LibGDX game?

text:
# Question
Title: How do you add AdMob to LibGDX game?
Im currently trying to implements AdMob into my libgdx game, but it seems that all tutorials are deprecated.

For example in the offical libgdx wiki the google play services get imported into eclipse, but google split the google play services up. Also I need to implement Firebase to the game (u need to now), but it doesnt say anything about that either. I also looked at the offical tutorials for Android Studio, but doing it in LibGDX doesnt seem to work (Cant resolve AdView).

All help is appreciated, thanks.

# Answer
1. Sign in the "firebase"
2. Go to My Projects page (if you have not, create new one then)
3. Click "Add firebase to your Android app" icon
4. Fill the necessary blank.
    * Copy and paste your app' packagename
    * Copy and paste your app' SHA1 signing
5. Move the google-play-services.json file (which will automatically donwload) to your project \> **app** directory .
6. Go your **project's** build.gradle file and paste the classpath line to your dependencies. (which google will give you like "classpath 'com.google.gms:google-services:3.0.0")
7. Go your **app** build.gradle file and paste the line compile 'com.google.firebase:firebase-core:10.0.1' to your dependencies.
8. Go your **app** build.gradle file and paste the apply-plugin line to bottom of file. (apply plugin: 'com.google.gms.google-services')
9. Finally click the sync now.

**NOTE** : Don't forget the use most recent versions. Check the link below.

https://firebase.google.com/docs/android/setup
> 1 votes

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


# Question
Title: How to store variables in between scenes? Unity
How would that be possible, and would I be able to access them from anywhere?

# Answer
There are multiple ways to go about this. One of them is by using PlayerPrefs, just save it in there (with Set commands) and get it later.

Make an object that doesn't get destroyed and set a static variable in that object. (This part is only known to me in C#, not specific to Unity.) Add the following script (or any other script that has a public static variable) to an object that will not be destroyed between levels (`DontDestroyOnLoad` call). This will, of course, get rid of the object if the player exits the game so it won't save it between sessions (only between level loads). (You can access the variable with `scriptName.variableName`, in the example's case `StaticVariableHolder.myStaticInt`, from any other script or object in the game):

```
public class StaticVariableHolder : MonoBehaviour {

 public static int myStaticInt;
 void Start ()
 {
     DontDestroyOnLoad(gameObject);
 }
}

```

Make a public variable on an object that won't be destroyed then access that by finding that object later on:

```
public class StaticVariableHolder : MonoBehaviour {

 public int myStaticInt;
 void Start ()
 {
     DontDestroyOnLoad(gameObject);
 }
}

```

Now in this case you need the other object's script to have these lines:

```
public class OtherScript : MonoBehaviour {
//this is the variable your
//gameobject with the script will be set to.
 GameObject myCarrierObject;

 void Start ()
 {
    myCarrierObject = GameObject.Find("persistentObject");
    int myStaticInt = myCarrierObject.GetComponent<StaticVariableHolder>().myStaticInt
 }
}

```

Now, only the objects that has these lines will be able to access the object and its variables (not the last line where I set the int variable) so you have to make sure, you find the object with every other script that needs it. This makes the variable more protected but less accessible.
> 2 votes

---
Tags: unity
---


title: S3TC / DTXn patents

text:
# Question
Title: S3TC / DTXn patents
I just wrote a **DTXn** loader in my OpenGL engine to support **.dds** files (i.e. via `glCompressedTexImage2D`) and generally employ *texture compression in GPU*.

I've also found that using **S3TC** leads to patent issues. I've done some searching and found that on wikipedia:

```
The patent on S3 Texture Compression expires on October 2, 2017.

```

Does this message means that in about 1 year S3TC algorithms could be open-sourced without patents and could be used freely and should just wait?

# Answer
> 2 votes
That patents shouldn't touch you (as mere user of OpenGL api) at all, unless you're writing own OpenGL/D3D implementations and adding texture compression support there. Then you'll have to pay attention.

---
Tags: opengl, textures, dds, patents
---


# Question
Title: Video playback on mobile: can't seek to the end
My Unity3D game needs to play videos on mobile devices (using `Handheld.PlayFullscreenMovie()`). Seeking works badly. If I tap the video progress bar near the end (expecting it to play the last second then finish), playback jumps back a full 10-20 seconds, depending on the video. What should I try to make it easier for the player to seek within the file? Force additional key frames?

I'm currently encoding with HandbrakeCLI and the following settings:

```
--preset="AppleTV" --x264-tune=animation --x264-preset=veryslow

```

# Answer
> 1 votes
If you're using x264 encoding, your most likely problem is keyframes\*. See this link and search for keyframe (it's the first thing there). Of course, you're not using FFmpeg, so you need the options for HandbrakeCLI, which seems to be "-x" command (a.k.a. --encopts) which receives a string, detailed here. Try those options out.

(`--encopts "keyint=60"` sets the maximum GOP size to 60 frames, which should make (at least) every 2 seconds searchable for a 30FPS video but that would also mean much lower compression)

*Keyframes are used for compression and you can only search between keyframes in a x264 compression (Jump from one keyframe to another). It is most likely a really high number by default for extreme compression.

---
Tags: unity, mobile, video
---


# Question
Title: C++ OpenGL Basic Binary Object File Loader
I have looked around for a in-depth explanation on what is a binary file (For a Opengl Object), how to make them and also how to load them, but I can't find many references... Can someone point me in the right direction?

EDIT. I'm wanting to load a models vertex positions from a file. I currently am using obj but I want to use something faster, such as binary files.

# Answer
If you want to load models from a binary file format, you need to implements a special loader for that specific binary format. For example .3ds is/was used quite often in the past. The problem, however, is the lack of a full documentation of the format, as the specifics are not released, just reverse engineered.

A format with full ASCII/Binary documentation for example is Collada which was designed as an exchange format.

If you want to load a couple of objects and learn some basics, stick with Wavefront Object (.obj) as you can easily manipulate it with a simple text editor.

Oh an last, but not least, loading geometry, textures, effects or anything else has nothing to do with OpenGL (or DirectX for that matter).

If you still want to load binary files, you can take a look at this tutorial.
> 1 votes

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


# Question
Title: How to rotate a surface in pygame, without changing its shape
I'm writing a class in pygame to create a sprite object, and I'd like to be able to rotate it. It works fine with an image, and rotates without issue. But when rotating a surface with a plain colour, the box appears to grow and shrink. I know that this is a result of the surface changing size to fit the vertices of the rectangle inside, but how do I stop it? I'd like to see a visual rotation.

I've created some sample code to show the problem that I'm facing, running it causes the box to simply change in size.

```
import sys, pygame
from pygame.locals import *

pygame.init()
SCREEN = pygame.display.set_mode((200, 200))
CLOCK  = pygame.time.Clock()

surface = pygame.Surface((50 , 50))
surface.fill((0, 0, 0))
rotated_surface = surface
rect = surface.get_rect()
angle = 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    SCREEN.fill((255, 255, 255))
    angle += 5
    rotated_surface = pygame.transform.rotate(surface, angle)
    rect = rotated_surface.get_rect(center = (100, 100))
    SCREEN.blit(rotated_surface, (rect.x, rect.y))

    pygame.display.update()
    CLOCK.tick(30)

```

How do I fix this issue, to make the surface rotate how I want?

Any help would be appreciated!

# Answer
After looking around a bit more, I found an answer to my question. To solve the problem experienced, you need to give the surface an alpha value. This can easily accomplished by replacing the line:

```
surface = pygame.Surface((50, 50))

```

With the line:

```
surface = pygame.Surface((50, 50), pygame.SRCALPHA)

```
> 1 votes

---
Tags: rotation, software-engineering, python, pygame
---


# Question
Title: Is there a gl*TexStorage* equivalent to glCompressedTexImage*
I have been using gl*TexImage* functions to create textures and then heard of glTexStorage\* that is supposed to be better and is introduced in the latest standards.

But the problem is that I can't seem to find an equivalent to glCompressedTexImage2D(...) in terms of gl\*TexStorage.

I've only found 2 references on an IRC chat to these supposedly equivalent functions while searching. (here and here)

Do these equivalent functions even exist ? And if they don't, why don't they exist ?

Thanks for any help

# Answer
> 0 votes
It seems glTexStorage\* functions do support compressed formats just by specifying the correct "internal format" parameter, i.e. there is a list of flags (GL\_COMPRESSED\_RGB\_S3TC\_DXT1\_EXT, etc...) that handle such compressed textures. You can find the list here.

---
Tags: opengl, textures
---


# Question
Title: Sprite Image in Canvas not displaying correctly (distorted)
I have a problem with displaying images in my Canvas, as they're not displaying exactly like the imported image.

In the image below, the sprite on the left is how it looks when it's imported. The sprite on the right is how it looks in the canvas. Notice that some of the pixels have incorrect colours, like the lighter pink in the center of the staff's top is gone, the eyeball is a darker shade, some of the colouration under the hood is wrong, and other errors.

( The sprite is just a test I took from somewhere else, not what I intend to use as a final product. )

The project is 3D (going for a 2.5D look with billboard sprites) set to 384x224 resolution, orthographic camera size of 3.5, no anistropic textures, no anti-aliasing.

Is there some setting I missed somewhere to ensure that images display 100% exact like the source sprite when used in the Canvas?

EDIT Sprite in the Inspector (Seems to also not be correct)

EDIT Added entire inspector

# Answer
> 0 votes
Likely scenarios that would make this happen: Wrong import settings, 3D lights affecting the supposedly 2D object, non-pixel perfect canvas.

I'd say, try checking the box that says Pixel Perfect on the canvas. That should fix it. If not, check your import settings, make sure there's no compression. If that's not the problem then it should be the lights affecting your 2D object (not sure if it's even possible) try removing all lighting from scene.

Report back with your findings, I'm curious to see what the problem is.

Edit: Problem is the compression.

Compression on Normal Quality:  Compression on High Quality:  Compression on None:

---
Tags: unity
---


# Question
Title: How can I spawn particles around a point but inside a box?
There are particles in a box, the black circle representing the spawn point and the red circle representing the particles.

How could I spawn them so they don't spawn outside the box, and so that they are at an exact distance away from the spawn point and particles can slightly overlap.

Here is an example of what I'm trying to do:

# Answer
You can pick a random location an exact distance away from the spawn point, first pick a random angle, find the x & y components of that angle, scale out by the desired distance & add the results to the spawn point to get the new coord:

```
double spawnDistance = 10;
Point.Double spawnPoint = new Point.Double(15, 17);
Random rng = new Random();
double value = rng.nextDouble();
double dx = Math.cos(value*Math.PI*2) * spawnDistance;
double dy = Math.sin(value*Math.PI*2) * spawnDistance;
Point.Double randomSpawn = new Point.Double(spawnPoint.x+dx, spawnPoint.y+dy);
}

```

To make sure the newest spawn point doesn't clip the boundary, test that its center is at least as far away from the boundary edges as the size of its radius:

```
boolean clippedByBoundary = (randomSpawn.x - radius < minBoundary.x ||
                             randomSpawn.y - radius < minBoundary.y ||
                             randomSpawn.x + radius > maxBoundary.x ||
                             randomSpawn.y + radius > maxBoundary.y);
// check clippedByBoundary & do whatever

```

To prevent the newest spawn point from overlapping other spawn points by too much, you'll need to check that it isn't too close to any other point generated thus far:

```
boolean isTooClose = false;
for(Point.Double pt : spawnPointList){
   if(pt.distance(randomSpawn) < maxOverlap){
     isTooClose = true;
     break;
   }
}
// check isTooClose & whatever you need based on the result

```

Note: the code above could be sped up a bit by checking squared distances instead of actual distances. Also, my solution has a bias for picking locations closer to the center of the spawn area. Uniform disk picking requires a couple more square root calculations:

```
double dx = Math.cos(value*Math.PI*2) * Math.sqrt(spawnDistance);
double dy = Math.sin(value*Math.PI*2) * Math.sqrt(spawnDistance);

```

Alternatively, you could also create a random 2D vector & normalize/scale it as needed (as suggested in comments by @Bálint).

For the convenience of answering, I put the test results in variables; you'll probably want to just use the tests directly in line or possibly as method calls depending on your situation. Since testing for edge clipping is cheaper, I would do that before checking for edge overlaps. If you need to generate many points, looping to check for overlap might prove to be a bit of a bottleneck - if that's the case, you might want to use a Poisson distribution placement scheme instead.
> 1 votes

---
Tags: java, libgdx, particles, spawning
---